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        // No platform picker: a live camera needs one, but a library pick can
81        // fall back to the file picker filtered to images.
82        if source == ImageSource::Camera {
83            return Box::pin(async { Err(ImagePickerError::Unsupported) });
84        }
85        Box::pin(async {
86            let picker = default_file_picker();
87            let options = FilePickerOptions::default()
88                .with_title("Choose image")
89                .with_filter(FileFilter::new("Images", IMAGE_EXTENSIONS));
90            match picker.pick_file(options).await {
91                Ok(Some(entry)) => match entry.read_all().await {
92                    Ok(bytes) => Ok(Some(bytes)),
93                    Err(error) => Err(ImagePickerError::Failed(error.to_string())),
94                },
95                Ok(None) => Ok(None),
96                Err(error) => Err(ImagePickerError::Failed(error.to_string())),
97            }
98        })
99    }
100}
101
102pub fn default_image_picker() -> ImagePickerRef {
103    Arc::new(PlatformImagePicker)
104}
105
106pub fn local_image_picker() -> CompositionLocal<ImagePickerRef> {
107    thread_local! {
108        static LOCAL_IMAGE_PICKER: RefCell<Option<CompositionLocal<ImagePickerRef>>> = const { RefCell::new(None) };
109    }
110
111    LOCAL_IMAGE_PICKER.with(|cell| {
112        let mut local = cell.borrow_mut();
113        local
114            .get_or_insert_with(|| compositionLocalOfWithPolicy(default_image_picker, Arc::ptr_eq))
115            .clone()
116    })
117}
118
119#[allow(non_snake_case)]
120#[composable]
121pub fn ProvideImagePicker(content: impl FnOnce()) {
122    let picker = cranpose_core::remember(default_image_picker).with(|state| state.clone());
123    let local = local_image_picker();
124
125    CompositionLocalProvider(vec![local.provides(picker)], move || {
126        content();
127    });
128}
129
130#[cfg(test)]
131mod tests {
132    use std::sync::RwLock;
133
134    use super::*;
135
136    struct FixedImagePicker {
137        bytes: RwLock<Option<Vec<u8>>>,
138    }
139
140    impl ImagePicker for FixedImagePicker {
141        fn pick_image(
142            &self,
143            _source: ImageSource,
144        ) -> PickerFuture<Result<Option<Vec<u8>>, ImagePickerError>> {
145            let bytes = self.bytes.read().unwrap().clone();
146            Box::pin(async move { Ok(bytes) })
147        }
148    }
149
150    #[test]
151    fn registered_image_picker_takes_precedence() {
152        let _guard = crate::registry::test_service_guard();
153        clear_platform_image_picker();
154        set_platform_image_picker(Arc::new(FixedImagePicker {
155            bytes: RwLock::new(Some(vec![1, 2, 3])),
156        }));
157        let picker = default_image_picker();
158        let result = pollster::block_on(picker.pick_image(ImageSource::Camera));
159        assert_eq!(result.unwrap(), Some(vec![1, 2, 3]));
160        clear_platform_image_picker();
161    }
162
163    #[test]
164    fn camera_is_unsupported_without_a_platform_picker() {
165        let _guard = crate::registry::test_service_guard();
166        clear_platform_image_picker();
167        let result = pollster::block_on(default_image_picker().pick_image(ImageSource::Camera));
168        assert!(matches!(result, Err(ImagePickerError::Unsupported)));
169    }
170}