cranpose 0.1.23

Cranpose runtime and UI facade
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! Android file and folder picker built on the Storage Access Framework.
//!
//! `cranposePickFile` / `cranposePickFolder` on
//! [`CranposeFilePickerActivity`](https://github.com/samoylenkodmitry/cranpose)
//! launch `ACTION_OPEN_DOCUMENT` / `ACTION_OPEN_DOCUMENT_TREE`, so the user can
//! choose a file or a folder from any document provider the device exposes
//! (local storage, cloud, or a mounted WebDAV share). The Java side reports the
//! chosen `content://` document URIs back through
//! [`Java_dev_cranpose_android_CranposeFilePickerActivity_nativeOnFilePicked`];
//! nothing is copied. A picked file is read on demand by opening a descriptor
//! from the provider through [`open_content_uri`], so even a multi-gigabyte
//! folder is selected instantly and each track is streamed only when played.
//!
//! The Java callback runs on the Android UI thread while `android_main` runs on
//! its own thread, so results travel through `Send` globals; the picked-entry
//! handle is built on the `android_main` thread when the future is polled.
#![allow(unsafe_code)]

use cranpose_services::{
    set_platform_file_picker, FilePicker, FilePickerError, FilePickerOptions, FolderStream,
    FolderStreamRef, PickedEntry, PickedEntryRef, PickedKind, PickerFuture,
};
use jni::objects::{JClass, JObject, JString, JValue};
use jni::sys::{jboolean, jlong};
use jni::{jni_sig, jni_str, EnvUnowned, Outcome};
use std::collections::HashMap;
use std::fs::File;
use std::future::Future;
use std::io::{self, Read};
use std::os::fd::FromRawFd;
use std::pin::Pin;
use std::rc::Rc;
use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::{Mutex, OnceLock};
use std::task::{Context, Poll, Waker};

type PickResult = Result<Option<PickedEntryRef>, FilePickerError>;

/// A picked document: its `content://` URI and display name.
struct PickedDocument {
    uri: String,
    name: String,
}

/// The raw, `Send` data delivered from the Java UI-thread callback.
struct RawResult {
    folder: bool,
    documents: Vec<PickedDocument>,
    cancelled: bool,
    error: Option<String>,
}

#[derive(Default)]
struct Pending {
    result: Option<RawResult>,
    waker: Option<Waker>,
}

static APP: OnceLock<android_activity::AndroidApp> = OnceLock::new();
static NEXT_TOKEN: AtomicI64 = AtomicI64::new(1);

fn pending() -> &'static Mutex<HashMap<i64, Pending>> {
    static PENDING: OnceLock<Mutex<HashMap<i64, Pending>>> = OnceLock::new();
    PENDING.get_or_init(|| Mutex::new(HashMap::new()))
}

/// Installs the Android picker as the platform file picker.
pub(crate) fn register(app: android_activity::AndroidApp) {
    let _ = APP.set(app);
    set_platform_file_picker(Rc::new(AndroidFilePicker));
}

struct AndroidFilePicker;

impl FilePicker for AndroidFilePicker {
    fn pick_file(&self, _options: FilePickerOptions) -> PickerFuture<PickResult> {
        present(false)
    }

    fn pick_folder(&self, _options: FilePickerOptions) -> PickerFuture<PickResult> {
        present(true)
    }

    fn pick_folder_streaming(
        &self,
        _options: FilePickerOptions,
    ) -> PickerFuture<Result<Option<FolderStreamRef>, FilePickerError>> {
        present_folder_stream()
    }
}

/// Which Android picker entry point to launch for a request.
#[derive(Clone, Copy)]
enum PickKind {
    /// `cranposePickFile` — a single document.
    File,
    /// `cranposePickFolder` — a tree, enumerated fully before delivery.
    Folder,
    /// `cranposePickFolderStreaming` — a tree whose files stream in as the
    /// provider discovers them.
    FolderStreaming,
}

fn present(folder: bool) -> PickerFuture<PickResult> {
    let token = NEXT_TOKEN.fetch_add(1, Ordering::Relaxed);
    pending()
        .lock()
        .expect("file picker registry poisoned")
        .insert(token, Pending::default());

    let kind = if folder {
        PickKind::Folder
    } else {
        PickKind::File
    };
    if let Err(error) = call_activity(kind, token) {
        pending()
            .lock()
            .expect("file picker registry poisoned")
            .remove(&token);
        return Box::pin(async move { Err(FilePickerError::Failed(error)) });
    }

    Box::pin(PickFuture { token })
}

fn call_activity(kind: PickKind, token: i64) -> Result<(), String> {
    let app = APP
        .get()
        .ok_or_else(|| "Android file picker was not registered".to_string())?;
    crate::android_jni::with_android_activity_env(app, |env, activity| {
        let method = match kind {
            PickKind::File => jni_str!("cranposePickFile"),
            PickKind::Folder => jni_str!("cranposePickFolder"),
            PickKind::FolderStreaming => jni_str!("cranposePickFolderStreaming"),
        };
        env.call_method(&activity, method, jni_sig!("(J)V"), &[JValue::Long(token)])
            .map(|_| ())
            .map_err(|error| format!("failed to launch Android picker: {error}"))
    })
}

/// Future resolved when the Java callback reports a result for `token`.
struct PickFuture {
    token: i64,
}

impl Future for PickFuture {
    type Output = PickResult;

    fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<PickResult> {
        let mut registry = pending().lock().expect("file picker registry poisoned");
        let Some(slot) = registry.get_mut(&self.token) else {
            return Poll::Ready(Ok(None));
        };
        match slot.result.take() {
            Some(raw) => {
                registry.remove(&self.token);
                Poll::Ready(build_result(raw))
            }
            None => {
                slot.waker = Some(context.waker().clone());
                Poll::Pending
            }
        }
    }
}

fn build_result(raw: RawResult) -> PickResult {
    if raw.cancelled {
        return Ok(None);
    }
    if let Some(error) = raw.error {
        return Err(FilePickerError::Failed(error));
    }
    if raw.folder {
        let children: Vec<PickedEntryRef> = raw
            .documents
            .into_iter()
            .map(|document| Rc::new(UriEntry::from(document)) as PickedEntryRef)
            .collect();
        Ok(Some(Rc::new(FolderEntry { children })))
    } else {
        match raw.documents.into_iter().next() {
            Some(document) => Ok(Some(Rc::new(UriEntry::from(document)))),
            None => Ok(None),
        }
    }
}

/// A picked file addressed by a `content://` URI. It is opened on demand
/// through the provider's descriptor and never copied to the cache.
struct UriEntry {
    uri: String,
    name: String,
}

impl From<PickedDocument> for UriEntry {
    fn from(document: PickedDocument) -> Self {
        UriEntry {
            uri: document.uri,
            name: document.name,
        }
    }
}

impl PickedEntry for UriEntry {
    fn name(&self) -> String {
        self.name.clone()
    }

    fn kind(&self) -> PickedKind {
        PickedKind::File
    }

    fn display_path(&self) -> String {
        self.uri.clone()
    }

    fn read_bytes(&self) -> PickerFuture<Result<Vec<u8>, FilePickerError>> {
        let uri = self.uri.clone();
        Box::pin(async move {
            let mut file = open_content_uri(&uri)
                .map_err(|error| FilePickerError::ReadFailed(error.to_string()))?;
            let mut bytes = Vec::new();
            file.read_to_end(&mut bytes)
                .map_err(|error| FilePickerError::ReadFailed(error.to_string()))?;
            Ok(bytes)
        })
    }

    fn list(&self) -> PickerFuture<Result<Vec<PickedEntryRef>, FilePickerError>> {
        Box::pin(async {
            Err(FilePickerError::WrongKind {
                actual: "file",
                expected: "folder",
            })
        })
    }
}

/// A picked folder: its audio descendants enumerated as [`UriEntry`] children
/// without copying anything.
struct FolderEntry {
    children: Vec<PickedEntryRef>,
}

impl PickedEntry for FolderEntry {
    fn name(&self) -> String {
        "folder".to_string()
    }

    fn kind(&self) -> PickedKind {
        PickedKind::Folder
    }

    fn display_path(&self) -> String {
        String::new()
    }

    fn read_bytes(&self) -> PickerFuture<Result<Vec<u8>, FilePickerError>> {
        Box::pin(async {
            Err(FilePickerError::WrongKind {
                actual: "folder",
                expected: "file",
            })
        })
    }

    fn list(&self) -> PickerFuture<Result<Vec<PickedEntryRef>, FilePickerError>> {
        let children = self.children.clone();
        Box::pin(async move { Ok(children) })
    }
}

// ---- Streaming folder discovery ------------------------------------------
//
// `enumerateTree` on the Java side walks the picked tree on a worker thread and
// reports audio files in batches as it finds them. That matters for a slow
// provider (a mounted WebDAV share): instead of blocking until the whole tree
// is walked, the folder selection resolves immediately and files arrive
// incrementally, so the app can show progress and play the first track at once.

/// Per-token state for a streaming folder pick, written by the Java callbacks
/// and drained by the [`AndroidFolderStream`] on the UI thread.
#[derive(Default)]
struct FolderStreaming {
    documents: Vec<PickedDocument>,
    picked: bool,
    cancelled: bool,
    pick_error: Option<String>,
    finished: bool,
    stream_error: Option<String>,
    waker: Option<Waker>,
}

fn folder_streaming() -> &'static Mutex<HashMap<i64, FolderStreaming>> {
    static FOLDER_STREAMING: OnceLock<Mutex<HashMap<i64, FolderStreaming>>> = OnceLock::new();
    FOLDER_STREAMING.get_or_init(|| Mutex::new(HashMap::new()))
}

fn present_folder_stream() -> PickerFuture<Result<Option<FolderStreamRef>, FilePickerError>> {
    let token = NEXT_TOKEN.fetch_add(1, Ordering::Relaxed);
    folder_streaming()
        .lock()
        .expect("folder picker registry poisoned")
        .insert(token, FolderStreaming::default());

    if let Err(error) = call_activity(PickKind::FolderStreaming, token) {
        folder_streaming()
            .lock()
            .expect("folder picker registry poisoned")
            .remove(&token);
        return Box::pin(async move { Err(FilePickerError::Failed(error)) });
    }

    Box::pin(FolderPickFuture { token })
}

/// Resolves once the user has selected (or cancelled) the folder; the returned
/// [`AndroidFolderStream`] then yields files as enumeration continues.
struct FolderPickFuture {
    token: i64,
}

impl Future for FolderPickFuture {
    type Output = Result<Option<FolderStreamRef>, FilePickerError>;

    fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
        let mut registry = folder_streaming()
            .lock()
            .expect("folder picker registry poisoned");
        let Some(slot) = registry.get_mut(&self.token) else {
            return Poll::Ready(Ok(None));
        };
        if slot.cancelled {
            registry.remove(&self.token);
            return Poll::Ready(Ok(None));
        }
        if let Some(error) = slot.pick_error.take() {
            registry.remove(&self.token);
            return Poll::Ready(Err(FilePickerError::Failed(error)));
        }
        if slot.picked {
            return Poll::Ready(Ok(Some(
                Rc::new(AndroidFolderStream { token: self.token }) as FolderStreamRef
            )));
        }
        slot.waker = Some(context.waker().clone());
        Poll::Pending
    }
}

/// Streams files discovered under a picked folder. Dropping it discards the
/// registry slot (the Java enumeration thread checks the slot and stops).
struct AndroidFolderStream {
    token: i64,
}

impl FolderStream for AndroidFolderStream {
    fn take_ready(&self) -> Vec<PickedEntryRef> {
        let mut registry = folder_streaming()
            .lock()
            .expect("folder picker registry poisoned");
        let Some(slot) = registry.get_mut(&self.token) else {
            return Vec::new();
        };
        std::mem::take(&mut slot.documents)
            .into_iter()
            .map(|document| Rc::new(UriEntry::from(document)) as PickedEntryRef)
            .collect()
    }

    fn is_finished(&self) -> bool {
        let registry = folder_streaming()
            .lock()
            .expect("folder picker registry poisoned");
        registry
            .get(&self.token)
            .map(|slot| slot.finished && slot.documents.is_empty())
            .unwrap_or(true)
    }

    fn take_error(&self) -> Option<FilePickerError> {
        let mut registry = folder_streaming()
            .lock()
            .expect("folder picker registry poisoned");
        registry
            .get_mut(&self.token)
            .and_then(|slot| slot.stream_error.take())
            .map(FilePickerError::Failed)
    }
}

impl Drop for AndroidFolderStream {
    fn drop(&mut self) {
        folder_streaming()
            .lock()
            .expect("folder picker registry poisoned")
            .remove(&self.token);
    }
}

/// Java callback: the user picked a folder (or cancelled/failed). Resolves the
/// [`FolderPickFuture`] so streaming can begin.
#[doc(hidden)]
#[no_mangle]
pub extern "system" fn Java_dev_cranpose_android_CranposeFilePickerActivity_nativeOnFolderPicked<
    'local,
>(
    mut env: EnvUnowned<'local>,
    _class: JClass<'local>,
    token: jlong,
    cancelled: jboolean,
    error: JString<'local>,
) {
    let error = read_optional_jstring(&mut env, error);
    let mut registry = folder_streaming()
        .lock()
        .expect("folder picker registry poisoned");
    if let Some(slot) = registry.get_mut(&token) {
        if cancelled {
            slot.cancelled = true;
        } else if let Some(error) = error {
            slot.pick_error = Some(error);
        } else {
            slot.picked = true;
        }
        if let Some(waker) = slot.waker.take() {
            waker.wake();
        }
    }
}

/// Java callback: a batch of newly-discovered files (`uri\tname` rows). Returns
/// `false` (0) once the consumer has dropped the stream, so the Java
/// enumeration thread can stop walking a huge tree it no longer needs.
#[doc(hidden)]
#[no_mangle]
pub extern "system" fn Java_dev_cranpose_android_CranposeFilePickerActivity_nativeOnFolderEntries<
    'local,
>(
    mut env: EnvUnowned<'local>,
    _class: JClass<'local>,
    token: jlong,
    entries: JString<'local>,
) -> jboolean {
    let documents = read_optional_jstring(&mut env, entries)
        .map(parse_documents)
        .unwrap_or_default();
    let mut registry = folder_streaming()
        .lock()
        .expect("folder picker registry poisoned");
    match registry.get_mut(&token) {
        Some(slot) => {
            slot.documents.extend(documents);
            true
        }
        None => false,
    }
}

/// Java callback: enumeration finished (with an optional error).
#[doc(hidden)]
#[no_mangle]
pub extern "system" fn Java_dev_cranpose_android_CranposeFilePickerActivity_nativeOnFolderFinished<
    'local,
>(
    mut env: EnvUnowned<'local>,
    _class: JClass<'local>,
    token: jlong,
    error: JString<'local>,
) {
    let error = read_optional_jstring(&mut env, error);
    let mut registry = folder_streaming()
        .lock()
        .expect("folder picker registry poisoned");
    if let Some(slot) = registry.get_mut(&token) {
        slot.finished = true;
        slot.stream_error = error;
    }
}

/// Opens a picked `content://` document for reading, returning a [`File`] backed
/// by the provider's descriptor. Nothing is copied; the descriptor is detached
/// from its `ParcelFileDescriptor` so the returned `File` owns and closes it.
/// Callable from any thread (it attaches to the JVM as needed), so the audio
/// engine can stream a track straight from the provider.
pub fn open_content_uri(uri: &str) -> io::Result<File> {
    let app = APP.get().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::NotConnected,
            "Android file picker is not registered",
        )
    })?;
    let fd = crate::android_jni::with_android_activity_env(app, |env, activity| {
        let argument = env.new_string(uri).map_err(|error| error.to_string())?;
        let argument: &JObject = argument.as_ref();
        env.call_method(
            &activity,
            jni_str!("cranposeOpenUri"),
            jni_sig!("(Ljava/lang/String;)I"),
            &[JValue::Object(argument)],
        )
        .and_then(|value| value.i())
        .map_err(|error| error.to_string())
    })
    .map_err(|error| io::Error::other(error))?;
    if fd < 0 {
        return Err(io::Error::other(format!(
            "ContentResolver returned no descriptor for {uri}"
        )));
    }
    // SAFETY: `cranposeOpenUri` detaches the descriptor from its
    // `ParcelFileDescriptor`, transferring ownership to this process; the
    // returned `File` closes it on drop.
    Ok(unsafe { File::from_raw_fd(fd) })
}

fn deliver(token: i64, result: RawResult) {
    let mut registry = pending().lock().expect("file picker registry poisoned");
    if let Some(slot) = registry.get_mut(&token) {
        slot.result = Some(result);
        if let Some(waker) = slot.waker.take() {
            waker.wake();
        }
    }
}

/// Java callback delivering a picker result. Runs on a worker thread spawned by
/// the activity. `entries` is newline-separated `uri\tname` rows (one for a
/// file, every audio descendant for a folder).
#[doc(hidden)]
#[no_mangle]
pub extern "system" fn Java_dev_cranpose_android_CranposeFilePickerActivity_nativeOnFilePicked<
    'local,
>(
    mut env: EnvUnowned<'local>,
    _class: JClass<'local>,
    token: jlong,
    folder: jboolean,
    entries: JString<'local>,
    cancelled: jboolean,
    error: JString<'local>,
) {
    let documents = read_optional_jstring(&mut env, entries)
        .map(parse_documents)
        .unwrap_or_default();
    let error = read_optional_jstring(&mut env, error);
    deliver(
        token,
        RawResult {
            folder,
            documents,
            cancelled,
            error,
        },
    );
}

fn parse_documents(text: String) -> Vec<PickedDocument> {
    text.lines()
        .filter_map(|line| {
            let mut parts = line.splitn(2, '\t');
            let uri = parts.next()?;
            if uri.is_empty() {
                return None;
            }
            let name = parts.next().unwrap_or("");
            Some(PickedDocument {
                uri: uri.to_string(),
                name: name.to_string(),
            })
        })
        .collect()
}

fn read_optional_jstring(env: &mut EnvUnowned<'_>, value: JString<'_>) -> Option<String> {
    if value.is_null() {
        return None;
    }
    match env
        .with_env(|env| -> jni::errors::Result<String> { value.try_to_string(env) })
        .into_outcome()
    {
        Outcome::Ok(text) if !text.is_empty() => Some(text),
        _ => None,
    }
}