day_piece_camera/lib.rs
1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-piece-camera: a camera viewfinder with photo capture for Day apps.
5//!
6//! An external Day Piece: one Rust API in front, the platform's camera behind it (AVFoundation
7//! on iOS, CameraX on Android, the NDK camera kit on HarmonyOS), declared as
8//! `[package.metadata.day.*]` in Cargo.toml and staged by `day build`. The renderers register
9//! link-time into each backend's slice; nothing in day knows this crate exists. The desktops and
10//! the web have no camera arm: there the kind realizes day's placeholder leaf, and [`support`]
11//! answers `Unsupported` so an app can leave its camera page out.
12//!
13//! ```ignore
14//! let shutter = Trigger::new();
15//! let state = Signal::new(CameraState::Idle);
16//! let photo: Signal<Option<Photo>> = Signal::new(None);
17//! camera()
18//! .auto_request() // ask for the permission the first time the session is wanted
19//! .capture(shutter) // fire it to take a photo
20//! .state(state) // what the camera is doing
21//! .photo(photo) // the last capture, a JPEG in the app's cache directory
22//! .frame(320.0, 240.0)
23//! ```
24//!
25//! The piece never starts a session without the camera permission: it reads
26//! `day_part_permissions::status` first, and only [`Camera::auto_request`] makes it ask.
27//! Prompting otherwise belongs to the app, which owns the rationale and decides when a system
28//! dialog is welcome.
29
30use std::io;
31use std::path::{Path, PathBuf};
32use std::sync::Arc;
33
34use day_core::{BuildCx, Flex, Piece, RNode, with_tree};
35use day_part_permissions::{self as perms, Permission, Status};
36use day_pieces::{Decorated, IntoReactive, Reactive};
37use day_reactive::{AnyBinding, Binding, Signal, Trigger, on_main, watch};
38use day_spec::Event;
39
40pub const KIND: &str = "day.piece.camera";
41
42/// Which camera the viewfinder shows.
43#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
44pub enum Facing {
45 /// The rear camera, the one a photo is usually taken with.
46 #[default]
47 Back,
48 /// The screen-side camera.
49 Front,
50}
51
52impl Facing {
53 /// The value that crosses the native boundary: 0 back, 1 front.
54 pub fn code(self) -> i32 {
55 match self {
56 Facing::Back => 0,
57 Facing::Front => 1,
58 }
59 }
60
61 /// The other camera.
62 #[must_use]
63 pub fn flipped(self) -> Facing {
64 match self {
65 Facing::Back => Facing::Front,
66 Facing::Front => Facing::Back,
67 }
68 }
69}
70
71/// Full props (realize). `active` is whether the session should run from the first frame; it
72/// is only ever true when the permission is already held.
73#[derive(Clone, Debug, Default, PartialEq)]
74pub struct CameraProps {
75 pub facing: Facing,
76 pub active: bool,
77}
78
79/// Sparse reconcile patch: the commands Rust sends the native camera after build.
80#[derive(Clone, Debug, PartialEq)]
81pub enum CameraPatch {
82 /// Run the session. Sent only once the permission is held.
83 Start,
84 /// Stop the session and release the camera.
85 Stop,
86 /// Take one photo; the native side answers with a [`report::PHOTO`] event.
87 Capture,
88 /// Switch cameras, live.
89 Facing(Facing),
90 /// HarmonyOS only: the ArkTS surface the preview renders into is ready; the text is its id.
91 /// The front-end forwards the [`report::SURFACE`] event as this patch so the renderer can
92 /// hand the surface to the NDK camera. Every other backend ignores it.
93 Surface(String),
94}
95
96/// What the camera is doing, as the native side reports it.
97#[derive(Clone, Debug, Default, PartialEq, Eq)]
98pub enum CameraState {
99 /// No session: never started, stopped, or waiting for a permission the app has not asked for.
100 #[default]
101 Idle,
102 /// The session is being configured and started.
103 Starting,
104 /// The preview is live and a capture will succeed.
105 Running,
106 /// This device has no usable camera: the iOS Simulator, a desktop without one.
107 Unavailable,
108 /// The permission was refused, or the OS restricts it, so the session cannot start.
109 Denied,
110 /// The native side failed; the text is its message.
111 Error(String),
112}
113
114impl CameraState {
115 /// The locale-independent label a script can assert on.
116 pub fn label(&self) -> &'static str {
117 match self {
118 CameraState::Idle => "idle",
119 CameraState::Starting => "starting",
120 CameraState::Running => "running",
121 CameraState::Unavailable => "unavailable",
122 CameraState::Denied => "denied",
123 CameraState::Error(_) => "error",
124 }
125 }
126
127 /// The state a native report means. [`report::PHOTO`] is not a state and maps to `None`.
128 pub fn from_report(num: f64, text: &str) -> Option<CameraState> {
129 Some(match num as i32 {
130 report::STOPPED => CameraState::Idle,
131 report::STARTING => CameraState::Starting,
132 report::RUNNING => CameraState::Running,
133 report::UNAVAILABLE => CameraState::Unavailable,
134 report::DENIED => CameraState::Denied,
135 report::ERROR => CameraState::Error(text.to_string()),
136 _ => return None,
137 })
138 }
139}
140
141/// The codes the native sides report through `Event::Custom { num, .. }`. `num` is the
142/// discriminator: a Custom event's `tag` is empty across JNI and the C ABI, so it is never
143/// matched on.
144pub mod report {
145 pub const STOPPED: i32 = 0;
146 pub const STARTING: i32 = 1;
147 pub const RUNNING: i32 = 2;
148 pub const UNAVAILABLE: i32 = 3;
149 pub const DENIED: i32 = 4;
150 pub const ERROR: i32 = 5;
151 /// A photo landed on disk. `text` is `path`, `width` and `height`, 0x1F-separated.
152 pub const PHOTO: i32 = 6;
153 /// HarmonyOS only: the ArkTS side's preview surface exists; `text` is its surface id.
154 pub const SURFACE: i32 = 7;
155}
156
157/// A photo the camera took: a JPEG under the app's cache directory.
158///
159/// The file is the app's to keep, move, or delete; the piece never touches the photo library,
160/// so no Photos permission is involved. [`Photo::bytes`] reads it on demand.
161#[derive(Clone, Debug, PartialEq, Eq)]
162pub struct Photo {
163 pub path: PathBuf,
164 pub width: u32,
165 pub height: u32,
166}
167
168impl Photo {
169 /// Parse a [`report::PHOTO`] payload: `path`, then the pixel size, 0x1F-separated. A
170 /// payload without a size is still a photo; the size then reads 0 × 0.
171 pub fn from_report(text: &str) -> Option<Photo> {
172 let mut parts = text.split('\u{1f}');
173 let path = parts.next().filter(|p| !p.is_empty())?;
174 let width = parts
175 .next()
176 .and_then(|w| w.trim().parse().ok())
177 .unwrap_or(0);
178 let height = parts
179 .next()
180 .and_then(|h| h.trim().parse().ok())
181 .unwrap_or(0);
182 Some(Photo {
183 path: PathBuf::from(path),
184 width,
185 height,
186 })
187 }
188
189 /// The JPEG bytes, read from the cache file; shared, since a photo is large and a viewer
190 /// keeps a reference to it.
191 ///
192 /// # Errors
193 ///
194 /// Returns the I/O error when the cache file cannot be read.
195 pub fn bytes(&self) -> io::Result<Arc<Vec<u8>>> {
196 std::fs::read(&self.path).map(Arc::new)
197 }
198
199 /// The file's name, for a caption.
200 pub fn file_name(&self) -> String {
201 Path::new(&self.path)
202 .file_name()
203 .map_or_default(|n| n.to_string_lossy().into_owned())
204 }
205}
206
207/// What this backend realizes: `Native` where a camera arm is compiled in, `Unsupported`
208/// elsewhere, where the kind renders day's placeholder leaf. `Native` is a promise about the
209/// code, not the hardware; the iOS Simulator reports [`CameraState::Unavailable`] at run time.
210pub fn support() -> day_spec::Support {
211 if cfg!(any(
212 all(feature = "uikit", target_os = "ios"),
213 all(feature = "material", target_os = "android"),
214 all(feature = "arkui", target_env = "ohos"),
215 )) {
216 day_spec::Support::Native
217 } else {
218 day_spec::Support::Unsupported
219 }
220}
221
222/// A native camera viewfinder. Bind the session to `.active(signal)`, take photos with
223/// `.capture(trigger)`, and read them back through `.photo(signal)`.
224#[must_use]
225pub struct Camera {
226 facing: Reactive<Facing>,
227 active: Reactive<bool>,
228 auto_request: bool,
229 capture: Option<Trigger>,
230 state: Option<AnyBinding<CameraState>>,
231 photo: Option<AnyBinding<Option<Photo>>>,
232}
233
234/// `camera()`: the rear camera's live preview, running whenever the permission is held.
235pub fn camera() -> Camera {
236 Camera {
237 facing: Reactive::Const(Facing::Back),
238 active: Reactive::Const(true),
239 auto_request: false,
240 capture: None,
241 state: None,
242 photo: None,
243 }
244}
245
246#[day_pieces::builder(CameraBuilder)]
247impl Camera {
248 /// Which camera to show: a constant, a `Signal<Facing>`, or a `Fn() -> Facing`. When it is
249 /// reactive the viewfinder switches live.
250 pub fn facing<M>(mut self, facing: impl IntoReactive<Facing, M>) -> Self {
251 self.facing = facing.into_reactive();
252 self
253 }
254
255 /// Whether the session should run: a constant, a `Signal<bool>`, or a closure. Default
256 /// true. The session runs only while this is true and the permission is held; `false`
257 /// stops it and releases the camera.
258 pub fn active<M>(mut self, active: impl IntoReactive<bool, M>) -> Self {
259 self.active = active.into_reactive();
260 self
261 }
262
263 /// Ask for the camera permission the first time the session is wanted and the OS has not
264 /// decided yet. Opt-in: an app that wants its own rationale screen first requests through
265 /// `day_part_permissions` itself and leaves this off.
266 pub fn auto_request(mut self) -> Self {
267 self.auto_request = true;
268 self
269 }
270
271 /// Take a photo whenever `trigger` fires.
272 pub fn capture(mut self, trigger: Trigger) -> Self {
273 self.capture = Some(trigger);
274 self
275 }
276
277 /// Where the camera reports what it is doing: a `Signal<CameraState>` or any other binding.
278 pub fn state(mut self, state: impl Binding<CameraState>) -> Self {
279 self.state = Some(AnyBinding::new(state));
280 self
281 }
282
283 /// Where each capture lands: a `Signal<Option<Photo>>` or any other binding.
284 pub fn photo(mut self, photo: impl Binding<Option<Photo>>) -> Self {
285 self.photo = Some(AnyBinding::new(photo));
286 self
287 }
288}
289
290impl Piece for Camera {
291 fn build(self, cx: &mut BuildCx) -> RNode {
292 let Camera {
293 facing,
294 active,
295 auto_request,
296 capture,
297 state,
298 photo,
299 } = self;
300 let set_state = move |next: CameraState| {
301 if let Some(state) = state
302 && state.get_untracked() != next
303 {
304 state.set(next);
305 }
306 };
307 // Whether the first frame may run: only with the permission already held. Anything else
308 // starts idle and is resolved reactively below, after the node exists to patch.
309 let wanted = active.get_untracked();
310 let held = perms::status(Permission::Camera) == Status::Granted;
311 let props = CameraProps {
312 facing: facing.get_untracked(),
313 active: wanted && held,
314 };
315 // A viewfinder fills the space it is offered (constrain via `.frame(w, h)`).
316 let node = cx.leaf(
317 KIND,
318 &props,
319 Flex {
320 grow_w: true,
321 grow_h: true,
322 ..Default::default()
323 },
324 );
325 let send = move |patch: CameraPatch| {
326 with_tree(|t| t.patch(node, Box::new(patch), false));
327 };
328 // A permission answer arrives on an unspecified thread, and the state binding never
329 // leaves the main one: the answer crosses back through this relay's `Setter`, and the
330 // binding is written from here.
331 let denied_relay: Signal<Option<CameraState>> = Signal::new(None);
332 watch(
333 move || denied_relay.get(),
334 move |next, _| {
335 if let Some(next) = next {
336 set_state(next.clone());
337 }
338 },
339 );
340
341 // The session follows `active`, gated on the permission. Denied and restricted are
342 // reported as such; an undecided permission is asked for only under `auto_request`,
343 // and otherwise leaves the camera idle for the app to resolve.
344 let start = move || match perms::status(Permission::Camera) {
345 Status::Granted => send(CameraPatch::Start),
346 Status::Prompt if auto_request => {
347 set_state(CameraState::Starting);
348 // The completion runs on an unspecified thread; the patch has to be issued on
349 // the main thread, where the tree lives, and a denial reaches the state binding
350 // through the relay's `Setter`.
351 let denied = denied_relay.setter();
352 perms::request(Permission::Camera, move |status| {
353 on_main(move || {
354 if status == Status::Granted {
355 with_tree(|t| t.patch(node, Box::new(CameraPatch::Start), false));
356 } else {
357 denied.set(Some(CameraState::Denied));
358 }
359 });
360 });
361 }
362 Status::Prompt => set_state(CameraState::Idle),
363 Status::Denied | Status::Restricted => set_state(CameraState::Denied),
364 // Ungated platforms answer Granted; the rest have no camera arm to start.
365 _ => set_state(CameraState::Unavailable),
366 };
367 if wanted && !held {
368 start();
369 }
370 if let Reactive::Dyn(read) = active {
371 // Only a change moves the session: the watch re-runs on any dependency of the
372 // closure, and re-sending Start to a running camera would reconfigure it.
373 let last = std::rc::Rc::new(std::cell::Cell::new(wanted));
374 watch(
375 move || read(),
376 move |now, _| {
377 if *now == last.get() {
378 return;
379 }
380 last.set(*now);
381 if *now {
382 start();
383 } else {
384 send(CameraPatch::Stop);
385 }
386 },
387 );
388 }
389 if let Reactive::Dyn(read) = facing {
390 let last = std::rc::Rc::new(std::cell::Cell::new(props.facing));
391 watch(
392 move || read(),
393 move |f, _| {
394 if *f != last.get() {
395 last.set(*f);
396 send(CameraPatch::Facing(*f));
397 }
398 },
399 );
400 }
401 if let Some(capture) = capture {
402 watch(
403 move || capture.track(),
404 move |(), _| send(CameraPatch::Capture),
405 );
406 }
407 cx.on(node, move |ev| {
408 if let Event::Custom { num, text, .. } = ev {
409 if *num as i32 == report::SURFACE {
410 send(CameraPatch::Surface(text.clone()));
411 return;
412 }
413 if *num as i32 == report::PHOTO {
414 if let Some(photo) = photo
415 && let Some(shot) = Photo::from_report(text)
416 {
417 photo.set(Some(shot));
418 }
419 return;
420 }
421 if let Some(next) = CameraState::from_report(*num, text) {
422 set_state(next);
423 }
424 }
425 });
426 node
427 }
428}
429
430// ---------------------------------------------------------------------------
431// Per-toolkit native renderers: the three mobile toolkits. Each registers a `Renderer`
432// link-time into its backend's `RENDERERS` slice; `#[cfg]` gates each to its feature + target.
433// ---------------------------------------------------------------------------
434
435day_pieces::glue_modules!(uikit, material, arkui);
436
437#[cfg(test)]
438mod tests {
439 use super::*;
440
441 #[test]
442 fn photo_report_parses_path_and_size() {
443 let p = Photo::from_report("/tmp/day-camera/a.jpg\u{1f}4032\u{1f}3024").unwrap();
444 assert_eq!(p.path, PathBuf::from("/tmp/day-camera/a.jpg"));
445 assert_eq!((p.width, p.height), (4032, 3024));
446 assert_eq!(p.file_name(), "a.jpg");
447 }
448
449 #[test]
450 fn photo_report_without_size_is_still_a_photo() {
451 let p = Photo::from_report("/tmp/x.jpg").unwrap();
452 assert_eq!((p.width, p.height), (0, 0));
453 assert!(Photo::from_report("").is_none());
454 }
455
456 #[test]
457 fn state_reports_map_and_photo_is_not_a_state() {
458 assert_eq!(
459 CameraState::from_report(f64::from(report::RUNNING), ""),
460 Some(CameraState::Running)
461 );
462 assert_eq!(
463 CameraState::from_report(f64::from(report::ERROR), "boom"),
464 Some(CameraState::Error("boom".into()))
465 );
466 assert_eq!(
467 CameraState::from_report(f64::from(report::PHOTO), "x"),
468 None
469 );
470 assert_eq!(CameraState::Unavailable.label(), "unavailable");
471 }
472
473 #[test]
474 fn facing_codes_round_trip() {
475 assert_eq!(Facing::Back.code(), 0);
476 assert_eq!(Facing::Front.code(), 1);
477 assert_eq!(Facing::Back.flipped(), Facing::Front);
478 }
479}