Skip to main content

cranpose_services/
launcher.rs

1//! Composition-owned launchers for the system choosers.
2//!
3//! A launcher is remembered under a stable **request key**, presents a system
4//! chooser when the application calls `launch`, and delivers the result to the
5//! composition through a callback. The framework — not the application — owns
6//! the awkward part: Android may destroy the activity, and with it the whole
7//! composition, while the chooser is in front. The launcher records which
8//! request is in flight, the platform backend records the granted selection,
9//! and the launcher that recomposes under the same key receives the result.
10//! Applications never poll an inbox, never drain a resume queue, and never
11//! write a marker file.
12//!
13//! ```rust,no_run
14//! use cranpose_macros::composable;
15//! use cranpose_services::{launcher::rememberOpenFileLauncher, FilePickerOptions};
16//!
17//! #[composable]
18//! fn ImportButton() {
19//!     let launcher = rememberOpenFileLauncher("import.document", |picked| {
20//!         if let Ok(Some(content)) = picked {
21//!             log::info!("picked {}", content.metadata().name);
22//!         }
23//!     });
24//!     launcher.launch(FilePickerOptions::default().with_title("Import"));
25//! }
26//! ```
27
28use std::{
29    cell::{Cell, RefCell},
30    collections::HashMap,
31    future::Future,
32    rc::Rc,
33};
34
35use cranpose_core::{current_runtime_handle, RuntimeHandle};
36use cranpose_macros::composable;
37
38use crate::{
39    content::{ContentFolderRef, ContentHandle, ContentSinkRef},
40    file_picker::{
41        local_file_picker, FilePickerError, FilePickerOptions, FilePickerRef, RecoveredPick,
42        SaveDocumentRequest,
43    },
44    preferences::preferences,
45};
46
47/// What a launcher hands back once the chooser resolves.
48///
49/// Cancellation is `Ok` with an empty selection, not an error: the user
50/// declining is an outcome, not a failure.
51pub type LauncherResult<T> = Result<T, FilePickerError>;
52
53thread_local! {
54    /// Results the host recovered after their requesting composition was
55    /// destroyed, keyed by the request key that asked for them.
56    static RECOVERED: RefCell<HashMap<String, RecoveredPick>> = RefCell::new(HashMap::new());
57    /// The request key of the chooser currently in flight, if any. At most one
58    /// system chooser can be in front, so one slot is enough.
59    static IN_FLIGHT: RefCell<Option<String>> = const { RefCell::new(None) };
60    /// Request keys with a live launcher, so duplicates are caught in debug.
61    static REGISTERED_KEYS: RefCell<HashMap<String, usize>> = RefCell::new(HashMap::new());
62}
63
64/// Where the in-flight request key is kept so it outlives the process.
65///
66/// The in-memory slot covers a composition being torn down. It does not cover
67/// the process being killed, which is the case Android actually presents: the
68/// system may destroy an application outright while its chooser is in front,
69/// and the grant then arrives to a process that has forgotten it asked. An
70/// application that wanted to survive that had to write its own marker file
71/// beside its data and read it back on the next start — which is the framework
72/// doing half a job and leaving the awkward half to every application.
73const IN_FLIGHT_PREFERENCE: &str = "cranpose.launcher.in-flight";
74
75/// Records that `request_key` launched a chooser. Called before presenting so a
76/// host recreation — or a restart after the process was killed — can attribute
77/// the recovered result.
78fn begin_request(request_key: &str) {
79    IN_FLIGHT.with(|slot| *slot.borrow_mut() = Some(request_key.to_string()));
80    // Written before the chooser is presented, so a process killed while it is
81    // in front still leaves the record behind.
82    let _ = preferences().set(IN_FLIGHT_PREFERENCE, request_key);
83}
84
85/// Clears the in-flight record once the chooser resolves in this process.
86fn finish_request(request_key: &str) {
87    IN_FLIGHT.with(|slot| {
88        let mut slot = slot.borrow_mut();
89        if slot.as_deref() == Some(request_key) {
90            *slot = None;
91        }
92    });
93    if preferences().get(IN_FLIGHT_PREFERENCE).as_deref() == Some(request_key) {
94        let _ = preferences().remove(IN_FLIGHT_PREFERENCE);
95    }
96}
97
98/// The request that was in flight, from this process or the one before it.
99fn in_flight_request() -> Option<String> {
100    IN_FLIGHT
101        .with(|slot| slot.borrow().clone())
102        .or_else(|| preferences().get(IN_FLIGHT_PREFERENCE))
103}
104
105/// Moves anything the platform recovered into the keyed inbox. Called whenever a
106/// launcher composes, which is the first moment a recreated composition can take
107/// delivery.
108fn drain_recovered(picker: &FilePickerRef) {
109    while let Some(pick) = picker.take_recovered_pick() {
110        let Some(key) = in_flight_request() else {
111            log::warn!("cranpose: a recovered pick arrived with no request in flight; dropping it");
112            continue;
113        };
114        RECOVERED.with(|inbox| inbox.borrow_mut().insert(key, pick));
115    }
116}
117
118/// Takes the recovered result addressed to `request_key`, if any.
119fn take_recovered(request_key: &str) -> Option<RecoveredPick> {
120    let recovered = RECOVERED.with(|inbox| inbox.borrow_mut().remove(request_key));
121    if recovered.is_some() {
122        finish_request(request_key);
123    }
124    recovered
125}
126
127/// Discards every framework-owned launcher record. Used by tests and by host
128/// teardown so one composition's in-flight request never leaks into the next.
129pub fn clear_launcher_state() {
130    RECOVERED.with(|inbox| inbox.borrow_mut().clear());
131    IN_FLIGHT.with(|slot| *slot.borrow_mut() = None);
132    REGISTERED_KEYS.with(|keys| keys.borrow_mut().clear());
133}
134
135/// Shared state behind every launcher: the picker, the runtime that runs the
136/// chooser future, and whether a request is outstanding.
137struct LauncherCore {
138    request_key: String,
139    picker: FilePickerRef,
140    runtime: Option<RuntimeHandle>,
141    in_flight: Cell<bool>,
142}
143
144impl LauncherCore {
145    fn spawn(self: &Rc<Self>, future: impl Future<Output = ()> + 'static) {
146        let Some(runtime) = self.runtime.clone() else {
147            log::warn!(
148                "cranpose: launcher `{}` has no runtime; the chooser was not presented",
149                self.request_key
150            );
151            self.in_flight.set(false);
152            finish_request(&self.request_key);
153            return;
154        };
155        if runtime.spawn_ui(future).is_none() {
156            log::warn!(
157                "cranpose: launcher `{}` outlived its runtime; the chooser was not presented",
158                self.request_key
159            );
160            self.in_flight.set(false);
161            finish_request(&self.request_key);
162        }
163    }
164
165    /// Marks a request as starting, refusing to present a second chooser while
166    /// one is already in front.
167    fn begin(self: &Rc<Self>) -> bool {
168        if self.in_flight.get() {
169            return false;
170        }
171        self.in_flight.set(true);
172        begin_request(&self.request_key);
173        true
174    }
175
176    fn end(self: &Rc<Self>) {
177        self.in_flight.set(false);
178        finish_request(&self.request_key);
179    }
180}
181
182/// Registration guard: keeps the duplicate-key check honest across recomposition
183/// and removes the key when the launcher leaves the composition.
184struct KeyRegistration {
185    request_key: String,
186}
187
188impl KeyRegistration {
189    fn new(request_key: &str) -> Self {
190        REGISTERED_KEYS.with(|keys| {
191            let mut keys = keys.borrow_mut();
192            let count = keys.entry(request_key.to_string()).or_insert(0);
193            *count += 1;
194            debug_assert!(
195                *count == 1,
196                "launcher request key `{request_key}` is registered {count} times; \
197                 keys must be unique so a recovered result reaches the right launcher"
198            );
199        });
200        Self {
201            request_key: request_key.to_string(),
202        }
203    }
204}
205
206impl Drop for KeyRegistration {
207    fn drop(&mut self) {
208        REGISTERED_KEYS.with(|keys| {
209            let mut keys = keys.borrow_mut();
210            if let Some(count) = keys.get_mut(&self.request_key) {
211                *count -= 1;
212                if *count == 0 {
213                    keys.remove(&self.request_key);
214                }
215            }
216        });
217    }
218}
219
220/// Everything a remembered launcher owns for one request key.
221struct LauncherSlot {
222    core: Rc<LauncherCore>,
223    _registration: KeyRegistration,
224}
225
226/// Remembers a launcher core for `request_key`, draining anything the host
227/// recovered for it and handing it to `deliver`.
228fn remember_core(
229    request_key: &'static str,
230    deliver: impl FnOnce(RecoveredPick) + 'static,
231) -> Rc<LauncherCore> {
232    let picker = local_file_picker().current();
233    let slot = cranpose_core::remember({
234        let picker = picker.clone();
235        let request_key = request_key.to_string();
236        move || LauncherSlot {
237            core: Rc::new(LauncherCore {
238                request_key: request_key.clone(),
239                picker,
240                runtime: current_runtime_handle(),
241                in_flight: Cell::new(false),
242            }),
243            _registration: KeyRegistration::new(&request_key),
244        }
245    });
246    let core = slot.with(|slot| Rc::clone(&slot.core));
247
248    drain_recovered(&picker);
249    if let Some(recovered) = take_recovered(request_key) {
250        let core = Rc::clone(&core);
251        cranpose_core::SideEffect(move || {
252            core.end();
253            deliver(recovered);
254        });
255    }
256    core
257}
258
259/// Presents the single-file chooser and hands the picked content back.
260#[derive(Clone)]
261pub struct OpenFileLauncher {
262    core: Rc<LauncherCore>,
263    on_result: Rc<dyn Fn(LauncherResult<Option<ContentHandle>>)>,
264}
265
266impl OpenFileLauncher {
267    /// Presents the chooser. A second call while one is in front is ignored.
268    pub fn launch(&self, options: FilePickerOptions) {
269        if !self.core.begin() {
270            return;
271        }
272        let core = Rc::clone(&self.core);
273        let done = Rc::clone(&self.core);
274        let on_result = Rc::clone(&self.on_result);
275        let future = core.picker.pick_file(options);
276        core.spawn(async move {
277            let result = future.await;
278            done.end();
279            on_result(result);
280        });
281    }
282
283    /// Whether a chooser presented by this launcher is still in front.
284    pub fn is_in_flight(&self) -> bool {
285        self.core.in_flight.get()
286    }
287}
288
289/// Remembers a single-file launcher under `request_key`.
290#[allow(non_snake_case)]
291#[composable]
292pub fn rememberOpenFileLauncher(
293    request_key: &'static str,
294    on_result: impl Fn(LauncherResult<Option<ContentHandle>>) + 'static,
295) -> OpenFileLauncher {
296    let on_result: Rc<dyn Fn(LauncherResult<Option<ContentHandle>>)> = Rc::new(on_result);
297    let core = remember_core(request_key, {
298        let on_result = Rc::clone(&on_result);
299        move |recovered| match recovered {
300            RecoveredPick::File(content) => on_result(Ok(Some(content))),
301            RecoveredPick::Files(mut files) => on_result(Ok(files.drain(..).next())),
302            _ => log::warn!("cranpose: `{request_key}` recovered a pick of another kind"),
303        }
304    });
305    OpenFileLauncher { core, on_result }
306}
307
308/// Presents the multi-file chooser and hands every picked item back.
309#[derive(Clone)]
310pub struct OpenFilesLauncher {
311    core: Rc<LauncherCore>,
312    on_result: Rc<dyn Fn(LauncherResult<Vec<ContentHandle>>)>,
313}
314
315impl OpenFilesLauncher {
316    /// Presents the chooser. A second call while one is in front is ignored.
317    pub fn launch(&self, options: FilePickerOptions) {
318        if !self.core.begin() {
319            return;
320        }
321        let core = Rc::clone(&self.core);
322        let done = Rc::clone(&self.core);
323        let on_result = Rc::clone(&self.on_result);
324        let future = core.picker.pick_files(options);
325        core.spawn(async move {
326            let result = future.await;
327            done.end();
328            on_result(result);
329        });
330    }
331
332    /// Whether a chooser presented by this launcher is still in front.
333    pub fn is_in_flight(&self) -> bool {
334        self.core.in_flight.get()
335    }
336}
337
338/// Remembers a multi-file launcher under `request_key`.
339#[allow(non_snake_case)]
340#[composable]
341pub fn rememberOpenFilesLauncher(
342    request_key: &'static str,
343    on_result: impl Fn(LauncherResult<Vec<ContentHandle>>) + 'static,
344) -> OpenFilesLauncher {
345    let on_result: Rc<dyn Fn(LauncherResult<Vec<ContentHandle>>)> = Rc::new(on_result);
346    let core = remember_core(request_key, {
347        let on_result = Rc::clone(&on_result);
348        move |recovered| match recovered {
349            RecoveredPick::Files(files) => on_result(Ok(files)),
350            RecoveredPick::File(content) => on_result(Ok(vec![content])),
351            _ => log::warn!("cranpose: `{request_key}` recovered a pick of another kind"),
352        }
353    });
354    OpenFilesLauncher { core, on_result }
355}
356
357/// Presents the folder chooser and hands the granted folder back.
358#[derive(Clone)]
359pub struct OpenFolderLauncher {
360    core: Rc<LauncherCore>,
361    on_result: Rc<dyn Fn(LauncherResult<Option<ContentFolderRef>>)>,
362}
363
364impl OpenFolderLauncher {
365    /// Presents the chooser. A second call while one is in front is ignored.
366    pub fn launch(&self, options: FilePickerOptions) {
367        if !self.core.begin() {
368            return;
369        }
370        let core = Rc::clone(&self.core);
371        let done = Rc::clone(&self.core);
372        let on_result = Rc::clone(&self.on_result);
373        let future = core.picker.pick_folder(options);
374        core.spawn(async move {
375            let result = future.await;
376            done.end();
377            on_result(result);
378        });
379    }
380
381    /// Whether a chooser presented by this launcher is still in front.
382    pub fn is_in_flight(&self) -> bool {
383        self.core.in_flight.get()
384    }
385}
386
387/// Remembers a folder launcher under `request_key`.
388#[allow(non_snake_case)]
389#[composable]
390pub fn rememberOpenFolderLauncher(
391    request_key: &'static str,
392    on_result: impl Fn(LauncherResult<Option<ContentFolderRef>>) + 'static,
393) -> OpenFolderLauncher {
394    let on_result: Rc<dyn Fn(LauncherResult<Option<ContentFolderRef>>)> = Rc::new(on_result);
395    let core = remember_core(request_key, {
396        let on_result = Rc::clone(&on_result);
397        move |recovered| match recovered {
398            RecoveredPick::Folder(folder) => on_result(Ok(Some(folder))),
399            _ => log::warn!("cranpose: `{request_key}` recovered a pick of another kind"),
400        }
401    });
402    OpenFolderLauncher { core, on_result }
403}
404
405/// Presents the save-document chooser and hands the opened sink back.
406#[derive(Clone)]
407pub struct SaveDocumentLauncher {
408    core: Rc<LauncherCore>,
409    on_result: Rc<dyn Fn(LauncherResult<Option<ContentSinkRef>>)>,
410}
411
412impl SaveDocumentLauncher {
413    /// Presents the chooser. A second call while one is in front is ignored.
414    pub fn launch(&self, request: SaveDocumentRequest) {
415        if !self.core.begin() {
416            return;
417        }
418        let core = Rc::clone(&self.core);
419        let done = Rc::clone(&self.core);
420        let on_result = Rc::clone(&self.on_result);
421        let future = core.picker.save_document(request);
422        core.spawn(async move {
423            let result = future.await;
424            done.end();
425            on_result(result);
426        });
427    }
428
429    /// Whether a chooser presented by this launcher is still in front.
430    pub fn is_in_flight(&self) -> bool {
431        self.core.in_flight.get()
432    }
433}
434
435/// Remembers a save-document launcher under `request_key`.
436#[allow(non_snake_case)]
437#[composable]
438pub fn rememberSaveDocumentLauncher(
439    request_key: &'static str,
440    on_result: impl Fn(LauncherResult<Option<ContentSinkRef>>) + 'static,
441) -> SaveDocumentLauncher {
442    let on_result: Rc<dyn Fn(LauncherResult<Option<ContentSinkRef>>)> = Rc::new(on_result);
443    let core = remember_core(request_key, move |_recovered| {
444        log::warn!("cranpose: `{request_key}` recovered a pick of another kind");
445    });
446    SaveDocumentLauncher { core, on_result }
447}
448
449/// Presents the persistent writable-folder chooser and hands the durable handle
450/// back. Store the handle and reopen it with
451/// [`crate::writable_folder::open_writable_folder`].
452#[derive(Clone)]
453pub struct WritableFolderLauncher {
454    core: Rc<LauncherCore>,
455    on_result: Rc<dyn Fn(LauncherResult<Option<String>>)>,
456}
457
458impl WritableFolderLauncher {
459    /// Presents the chooser. A second call while one is in front is ignored.
460    pub fn launch(&self, options: FilePickerOptions) {
461        if !self.core.begin() {
462            return;
463        }
464        let core = Rc::clone(&self.core);
465        let done = Rc::clone(&self.core);
466        let on_result = Rc::clone(&self.on_result);
467        let future = core.picker.pick_writable_folder(options);
468        core.spawn(async move {
469            let result = future.await;
470            done.end();
471            on_result(result);
472        });
473    }
474
475    /// Whether a chooser presented by this launcher is still in front.
476    pub fn is_in_flight(&self) -> bool {
477        self.core.in_flight.get()
478    }
479}
480
481/// Remembers a writable-folder launcher under `request_key`.
482#[allow(non_snake_case)]
483#[composable]
484pub fn rememberWritableFolderLauncher(
485    request_key: &'static str,
486    on_result: impl Fn(LauncherResult<Option<String>>) + 'static,
487) -> WritableFolderLauncher {
488    let on_result: Rc<dyn Fn(LauncherResult<Option<String>>)> = Rc::new(on_result);
489    let core = remember_core(request_key, {
490        let on_result = Rc::clone(&on_result);
491        move |recovered| match recovered {
492            RecoveredPick::WritableFolder(handle) => on_result(Ok(Some(handle))),
493            _ => log::warn!("cranpose: `{request_key}` recovered a pick of another kind"),
494        }
495    });
496    WritableFolderLauncher { core, on_result }
497}
498
499#[cfg(test)]
500mod tests {
501    use super::*;
502
503    /// The persistence contract, in one test.
504    ///
505    /// Two tests would share the process-wide preferences store *and* the one
506    /// key the in-flight record lives under, and the harness runs them at the
507    /// same time - so each would clear the other's record and the failure would
508    /// look like the contract being wrong. One outstanding request is also the
509    /// real invariant: a system chooser is modal, so there is one to remember.
510    #[test]
511    fn an_in_flight_request_outlives_the_process_that_started_it() {
512        // An in-memory store, because a unit test has no business writing to
513        // the user's config directory - which is where the default file-backed
514        // store puts it.
515        crate::preferences::set_platform_preferences(std::sync::Arc::new(
516            crate::preferences::MemoryPreferences::new(),
517        ));
518
519        // The in-memory slot is what a torn-down composition leaves behind. A
520        // killed process leaves nothing, so the record has to be somewhere that
521        // outlives it - otherwise a grant returns to an application that has
522        // forgotten it asked, and every application writes its own marker file.
523        begin_request("test.pick");
524        assert_eq!(in_flight_request().as_deref(), Some("test.pick"));
525
526        // The process dies: the thread-local is gone, the record is not.
527        IN_FLIGHT.with(|slot| *slot.borrow_mut() = None);
528        assert_eq!(
529            in_flight_request().as_deref(),
530            Some("test.pick"),
531            "a restarted process must still know which request was outstanding"
532        );
533
534        // A different launcher resolving must not clear this one's record;
535        // `drain_recovered` routes a recovered grant by it.
536        finish_request("test.other");
537        assert_eq!(
538            in_flight_request().as_deref(),
539            Some("test.pick"),
540            "one launcher resolving must not clear a different launcher's record"
541        );
542
543        finish_request("test.pick");
544        assert_eq!(
545            in_flight_request(),
546            None,
547            "a resolved request is not still in flight"
548        );
549
550        crate::preferences::clear_platform_preferences();
551    }
552}