Skip to content

Commit 5ee319f

Browse files
authored
Merge pull request #421 from emmertex/fix/android-folder-import-camera-roll
Android: enable Import from Folder; camera roll as a default import source
2 parents e795e79 + f1cea74 commit 5ee319f

14 files changed

Lines changed: 504 additions & 4 deletions

File tree

‎apps/android/src/app.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,7 @@ fn services(cc: &eframe::CreationContext<'_>, host: Option<Arc<Host>>) -> Servic
140140
}
141141
let picker_host = host.clone();
142142
let storage_host = host.clone();
143+
let roll_host = host.clone();
143144
let url_host = host;
144145
Services {
145146
// the system picker (Storage Access Framework); the activity copies what is picked into
@@ -165,6 +166,8 @@ fn services(cc: &eframe::CreationContext<'_>, host: Option<Arc<Host>>) -> Servic
165166
ask: Box::new(move || ask.ask_all_files_access().map_err(|e| e.to_string())),
166167
}
167168
}),
169+
// the camera roll through MediaStore (asks for the photo permission; `file.addCameraRoll`)
170+
camera_roll: roll_host.map(|h| -> lcc_ui_egui::CameraRollFn { Box::new(move || h.camera_roll().map_err(|e| e.to_string())) }),
168171
open_url: url_host.map(|h| -> lcc_ui_egui::OpenUrlFn { Box::new(move |url: &str| h.open_url(url).map_err(|e| e.to_string())) }),
169172
// atomic (temp file + sync + rename): a failed write never leaves a truncated file
170173
write_shared: Some(Arc::new(lcc_engine::export::write_file)),

‎apps/app/src/main.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -610,6 +610,7 @@ fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::path::Path>
610610
open_all_with: Some(Box::new(editors::open_all_with)),
611611
check_editor: Some(Box::new(editors::check)),
612612
storage_access: None,
613+
camera_roll: None,
613614
open_url: Some(Box::new(|url: &str| {
614615
// https links, plus the local page Preview in Browser generates (nothing else)
615616
lcc_ui_egui::links::check_browser_url(url)?;

‎apps/web/src/web.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,7 @@ fn services(originals: Originals, backend: Option<Backend>, files: Files, frozen
238238
open_all_with: None,
239239
check_editor: None,
240240
storage_access: None,
241+
camera_roll: None,
241242
open_url: Some(Box::new(|url: &str| {
242243
let w = web_sys::window().ok_or("no window")?;
243244
w.open_with_url_and_target(url, "_blank").map(|_| ()).map_err(|_| "the browser blocked the new tab".to_string())

‎crates/android-host/src/lib.rs‎

Lines changed: 107 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,46 @@ impl Answers {
123123
}
124124
}
125125

126+
/// The camera roll's answer: the photos' paths, or why there are none.
127+
pub type CameraRoll = Result<Vec<String>, String>;
128+
129+
/// Camera-roll listings waiting for the activity (`nativeCameraRoll`), by request id.
130+
#[derive(Default)]
131+
pub struct RollAnswers {
132+
waiting: std::collections::HashMap<i64, std::sync::mpsc::Sender<CameraRoll>>,
133+
}
134+
135+
impl RollAnswers {
136+
/// A new listing with `id`: its answer comes through the returned channel.
137+
pub fn wait(&mut self, id: i64) -> std::sync::mpsc::Receiver<CameraRoll> {
138+
let (tx, rx) = std::sync::mpsc::channel();
139+
self.waiting.insert(id, tx);
140+
rx
141+
}
142+
143+
/// Forgets a listing that never started.
144+
pub fn forget(&mut self, id: i64) {
145+
self.waiting.remove(&id);
146+
}
147+
148+
/// The activity's answer for `id`: `paths` (null = failed) and, on failure, `error` (the
149+
/// activity's reason, e.g. the permission was refused).
150+
pub fn answer(&mut self, id: i64, paths: Option<Vec<String>>, error: Option<String>) {
151+
let Some(tx) = self.waiting.remove(&id) else {
152+
log::warn!("camera roll {id}: an answer nothing waits for; dropped");
153+
return;
154+
};
155+
let answer = match (paths, error) {
156+
(_, Some(e)) if !e.is_empty() => Err(e),
157+
(Some(p), _) => Ok(p),
158+
(None, _) => Err("the camera roll could not be read (see the log)".into()),
159+
};
160+
if tx.send(answer).is_err() {
161+
log::warn!("camera roll {id}: answered, but nothing is waiting any more");
162+
}
163+
}
164+
}
165+
126166
/// A picker to show.
127167
#[derive(Clone, Debug, PartialEq, Eq)]
128168
pub struct PickRequest {
@@ -270,11 +310,13 @@ mod imp {
270310
use jni::sys::jlong;
271311
use jni::{JNIEnv, JavaVM, NativeMethod};
272312

273-
use super::{Answers, CopyProgress, Error, PickRequest, Unclaimed};
313+
use super::{Answers, CopyProgress, Error, PickRequest, RollAnswers, Unclaimed};
274314

275315
/// Pickers that are up, by the id the activity answers with, and answers nothing waits for.
276316
static PENDING: Mutex<Option<Answers>> = Mutex::new(None);
277317
static NEXT_ID: AtomicI64 = AtomicI64::new(1);
318+
/// Camera-roll listings that are running.
319+
static ROLLS: Mutex<Option<RollAnswers>> = Mutex::new(None);
278320
/// Asks the UI for a frame (set by the app: an answer must not wait for the next touch).
279321
static WAKER: OnceLock<Box<dyn Fn() + Send + Sync>> = OnceLock::new();
280322
/// Where copies report (set by the app once its session exists).
@@ -312,6 +354,11 @@ mod imp {
312354
fn_ptr: native_copy_progress as *mut std::ffi::c_void,
313355
},
314356
NativeMethod { name: "nativeCopyEnded".into(), sig: "(J)V".into(), fn_ptr: native_copy_ended as *mut std::ffi::c_void },
357+
NativeMethod {
358+
name: "nativeCameraRoll".into(),
359+
sig: "(J[Ljava/lang/String;Ljava/lang/String;)V".into(),
360+
fn_ptr: native_camera_roll as *mut std::ffi::c_void,
361+
},
315362
crate::opened::native_method(),
316363
];
317364
env.register_native_methods(&class, &methods).map_err(|e| jni_error("register the native callbacks", e))?;
@@ -369,6 +416,23 @@ mod imp {
369416
Ok(rx)
370417
}
371418

419+
/// Lists the photos in the camera roll (DCIM/Camera, through MediaStore), asking for the
420+
/// photo permission first when the app lacks it. Photos the app can read where they are
421+
/// come back as their paths; others are copied (in the activity stack) first.
422+
pub fn camera_roll(&self) -> Result<Receiver<super::CameraRoll>, Error> {
423+
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
424+
let rx = rolls(|r| r.wait(id));
425+
let result = self.call("startCameraRoll", |env, activity| {
426+
env.call_method(activity, "startCameraRoll", "(J)V", &[JValue::Long(id)])?;
427+
Ok(())
428+
});
429+
if let Err(e) = result {
430+
rolls(|r| r.forget(id));
431+
return Err(e);
432+
}
433+
Ok(rx)
434+
}
435+
372436
/// Sets where the activity's copies of picked documents report their progress.
373437
pub fn set_copy_progress(&self, sink: std::sync::Arc<dyn CopyProgress>) {
374438
*COPIES.lock().unwrap_or_else(PoisonError::into_inner) = Some(sink);
@@ -439,6 +503,29 @@ mod imp {
439503
f(guard.get_or_insert_with(Answers::default))
440504
}
441505

506+
fn rolls<R>(f: impl FnOnce(&mut RollAnswers) -> R) -> R {
507+
let mut guard = ROLLS.lock().unwrap_or_else(PoisonError::into_inner);
508+
f(guard.get_or_insert_with(RollAnswers::default))
509+
}
510+
511+
/// `void nativeCameraRoll(long id, String[] paths, String error)`: the answer to
512+
/// [`Host::camera_roll`].
513+
extern "system" fn native_camera_roll<'l>(mut env: JNIEnv<'l>, _this: JObject<'l>, id: jlong, paths: JObjectArray<'l>, error: JString<'l>) {
514+
// a panic must never unwind into the JVM
515+
let answered = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
516+
let list = read_strings(&mut env, &paths).unwrap_or_else(|e| {
517+
log::error!("camera roll answer unreadable: {e}");
518+
None
519+
});
520+
let error: Option<String> = if error.is_null() { None } else { env.get_string(&error).map(Into::into).ok() };
521+
rolls(|r| r.answer(id, list, error));
522+
wake();
523+
}));
524+
if answered.is_err() {
525+
log::error!("camera roll answer: a panic was caught");
526+
}
527+
}
528+
442529
fn string_array<'l>(env: &mut JNIEnv<'l>, items: &[String]) -> jni::errors::Result<JObjectArray<'l>> {
443530
let len = i32::try_from(items.len()).unwrap_or(i32::MAX);
444531
let array = env.new_object_array(len, "java/lang/String", JObject::null())?;
@@ -740,6 +827,25 @@ mod tests {
740827
assert!(a.take_unclaimed().is_empty());
741828
}
742829

830+
#[test]
831+
fn camera_roll_answers_carry_the_photos_or_the_reason() {
832+
let mut r = RollAnswers::default();
833+
let ok = r.wait(1);
834+
let denied = r.wait(2);
835+
let broken = r.wait(3);
836+
r.answer(1, Some(vec!["/storage/emulated/0/DCIM/Camera/IMG_1.jpg".into()]), None);
837+
r.answer(2, None, Some("access to photos was refused".into()));
838+
r.answer(3, None, None);
839+
// an answer for a listing that is gone is dropped, not a panic
840+
r.answer(99, Some(vec![]), None);
841+
assert_eq!(ok.try_recv().unwrap(), Ok(vec!["/storage/emulated/0/DCIM/Camera/IMG_1.jpg".to_string()]));
842+
assert_eq!(denied.try_recv().unwrap(), Err("access to photos was refused".to_string()));
843+
assert!(broken.try_recv().unwrap().is_err());
844+
let forgotten = r.wait(4);
845+
r.forget(4);
846+
assert!(matches!(forgotten.try_recv(), Err(std::sync::mpsc::TryRecvError::Disconnected)));
847+
}
848+
743849
#[test]
744850
fn kinds_have_distinct_codes() {
745851
let codes = [PickKind::Files, PickKind::File, PickKind::Folder, PickKind::Save].map(PickKind::code);

‎crates/ui-egui/src/camera_roll.rs‎

Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
//! The device's camera roll as an import source (Android): `file.addCameraRoll` asks the host
2+
//! ([`crate::Services::camera_roll`]) for the photos in DCIM/Camera, which it lists through the
3+
//! system's media store (asking for the photo permission first), and opens the import review on
4+
//! them, as Import from Folder… does. On the first start a window asks whether to add it; the
5+
//! answer is kept in the UI settings (`camera_roll_asked`), and Settings ▸ Folders offers it again.
6+
7+
use egui::{Align2, RichText, vec2};
8+
use serde_json::Value;
9+
use std::sync::mpsc::TryRecvError;
10+
11+
use crate::LccApp;
12+
use crate::theme::Tokens;
13+
use crate::widgets::register;
14+
15+
/// `file.addCameraRoll`: starts listing the camera roll; the import review opens when it answers.
16+
pub fn start(app: &mut LccApp) -> Result<Value, String> {
17+
app.ui.camera_roll_asked = true;
18+
if app.pending_camera_roll.is_some() {
19+
return Ok(Value::Null);
20+
}
21+
let Some(list) = app.services.camera_roll.as_mut() else {
22+
return Err("there is no camera roll on this platform".into());
23+
};
24+
app.pending_camera_roll = Some(list()?);
25+
Ok(Value::Null)
26+
}
27+
28+
/// Each frame: the host's answer opens the import review, or says why there is nothing to import.
29+
pub fn poll(app: &mut LccApp, ctx: &egui::Context) {
30+
let Some(rx) = &app.pending_camera_roll else { return };
31+
let answer = match rx.try_recv() {
32+
Ok(a) => a,
33+
Err(TryRecvError::Empty) => {
34+
ctx.request_repaint_after(std::time::Duration::from_millis(250));
35+
return;
36+
}
37+
Err(TryRecvError::Disconnected) => Err(crate::i18n::tr("the camera roll could not be read").to_string()),
38+
};
39+
app.pending_camera_roll = None;
40+
match answer {
41+
Ok(paths) if paths.is_empty() => app.toast(ctx, crate::i18n::tr("There are no photos in the camera roll")),
42+
Ok(paths) => {
43+
if let Err(e) = crate::import::open(app, paths) {
44+
app.toast_error(ctx, e);
45+
}
46+
}
47+
Err(e) => app.toast_error(ctx, format!("{}: {e}", crate::i18n::tr("Couldn't add the camera roll"))),
48+
}
49+
}
50+
51+
/// Whether the first-start question is due.
52+
pub fn prompt_due(app: &LccApp) -> bool {
53+
app.services.camera_roll.is_some() && !app.ui.camera_roll_asked && app.library_problem.is_none() && app.pending_camera_roll.is_none()
54+
}
55+
56+
/// The first-start question: add the camera roll to the library?
57+
pub fn prompt(app: &mut LccApp, ctx: &egui::Context) {
58+
if !prompt_due(app) {
59+
return;
60+
}
61+
let t = Tokens::get(ctx);
62+
let mut choice = None;
63+
let frame = egui::Frame::window(&ctx.global_style()).inner_margin(egui::Margin::symmetric(18, 14));
64+
egui::Window::new(crate::i18n::tr("Add Your Camera Roll?"))
65+
.id(egui::Id::new("camera-roll-prompt"))
66+
.order(egui::Order::Foreground)
67+
.collapsible(false)
68+
.resizable(false)
69+
.frame(frame)
70+
.anchor(Align2::CENTER_CENTER, [0.0, 0.0])
71+
.default_width(420.0)
72+
.show(ctx, |ui| {
73+
ui.set_width(400.0);
74+
ui.spacing_mut().item_spacing.y = 8.0;
75+
ui.add(
76+
egui::Label::new(
77+
RichText::new(crate::i18n::tr(
78+
"{app} can add the photos in your camera roll (DCIM/Camera) to the library. Android asks you to allow access to your photos first.",
79+
))
80+
.color(t.text),
81+
)
82+
.wrap(),
83+
);
84+
ui.label(RichText::new(crate::i18n::tr("You can add it later from Settings ▸ Folders.")).color(t.text_dim));
85+
ui.horizontal(|ui| {
86+
for (id, label, add) in [("cameraRollAdd", "Add Camera Roll", true), ("cameraRollNotNow", "Not Now", false)] {
87+
let r = ui.add(egui::Button::new(crate::i18n::tr(label)).min_size(vec2(0.0, 26.0)));
88+
register(ui.ctx(), format!("button:{id}"), r.rect);
89+
if r.clicked() {
90+
choice = Some(add);
91+
}
92+
}
93+
});
94+
});
95+
match choice {
96+
Some(true) => {
97+
if let Err(e) = app.run("file.addCameraRoll", Value::Null) {
98+
app.toast_error(ctx, e);
99+
}
100+
}
101+
Some(false) => app.ui.camera_roll_asked = true,
102+
None => {}
103+
}
104+
}
105+
106+
#[cfg(test)]
107+
mod tests {
108+
use super::*;
109+
use serde_json::json;
110+
use std::sync::mpsc::{Sender, channel};
111+
use std::sync::{Arc, Mutex};
112+
113+
type Answer = Arc<Mutex<Option<Sender<Result<Vec<String>, String>>>>>;
114+
115+
fn app_with_roll() -> (LccApp, Answer) {
116+
let answer: Answer = Default::default();
117+
let a = answer.clone();
118+
let services = crate::Services {
119+
camera_roll: Some(Box::new(move || {
120+
let (tx, rx) = channel();
121+
*a.lock().unwrap() = Some(tx);
122+
Ok(rx)
123+
})),
124+
..Default::default()
125+
};
126+
(LccApp::new(lcc_engine::Session::new(), services), answer)
127+
}
128+
129+
#[test]
130+
fn without_a_camera_roll_nothing_is_asked_and_the_command_says_why() {
131+
let mut app = LccApp::new(lcc_engine::Session::new(), crate::Services::default());
132+
assert!(!prompt_due(&app));
133+
assert!(app.run("file.addCameraRoll", json!({})).is_err());
134+
}
135+
136+
#[test]
137+
fn the_first_start_asks_once_and_the_answer_is_remembered() {
138+
let (mut app, _) = app_with_roll();
139+
assert!(prompt_due(&app));
140+
app.run("file.addCameraRoll", json!({})).unwrap();
141+
assert!(app.ui.camera_roll_asked);
142+
assert!(!prompt_due(&app));
143+
// the answer survives the settings file
144+
let saved: crate::UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap();
145+
assert!(saved.camera_roll_asked);
146+
// an old settings file without it asks
147+
let old: crate::UiState = serde_json::from_value(json!({})).unwrap();
148+
assert!(!old.camera_roll_asked);
149+
}
150+
151+
#[test]
152+
fn a_refused_permission_is_reported_and_the_roll_can_be_asked_for_again() {
153+
let ctx = egui::Context::default();
154+
let (mut app, answer) = app_with_roll();
155+
app.run("file.addCameraRoll", json!({})).unwrap();
156+
answer.lock().unwrap().take().unwrap().send(Err("permission denied".into())).unwrap();
157+
poll(&mut app, &ctx);
158+
assert!(app.pending_camera_roll.is_none());
159+
// asking again starts a new listing
160+
app.run("file.addCameraRoll", json!({})).unwrap();
161+
assert!(app.pending_camera_roll.is_some());
162+
// a host that went away without answering is an error too, never a hang
163+
drop(answer.lock().unwrap().take());
164+
poll(&mut app, &ctx);
165+
assert!(app.pending_camera_roll.is_none());
166+
}
167+
168+
#[test]
169+
fn the_camera_roll_opens_the_import_review() {
170+
let ctx = egui::Context::default();
171+
let (mut app, answer) = app_with_roll();
172+
app.run("file.addCameraRoll", json!({})).unwrap();
173+
let dir = std::env::temp_dir().join(format!("lc-camera-roll-{}", std::process::id()));
174+
std::fs::create_dir_all(&dir).unwrap();
175+
let img = lcc_raster::Rgba8::from_fn(8, 6, |x, y| [(x * 20) as u8, (y * 30) as u8, 9, 255]);
176+
let o = lcc_engine::export::ExportOptions { format: lcc_engine::export::ExportFormat::Png, ..Default::default() };
177+
let photo = dir.join("IMG_1.png");
178+
std::fs::write(&photo, lcc_engine::export::encode_image(&img, &o).unwrap()).unwrap();
179+
answer.lock().unwrap().take().unwrap().send(Ok(vec![photo.to_string_lossy().to_string()])).unwrap();
180+
poll(&mut app, &ctx);
181+
assert!(app.pending_camera_roll.is_none());
182+
assert!(app.scan.is_some(), "the import review's scan started");
183+
let _ = std::fs::remove_dir_all(&dir);
184+
}
185+
}

0 commit comments

Comments
 (0)