1use std::{
29 cell::{Cell, RefCell},
30 collections::HashMap,
31 future::Future,
32 rc::Rc,
33};
34
35use cranpose_core::{RuntimeHandle, current_runtime_handle};
36use cranpose_macros::composable;
37
38use crate::{
39 content::{ContentFolderRef, ContentHandle, ContentSinkRef},
40 file_picker::{
41 FilePickerError, FilePickerOptions, FilePickerRef, RecoveredPick, SaveDocumentRequest,
42 local_file_picker,
43 },
44 preferences::preferences,
45};
46
47pub type LauncherResult<T> = Result<T, FilePickerError>;
52
53thread_local! {
54 static RECOVERED: RefCell<HashMap<String, RecoveredPick>> = RefCell::new(HashMap::new());
55 static IN_FLIGHT: RefCell<Option<String>> = const { RefCell::new(None) };
56 static REGISTERED_KEYS: RefCell<HashMap<String, usize>> = RefCell::new(HashMap::new());
57}
58
59const IN_FLIGHT_PREFERENCE: &str = "cranpose.launcher.in-flight";
60
61fn begin_request(request_key: &str) {
62 IN_FLIGHT.with(|slot| *slot.borrow_mut() = Some(request_key.to_string()));
63 let _ = preferences().set(IN_FLIGHT_PREFERENCE, request_key);
64}
65
66fn finish_request(request_key: &str) {
67 IN_FLIGHT.with(|slot| {
68 let mut slot = slot.borrow_mut();
69 if slot.as_deref() == Some(request_key) {
70 *slot = None;
71 }
72 });
73 if preferences().get(IN_FLIGHT_PREFERENCE).as_deref() == Some(request_key) {
74 let _ = preferences().remove(IN_FLIGHT_PREFERENCE);
75 }
76}
77
78fn in_flight_request() -> Option<String> {
79 IN_FLIGHT
80 .with(|slot| slot.borrow().clone())
81 .or_else(|| preferences().get(IN_FLIGHT_PREFERENCE))
82}
83
84fn drain_recovered(picker: &FilePickerRef) {
85 while let Some(pick) = picker.take_recovered_pick() {
86 let Some(key) = in_flight_request() else {
87 log::warn!("cranpose: a recovered pick arrived with no request in flight; dropping it");
88 continue;
89 };
90 RECOVERED.with(|inbox| inbox.borrow_mut().insert(key, pick));
91 }
92}
93
94fn take_recovered(request_key: &str) -> Option<RecoveredPick> {
95 let recovered = RECOVERED.with(|inbox| inbox.borrow_mut().remove(request_key));
96 if recovered.is_some() {
97 finish_request(request_key);
98 }
99 recovered
100}
101
102pub fn clear_launcher_state() {
105 RECOVERED.with(|inbox| inbox.borrow_mut().clear());
106 IN_FLIGHT.with(|slot| *slot.borrow_mut() = None);
107 REGISTERED_KEYS.with(|keys| keys.borrow_mut().clear());
108}
109
110struct LauncherCore {
111 request_key: String,
112 picker: FilePickerRef,
113 runtime: Option<RuntimeHandle>,
114 in_flight: Cell<bool>,
115}
116
117impl LauncherCore {
118 fn spawn(self: &Rc<Self>, future: impl Future<Output = ()> + 'static) {
119 let Some(runtime) = self.runtime.clone() else {
120 log::warn!(
121 "cranpose: launcher `{}` has no runtime; the chooser was not presented",
122 self.request_key
123 );
124 self.in_flight.set(false);
125 finish_request(&self.request_key);
126 return;
127 };
128 if runtime.spawn_ui(future).is_none() {
129 log::warn!(
130 "cranpose: launcher `{}` outlived its runtime; the chooser was not presented",
131 self.request_key
132 );
133 self.in_flight.set(false);
134 finish_request(&self.request_key);
135 }
136 }
137
138 fn begin(self: &Rc<Self>) -> bool {
139 if self.in_flight.get() {
140 return false;
141 }
142 self.in_flight.set(true);
143 begin_request(&self.request_key);
144 true
145 }
146
147 fn end(self: &Rc<Self>) {
148 self.in_flight.set(false);
149 finish_request(&self.request_key);
150 }
151}
152
153struct KeyRegistration {
154 request_key: String,
155}
156
157impl KeyRegistration {
158 fn new(request_key: &str) -> Self {
159 REGISTERED_KEYS.with(|keys| {
160 let mut keys = keys.borrow_mut();
161 let count = keys.entry(request_key.to_string()).or_insert(0);
162 *count += 1;
163 debug_assert!(
164 *count == 1,
165 "launcher request key `{request_key}` is registered {count} times; \
166 keys must be unique so a recovered result reaches the right launcher"
167 );
168 });
169 Self {
170 request_key: request_key.to_string(),
171 }
172 }
173}
174
175impl Drop for KeyRegistration {
176 fn drop(&mut self) {
177 REGISTERED_KEYS.with(|keys| {
178 let mut keys = keys.borrow_mut();
179 if let Some(count) = keys.get_mut(&self.request_key) {
180 *count -= 1;
181 if *count == 0 {
182 keys.remove(&self.request_key);
183 }
184 }
185 });
186 }
187}
188
189struct LauncherSlot {
190 core: Rc<LauncherCore>,
191 _registration: KeyRegistration,
192}
193
194#[track_caller]
195fn remember_core(
196 request_key: &'static str,
197 deliver: impl FnOnce(RecoveredPick) + 'static,
198) -> Rc<LauncherCore> {
199 let picker = local_file_picker().current();
200 let slot = cranpose_core::remember({
201 let picker = picker.clone();
202 let request_key = request_key.to_string();
203 move || LauncherSlot {
204 core: Rc::new(LauncherCore {
205 request_key: request_key.clone(),
206 picker,
207 runtime: current_runtime_handle(),
208 in_flight: Cell::new(false),
209 }),
210 _registration: KeyRegistration::new(&request_key),
211 }
212 });
213 let core = slot.with(|slot| Rc::clone(&slot.core));
214
215 drain_recovered(&picker);
216 if let Some(recovered) = take_recovered(request_key) {
217 let core = Rc::clone(&core);
218 cranpose_core::SideEffect(move || {
219 core.end();
220 deliver(recovered);
221 });
222 }
223 core
224}
225
226#[derive(Clone)]
228pub struct OpenFileLauncher {
229 core: Rc<LauncherCore>,
230 on_result: Rc<dyn Fn(LauncherResult<Option<ContentHandle>>)>,
231}
232
233impl OpenFileLauncher {
234 pub fn launch(&self, options: FilePickerOptions) {
236 if !self.core.begin() {
237 return;
238 }
239 let core = Rc::clone(&self.core);
240 let done = Rc::clone(&self.core);
241 let on_result = Rc::clone(&self.on_result);
242 let future = core.picker.pick_file(options);
243 core.spawn(async move {
244 let result = future.await;
245 done.end();
246 on_result(result);
247 });
248 }
249
250 pub fn is_in_flight(&self) -> bool {
252 self.core.in_flight.get()
253 }
254}
255
256#[composable]
258#[track_caller]
259pub fn rememberOpenFileLauncher(
260 request_key: &'static str,
261 on_result: impl Fn(LauncherResult<Option<ContentHandle>>) + 'static,
262) -> OpenFileLauncher {
263 let on_result: Rc<dyn Fn(LauncherResult<Option<ContentHandle>>)> = Rc::new(on_result);
264 let core = remember_core(request_key, {
265 let on_result = Rc::clone(&on_result);
266 move |recovered| match recovered {
267 RecoveredPick::File(content) => on_result(Ok(Some(content))),
268 RecoveredPick::Files(mut files) => on_result(Ok(files.drain(..).next())),
269 _ => log::warn!("cranpose: `{request_key}` recovered a pick of another kind"),
270 }
271 });
272 OpenFileLauncher { core, on_result }
273}
274
275#[derive(Clone)]
277pub struct OpenFilesLauncher {
278 core: Rc<LauncherCore>,
279 on_result: Rc<dyn Fn(LauncherResult<Vec<ContentHandle>>)>,
280}
281
282impl OpenFilesLauncher {
283 pub fn launch(&self, options: FilePickerOptions) {
285 if !self.core.begin() {
286 return;
287 }
288 let core = Rc::clone(&self.core);
289 let done = Rc::clone(&self.core);
290 let on_result = Rc::clone(&self.on_result);
291 let future = core.picker.pick_files(options);
292 core.spawn(async move {
293 let result = future.await;
294 done.end();
295 on_result(result);
296 });
297 }
298
299 pub fn is_in_flight(&self) -> bool {
301 self.core.in_flight.get()
302 }
303}
304
305#[composable]
307#[track_caller]
308pub fn rememberOpenFilesLauncher(
309 request_key: &'static str,
310 on_result: impl Fn(LauncherResult<Vec<ContentHandle>>) + 'static,
311) -> OpenFilesLauncher {
312 let on_result: Rc<dyn Fn(LauncherResult<Vec<ContentHandle>>)> = Rc::new(on_result);
313 let core = remember_core(request_key, {
314 let on_result = Rc::clone(&on_result);
315 move |recovered| match recovered {
316 RecoveredPick::Files(files) => on_result(Ok(files)),
317 RecoveredPick::File(content) => on_result(Ok(vec![content])),
318 _ => log::warn!("cranpose: `{request_key}` recovered a pick of another kind"),
319 }
320 });
321 OpenFilesLauncher { core, on_result }
322}
323
324#[derive(Clone)]
326pub struct OpenFolderLauncher {
327 core: Rc<LauncherCore>,
328 on_result: Rc<dyn Fn(LauncherResult<Option<ContentFolderRef>>)>,
329}
330
331impl OpenFolderLauncher {
332 pub fn launch(&self, options: FilePickerOptions) {
334 if !self.core.begin() {
335 return;
336 }
337 let core = Rc::clone(&self.core);
338 let done = Rc::clone(&self.core);
339 let on_result = Rc::clone(&self.on_result);
340 let future = core.picker.pick_folder(options);
341 core.spawn(async move {
342 let result = future.await;
343 done.end();
344 on_result(result);
345 });
346 }
347
348 pub fn is_in_flight(&self) -> bool {
350 self.core.in_flight.get()
351 }
352}
353
354#[composable]
356#[track_caller]
357pub fn rememberOpenFolderLauncher(
358 request_key: &'static str,
359 on_result: impl Fn(LauncherResult<Option<ContentFolderRef>>) + 'static,
360) -> OpenFolderLauncher {
361 let on_result: Rc<dyn Fn(LauncherResult<Option<ContentFolderRef>>)> = Rc::new(on_result);
362 let core = remember_core(request_key, {
363 let on_result = Rc::clone(&on_result);
364 move |recovered| match recovered {
365 RecoveredPick::Folder(folder) => on_result(Ok(Some(folder))),
366 _ => log::warn!("cranpose: `{request_key}` recovered a pick of another kind"),
367 }
368 });
369 OpenFolderLauncher { core, on_result }
370}
371
372#[derive(Clone)]
374pub struct SaveDocumentLauncher {
375 core: Rc<LauncherCore>,
376 on_result: Rc<dyn Fn(LauncherResult<Option<ContentSinkRef>>)>,
377}
378
379impl SaveDocumentLauncher {
380 pub fn launch(&self, request: SaveDocumentRequest) {
382 if !self.core.begin() {
383 return;
384 }
385 let core = Rc::clone(&self.core);
386 let done = Rc::clone(&self.core);
387 let on_result = Rc::clone(&self.on_result);
388 let future = core.picker.save_document(request);
389 core.spawn(async move {
390 let result = future.await;
391 done.end();
392 on_result(result);
393 });
394 }
395
396 pub fn is_in_flight(&self) -> bool {
398 self.core.in_flight.get()
399 }
400}
401
402#[composable]
404#[track_caller]
405pub fn rememberSaveDocumentLauncher(
406 request_key: &'static str,
407 on_result: impl Fn(LauncherResult<Option<ContentSinkRef>>) + 'static,
408) -> SaveDocumentLauncher {
409 let on_result: Rc<dyn Fn(LauncherResult<Option<ContentSinkRef>>)> = Rc::new(on_result);
410 let core = remember_core(request_key, move |_recovered| {
411 log::warn!("cranpose: `{request_key}` recovered a pick of another kind");
412 });
413 SaveDocumentLauncher { core, on_result }
414}
415
416#[derive(Clone)]
420pub struct WritableFolderLauncher {
421 core: Rc<LauncherCore>,
422 on_result: Rc<dyn Fn(LauncherResult<Option<String>>)>,
423}
424
425impl WritableFolderLauncher {
426 pub fn launch(&self, options: FilePickerOptions) {
428 if !self.core.begin() {
429 return;
430 }
431 let core = Rc::clone(&self.core);
432 let done = Rc::clone(&self.core);
433 let on_result = Rc::clone(&self.on_result);
434 let future = core.picker.pick_writable_folder(options);
435 core.spawn(async move {
436 let result = future.await;
437 done.end();
438 on_result(result);
439 });
440 }
441
442 pub fn is_in_flight(&self) -> bool {
444 self.core.in_flight.get()
445 }
446}
447
448#[composable]
450#[track_caller]
451pub fn rememberWritableFolderLauncher(
452 request_key: &'static str,
453 on_result: impl Fn(LauncherResult<Option<String>>) + 'static,
454) -> WritableFolderLauncher {
455 let on_result: Rc<dyn Fn(LauncherResult<Option<String>>)> = Rc::new(on_result);
456 let core = remember_core(request_key, {
457 let on_result = Rc::clone(&on_result);
458 move |recovered| match recovered {
459 RecoveredPick::WritableFolder(handle) => on_result(Ok(Some(handle))),
460 _ => log::warn!("cranpose: `{request_key}` recovered a pick of another kind"),
461 }
462 });
463 WritableFolderLauncher { core, on_result }
464}
465
466#[cfg(test)]
467#[path = "tests/launcher_tests.rs"]
468mod tests;