Skip to main content

cranpose_services/
image_picker.rs

1//! Photo/image picker: choose a single image from the user's photo library.
2//!
3//! On iOS "photos" and "files" are distinct — a scanner's document photos live
4//! in the Photos library, which the file picker (`UIDocumentPicker`) cannot
5//! reach. The iOS backend registers a `UIImagePickerController`-based photo
6//! picker through [`set_platform_image_picker`]. The compiled-in default
7//! delegates to the file picker with an image filter, which is the right
8//! behavior on desktop (a file dialog), the web (`<input accept="image/*">`),
9//! and Android (SAF), where a plain file picker already surfaces images.
10
11use std::{cell::RefCell, sync::Arc};
12
13use cranpose_core::{CompositionLocal, CompositionLocalProvider, compositionLocalOfWithPolicy};
14use cranpose_macros::composable;
15
16use crate::{
17    file_picker::{FileFilter, FilePickerOptions, PickerFuture, default_file_picker},
18    registry::ServiceRegistry,
19};
20
21/// Image extensions offered when the picker falls back to the file picker.
22pub const IMAGE_EXTENSIONS: &[&str] = &["jpg", "jpeg", "png", "webp", "bmp", "heic", "heif"];
23
24#[derive(thiserror::Error, Debug)]
25pub enum ImagePickerError {
26    #[error("image picking is not supported on this platform")]
27    Unsupported,
28    #[error("failed to pick an image: {0}")]
29    Failed(String),
30}
31
32/// Where an image comes from.
33#[derive(Clone, Copy, PartialEq, Eq, Debug)]
34pub enum ImageSource {
35    /// The user's photo library (or a file dialog on platforms without one).
36    PhotoLibrary,
37    /// A photo captured with the device camera.
38    Camera,
39}
40
41/// Picks or captures a single image and returns its encoded bytes.
42pub trait ImagePicker: Send + Sync {
43    /// Present a picker/camera for `source` and resolve to the chosen image's
44    /// encoded bytes, or `None` if the user cancelled.
45    fn pick_image(
46        &self,
47        source: ImageSource,
48    ) -> PickerFuture<Result<Option<Vec<u8>>, ImagePickerError>>;
49}
50
51pub type ImagePickerRef = Arc<dyn ImagePicker>;
52
53static PLATFORM_IMAGE_PICKER: ServiceRegistry<dyn ImagePicker> = ServiceRegistry::new();
54
55/// Installs a platform image picker, replacing any previously installed one.
56/// The iOS backend registers a photo-library picker here.
57pub fn set_platform_image_picker(picker: ImagePickerRef) {
58    PLATFORM_IMAGE_PICKER.set(picker);
59}
60
61/// Removes any registered platform image picker (tests and teardown).
62pub fn clear_platform_image_picker() {
63    PLATFORM_IMAGE_PICKER.clear();
64}
65
66fn registered_platform_image_picker() -> Option<ImagePickerRef> {
67    PLATFORM_IMAGE_PICKER.get_or_warn("image picker")
68}
69
70struct PlatformImagePicker;
71
72impl ImagePicker for PlatformImagePicker {
73    fn pick_image(
74        &self,
75        source: ImageSource,
76    ) -> PickerFuture<Result<Option<Vec<u8>>, ImagePickerError>> {
77        if let Some(picker) = registered_platform_image_picker() {
78            return picker.pick_image(source);
79        }
80        if source == ImageSource::Camera {
81            return Box::pin(async { Err(ImagePickerError::Unsupported) });
82        }
83        Box::pin(async {
84            let picker = default_file_picker();
85            let options = FilePickerOptions::default()
86                .with_title("Choose image")
87                .with_filter(FileFilter::new("Images", IMAGE_EXTENSIONS));
88            match picker.pick_file(options).await {
89                Ok(Some(entry)) => match entry.read_all().await {
90                    Ok(bytes) => Ok(Some(bytes)),
91                    Err(error) => Err(ImagePickerError::Failed(error.to_string())),
92                },
93                Ok(None) => Ok(None),
94                Err(error) => Err(ImagePickerError::Failed(error.to_string())),
95            }
96        })
97    }
98}
99
100pub fn default_image_picker() -> ImagePickerRef {
101    Arc::new(PlatformImagePicker)
102}
103
104pub fn local_image_picker() -> CompositionLocal<ImagePickerRef> {
105    thread_local! {
106        static LOCAL_IMAGE_PICKER: RefCell<Option<CompositionLocal<ImagePickerRef>>> = const { RefCell::new(None) };
107    }
108
109    LOCAL_IMAGE_PICKER.with(|cell| {
110        let mut local = cell.borrow_mut();
111        local
112            .get_or_insert_with(|| compositionLocalOfWithPolicy(default_image_picker, Arc::ptr_eq))
113            .clone()
114    })
115}
116
117#[allow(non_snake_case)]
118#[composable]
119pub fn ProvideImagePicker(content: impl FnOnce()) {
120    let picker = cranpose_core::remember(default_image_picker).with(|state| state.clone());
121    let local = local_image_picker();
122
123    CompositionLocalProvider(vec![local.provides(picker)], move || {
124        content();
125    });
126}
127
128#[cfg(test)]
129mod tests {
130    use std::sync::RwLock;
131
132    use super::*;
133
134    struct FixedImagePicker {
135        bytes: RwLock<Option<Vec<u8>>>,
136    }
137
138    impl ImagePicker for FixedImagePicker {
139        fn pick_image(
140            &self,
141            _source: ImageSource,
142        ) -> PickerFuture<Result<Option<Vec<u8>>, ImagePickerError>> {
143            let bytes = self.bytes.read().unwrap().clone();
144            Box::pin(async move { Ok(bytes) })
145        }
146    }
147
148    #[test]
149    fn registered_image_picker_takes_precedence() {
150        let _guard = crate::registry::test_service_guard();
151        clear_platform_image_picker();
152        set_platform_image_picker(Arc::new(FixedImagePicker {
153            bytes: RwLock::new(Some(vec![1, 2, 3])),
154        }));
155        let picker = default_image_picker();
156        let result = pollster::block_on(picker.pick_image(ImageSource::Camera));
157        assert_eq!(result.unwrap(), Some(vec![1, 2, 3]));
158        clear_platform_image_picker();
159    }
160
161    #[test]
162    fn camera_is_unsupported_without_a_platform_picker() {
163        let _guard = crate::registry::test_service_guard();
164        clear_platform_image_picker();
165        let result = pollster::block_on(default_image_picker().pick_image(ImageSource::Camera));
166        assert!(matches!(result, Err(ImagePickerError::Unsupported)));
167    }
168}