diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index 1c13d4e..f54193c 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -193,16 +193,17 @@ export const t = { usbCamera: { button: "USB", title: "Câmara por USB", - help: "Com a câmara ligada por cabo, cada foto nova entra no evento abaixo. As que já estavam no cartão ficam lá: isto é o tether, não uma cópia do cartão.", + help: "Com a câmara ligada por cabo, vês o cartão e cada foto nova. Nada sobe sozinho: escolhes o que descarregar para o evento abaixo.", none: "Nenhuma câmara ligada por cabo.", - tetherOn: "Tether ligado", - tetherOff: "Tether desligado", - turnOn: "Ligar tether", - turnOff: "Desligar tether", + tetherOn: "Cabo ligado", + tetherOff: "Cabo desligado", + turnOn: "Ligar cabo", + turnOff: "Desligar cabo", opening: "A ligar à câmara…", - tethered: "A receber fotos novas", + tethered: "Câmara pronta — escolhe o que descarregar", busy: "A câmara está ocupada por outra app (o EOS Utility, por exemplo). Fecha-a: o cabo só pode estar com uma de cada vez. A tentar outra vez sozinho.", - idle: "Tether desligado", + idle: "Cabo desligado", + listing: "A ler o cartão…", rawKept: "O RAW fica na pasta de trabalho, ao lado do JPEG.", outdated: "Esta versão da app de computador ainda não lê a câmara por USB. Instala a versão nova.", received: (n: number) => (n === 1 ? "1 foto recebida" : `${n} fotos recebidas`), @@ -213,6 +214,16 @@ export const t = { clockBehind: (n: number) => `A câmara estava ${n} s atrasada. O relógio ficou igual ao deste computador.`, clockUnsupported: "Esta câmara não deixa acertar o relógio pelo cabo.", clockSync: "Acertar relógio outra vez", + card: "Cartão", + files: (n: number) => (n === 1 ? "1 ficheiro" : `${n} ficheiros`), + newShot: "nova", + imported: "já puxada", + selectNew: "Seleccionar novas", + selectAll: "Todas", + selectNone: "Nenhuma", + refresh: "Actualizar lista", + download: (n: number) => (n === 1 ? "Descarregar 1" : `Descarregar ${n}`), + emptyCard: "O cartão ainda não tem fotos listadas.", }, squad: { title: "Pessoas", diff --git a/apps/app/src/library/UsbCamera.test.tsx b/apps/app/src/library/UsbCamera.test.tsx index ebd3961..6f9fc97 100644 --- a/apps/app/src/library/UsbCamera.test.tsx +++ b/apps/app/src/library/UsbCamera.test.tsx @@ -3,12 +3,17 @@ import type { EventSummary } from "@photoreport/sdk"; import { describe, expect, it, vi } from "vitest"; import type { Invoke } from "./LocalFtp.js"; import type { UploadStatus } from "./uploads.js"; -import { UsbCameraButton, type UsbStatus, useUsbCamera } from "./UsbCamera.js"; +import { UsbCameraButton, type UsbStatus, useUsbCamera, withSidecars } from "./UsbCamera.js"; const camera: UsbStatus = { supported: true, tether: true, - devices: [{ id: "abc", name: "Canon Digital Camera", vendorId: 1193, productId: 13075, state: "tethered", error: null }], + devices: [{ id: "abc", name: "Canon Digital Camera", vendorId: 1193, productId: 13075, state: "tethered", error: null, catalogReady: true }], + files: [ + { name: "IMG_0001.JPG", size: 10, isNew: true, imported: false }, + { name: "IMG_0001.CR3", size: 20, isNew: true, imported: false }, + { name: "IMG_0002.JPG", size: 10, isNew: false, imported: false }, + ], }; function shell(files: { path: string; name: string; size: number; modifiedMs: number }[]) { @@ -29,8 +34,18 @@ function shell(files: { path: string; name: string; size: number; modifiedMs: nu const event = { id: "ev1", title: "", home: "Portugal", away: "Suíça", startsAt: "2026-11-04T19:00:00Z" } as EventSummary; +const usbStub = { + status: camera, + outdated: false, + counts: { received: 0, sent: 0, failed: 0 }, + setTether: vi.fn(), + syncClock: vi.fn(), + importFiles: vi.fn(), + refresh: vi.fn(), +}; + describe("usb tether", () => { - it("sends each new shot to the target event and files the original", async () => { + it("pulls only files the shell already downloaded (chosen on the camera panel)", async () => { const { invoke, sent } = shell([{ path: "/ingest/.usb/IMG_0001.JPG", name: "IMG_0001.JPG", size: 10, modifiedMs: 1 }]); const added: { name: string; eventId: string | undefined }[] = []; const add = (files: Iterable, eventId?: string, onSettled?: (f: File, s: UploadStatus) => void) => { @@ -46,30 +61,16 @@ describe("usb tether", () => { it("uses the open event when a camera is plugged in and none is chosen", async () => { const setTarget = vi.fn(); - const usb = { - status: camera, - outdated: false, - counts: { received: 0, sent: 0, failed: 0 }, - setTether: vi.fn(), - syncClock: vi.fn(), - }; - render(); + render(); await waitFor(() => expect(setTarget).toHaveBeenCalledWith(event)); expect(screen.getByRole("button", { name: /USB/ })).toBeTruthy(); }); it("leaves a chosen event alone", () => { const setTarget = vi.fn(); - const usb = { - status: camera, - outdated: false, - counts: { received: 0, sent: 0, failed: 0 }, - setTether: vi.fn(), - syncClock: vi.fn(), - }; render( { ); expect(setTarget).not.toHaveBeenCalled(); }); + + it("adds the RAW sidecar when a JPEG is selected for download", () => { + expect(withSidecars(["IMG_0001.JPG"], camera.files).sort()).toEqual(["IMG_0001.CR3", "IMG_0001.JPG"]); + expect(withSidecars(["IMG_0002.JPG"], camera.files)).toEqual(["IMG_0002.JPG"]); + }); }); diff --git a/apps/app/src/library/UsbCamera.tsx b/apps/app/src/library/UsbCamera.tsx index 3414507..90a67bb 100644 --- a/apps/app/src/library/UsbCamera.tsx +++ b/apps/app/src/library/UsbCamera.tsx @@ -1,5 +1,5 @@ import type { EventSummary } from "@photoreport/sdk"; -import { useCallback, useEffect, useRef, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { t } from "../i18n.js"; import { asArrayBuffer } from "../platform.js"; import { type FtpTarget, type IncomingFile, type Invoke, eventLabel } from "./LocalFtp.js"; @@ -11,19 +11,30 @@ export interface UsbCamera { name: string; vendorId: number; productId: number; - /** opening: session starting; tethered: new shots come in; busy: another app holds the cable; idle: tether off. */ + /** opening: session starting; tethered: ready to pick files; busy: another app holds the cable; idle: off. */ state: "opening" | "tethered" | "busy" | "idle"; error: string | null; /** synced: clock set to this Mac; unsupported: the body refuses; null: not tried yet. */ clock?: "synced" | "unsupported" | null; /** Seconds the camera was ahead of the Mac before the sync. */ clockOffset?: number | null; + /** True once the card listing is available. */ + catalogReady?: boolean; +} + +export interface UsbFile { + name: string; + size: number; + createdMs?: number | null; + isNew?: boolean; + imported?: boolean; } export interface UsbStatus { supported: boolean; tether: boolean; devices: UsbCamera[]; + files: UsbFile[]; } const tauriInvoke: Invoke = async (cmd, args) => (await import("@tauri-apps/api/core")).invoke(cmd, args); @@ -34,8 +45,8 @@ const POLL_MS = 1000; type Add = (files: Iterable, eventId?: string, onSettled?: (file: File, status: UploadStatus) => void, original?: PreviewOf) => void; /** - * Tethered shots (taken after the camera was plugged in) follow the same path as local FTP: a preview goes up - * to the target event and the original, plus the RAW beside it, moves to the event's work folder. + * USB camera: the shell lists the card (and each new shot). Chosen files are downloaded into the + * ingest folder; this hook then uploads them to the target event like local FTP. */ export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | null, invoke: Invoke = tauriInvoke) { const [status, setStatus] = useState(null); @@ -92,7 +103,6 @@ export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | nul const photos = files.filter((f) => /\.jpe?g$/i.test(f.name)); for (const raw of files) { if (/\.jpe?g$/i.test(raw.name)) continue; - // The RAW is not uploaded. If the JPEG of the same shot is filed, it takes this file with it. void invoke("ftp_sent", { path: raw.path, event: to?.title ?? "", date: to?.date ?? "" }).catch(() => {}); } if (!photos.length) return; @@ -130,13 +140,43 @@ export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | nul [invoke], ); - return { status, outdated, counts, setTether, syncClock }; + const importFiles = useCallback( + async (names: string[]) => { + if (!names.length) return; + try { + setStatus(await invoke("camera_import", { names })); + } catch { + setOutdated(true); + } + }, + [invoke], + ); + + const refresh = useCallback(async () => { + try { + setStatus(await invoke("camera_refresh")); + } catch { + setOutdated(true); + } + }, [invoke]); + + return { status, outdated, counts, setTether, syncClock, importFiles, refresh }; } export type UsbCameraState = ReturnType; const live = (d: UsbCamera) => d.state === "tethered" || d.state === "opening" || d.state === "busy"; +function stemOf(name: string) { + return name.replace(/\.[^.]+$/, "").toLowerCase(); +} + +/** JPEG names plus any RAW that shares the same stem (Canon CR3 beside the JPG, etc.). */ +export function withSidecars(selected: Iterable, files: UsbFile[]): string[] { + const want = new Set([...selected].map(stemOf)); + return files.filter((f) => want.has(stemOf(f.name))).map((f) => f.name); +} + /** Button + panel in the Library toolbar. Hidden where the shell has no USB cameras (Windows, Linux). */ export function UsbCameraButton({ usb, @@ -150,19 +190,50 @@ export function UsbCameraButton({ openEvent: EventSummary | undefined; }) { const [open, setOpen] = useState(false); + const [picked, setPicked] = useState>(() => new Set()); const { status, counts } = usb; const L = t.usbCamera; const devices = status?.devices ?? []; + const files = status?.files ?? []; const connected = devices.filter(live); const on = connected.some((d) => d.state === "tethered" || d.state === "opening"); + const catalogReady = devices.some((d) => d.catalogReady); + const jpegs = useMemo(() => files.filter((f) => /\.jpe?g$/i.test(f.name)), [files]); - // Plugging a body in, with no event chosen yet, uses the one open in the library. useEffect(() => { if (connected.length && !target && openEvent) setTarget(openEvent); }, [connected.length, target, openEvent, setTarget]); + // Drop selections that left the catalog (unplug / refresh). + useEffect(() => { + const names = new Set(files.map((f) => f.name)); + setPicked((prev) => { + let changed = false; + const next = new Set(); + for (const n of prev) { + if (names.has(n)) next.add(n); + else changed = true; + } + return changed ? next : prev; + }); + }, [files]); + if (status && !status.supported && !usb.outdated) return null; + const toggle = (name: string) => { + setPicked((prev) => { + const next = new Set(prev); + if (next.has(name)) next.delete(name); + else next.add(name); + return next; + }); + }; + + const download = () => { + const names = withSidecars(picked, files); + void usb.importFiles(names); + }; + return (
{open && ( -
+
{L.title} {status?.tether ? L.tetherOn : L.tetherOff} @@ -200,7 +271,7 @@ export function UsbCameraButton({
{d.name}
{d.state === "opening" && L.opening} - {d.state === "tethered" && L.tethered} + {d.state === "tethered" && (d.catalogReady ? L.tethered : L.listing)} {d.state === "idle" && L.idle} {d.state === "busy" && L.busy}
@@ -217,6 +288,56 @@ export function UsbCameraButton({ )}
))} + + {on && ( +
+
+ + {L.card} + {jpegs.length > 0 && {L.files(jpegs.length)}} + +
+ + + + +
+
+ {!catalogReady &&

{L.listing}

} + {catalogReady && jpegs.length === 0 &&

{L.emptyCard}

} + {jpegs.length > 0 && ( +
    + {jpegs.map((f) => { + const checked = picked.has(f.name); + return ( +
  • + toggle(f.name)} className="accent-accent" /> + + {f.isNew && !f.imported && {L.newShot}} + {f.imported && {L.imported}} +
  • + ); + })} +
+ )} + {picked.size > 0 && ( + + )} +
+ )} + {counts.received > 0 && (
{L.received(counts.received)} · {L.sent(counts.sent)} @@ -226,10 +347,7 @@ export function UsbCameraButton({

{L.rawKept}

{status && (
- {on && ( diff --git a/apps/desktop/package.json b/apps/desktop/package.json index f39f14d..3b389b2 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@photoreport/desktop", - "version": "0.3.25", + "version": "0.3.26", "private": true, "type": "module", "scripts": { diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index d4495a1..253b797 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "photoreport-desktop" -version = "0.3.25" +version = "0.3.26" edition = "2024" publish = false description = "PhotoReport desktop: the web app in a native shell, with keychain sign-in and (later) local FTP and the native engine." diff --git a/apps/desktop/src-tauri/build.rs b/apps/desktop/src-tauri/build.rs index 23e9bc1..196adc2 100644 --- a/apps/desktop/src-tauri/build.rs +++ b/apps/desktop/src-tauri/build.rs @@ -71,6 +71,8 @@ fn main() { "camera_take", "camera_tether", "camera_sync", + "camera_import", + "camera_refresh", ]), )) .expect("failed to run tauri-build"); diff --git a/apps/desktop/src-tauri/capabilities/default.json b/apps/desktop/src-tauri/capabilities/default.json index 2e2a5f4..838c588 100644 --- a/apps/desktop/src-tauri/capabilities/default.json +++ b/apps/desktop/src-tauri/capabilities/default.json @@ -73,7 +73,9 @@ "allow-camera-status", "allow-camera-take", "allow-camera-tether", - "allow-camera-sync" + "allow-camera-sync", + "allow-camera-import", + "allow-camera-refresh" ], "remote": { "urls": [ diff --git a/apps/desktop/src-tauri/permissions/autogenerated/camera_import.toml b/apps/desktop/src-tauri/permissions/autogenerated/camera_import.toml new file mode 100644 index 0000000..81c2d1f --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/camera_import.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-camera-import" +description = "Enables the camera_import command without any pre-configured scope." +commands.allow = ["camera_import"] + +[[permission]] +identifier = "deny-camera-import" +description = "Denies the camera_import command without any pre-configured scope." +commands.deny = ["camera_import"] diff --git a/apps/desktop/src-tauri/permissions/autogenerated/camera_refresh.toml b/apps/desktop/src-tauri/permissions/autogenerated/camera_refresh.toml new file mode 100644 index 0000000..519d48d --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/camera_refresh.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-camera-refresh" +description = "Enables the camera_refresh command without any pre-configured scope." +commands.allow = ["camera_refresh"] + +[[permission]] +identifier = "deny-camera-refresh" +description = "Denies the camera_refresh command without any pre-configured scope." +commands.deny = ["camera_refresh"] diff --git a/apps/desktop/src-tauri/src/camera.rs b/apps/desktop/src-tauri/src/camera.rs index d239aac..b68f5e5 100644 --- a/apps/desktop/src-tauri/src/camera.rs +++ b/apps/desktop/src-tauri/src/camera.rs @@ -1,7 +1,7 @@ //! USB tether (macOS). A Canon (or any PTP body) does not show up as a disk; ImageCaptureCore -//! (`camera_mac.m`) sees it, and shots taken after the card catalog is ready land in -//! `/.usb`. The web app polls `camera_take` and files them like a local-FTP photo. -//! The dot folder is skipped by the FTP scan, so a running FTP server does not upload them twice. +//! (`camera_mac.m`) lists the card and each new shot. Nothing is copied until the photographer +//! picks files (`camera_import`). Chosen files land in `/.usb` and the web app polls +//! `camera_take` to file them like a local-FTP photo. The dot folder is skipped by the FTP scan. use std::path::Path; use std::sync::{Mutex, OnceLock}; @@ -26,6 +26,24 @@ pub struct CameraDevice { /// Seconds the camera was ahead of the Mac before the sync. Positive means the camera was fast. #[serde(default)] pub clock_offset: Option, + /// True once the card listing is complete (and keeps updating as new shots appear). + #[serde(default)] + pub catalog_ready: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CameraFile { + pub name: String, + pub size: u64, + #[serde(default)] + pub created_ms: Option, + /// True when the file appeared after this session opened (a tethered shot). + #[serde(default)] + pub is_new: bool, + /// Already pulled into the ingest folder in this session. + #[serde(default)] + pub imported: bool, } #[derive(Debug, Clone, Serialize)] @@ -35,6 +53,7 @@ pub struct CameraStatus { pub supported: bool, pub tether: bool, pub devices: Vec, + pub files: Vec, } #[derive(Debug, Deserialize)] @@ -42,13 +61,21 @@ pub struct CameraStatus { enum CameraEvent { #[serde(rename = "devices")] Devices { devices: Vec }, + #[serde(rename = "catalog")] + Catalog { + #[serde(rename = "cameraId")] + #[allow(dead_code)] + camera_id: String, + files: Vec, + }, #[serde(rename = "file")] File { path: String, name: String, size: u64 }, } struct Inner { devices: Vec, - files: Vec, + files: Vec, + pending: Vec, tether: bool, dir: String, } @@ -63,6 +90,7 @@ impl Default for CameraState { inner: Mutex::new(Inner { devices: Vec::new(), files: Vec::new(), + pending: Vec::new(), tether: true, dir: String::new(), }), @@ -114,7 +142,8 @@ impl CameraState { CameraStatus { supported: supported(), tether: inner.as_ref().is_none_or(|i| i.tether), - devices: inner.map(|i| i.devices.clone()).unwrap_or_default(), + devices: inner.as_ref().map(|i| i.devices.clone()).unwrap_or_default(), + files: inner.map(|i| i.files.clone()).unwrap_or_default(), } } @@ -122,16 +151,29 @@ impl CameraState { self.drain(); self.inner .lock() - .map(|mut i| std::mem::take(&mut i.files)) + .map(|mut i| std::mem::take(&mut i.pending)) .unwrap_or_default() } pub fn set_tether(&self, on: bool) { if let Ok(mut inner) = self.inner.lock() { inner.tether = on; + if !on { + inner.files.clear(); + } } set_tether_native(on); } + + pub fn import(&self, names: &[String]) { + if names.is_empty() { + return; + } + let Ok(json) = serde_json::to_string(names) else { + return; + }; + import_native(&json); + } } fn apply_event(inner: &mut Inner, line: &str) { @@ -140,10 +182,10 @@ fn apply_event(inner: &mut Inner, line: &str) { }; match event { CameraEvent::Devices { devices } => inner.devices = devices, + CameraEvent::Catalog { camera_id: _, files } => inner.files = files, CameraEvent::File { path, name, size } => { - // JPEG is uploaded. RAW is only filed next to it (or on its own, when the body shot RAW). if size > 0 && (crate::ftp::is_jpeg_name(&name) || crate::ftp::is_raw_name(&name)) { - inner.files.push(IncomingFile::at(path, name, size)); + inner.pending.push(IncomingFile::at(path, name, size)); } } } @@ -179,6 +221,8 @@ unsafe extern "C" { fn pr_camera_set_dir(dir: *const std::ffi::c_char); fn pr_camera_set_tether(on: i32); fn pr_camera_sync(); + fn pr_camera_import(names_json: *const std::ffi::c_char); + fn pr_camera_refresh_catalog(); } #[cfg(target_os = "macos")] @@ -208,6 +252,25 @@ fn sync_native() { #[cfg(not(target_os = "macos"))] fn sync_native() {} +#[cfg(target_os = "macos")] +fn import_native(names_json: &str) { + let Ok(c) = std::ffi::CString::new(names_json) else { + return; + }; + unsafe { pr_camera_import(c.as_ptr()) } +} + +#[cfg(not(target_os = "macos"))] +fn import_native(_names_json: &str) {} + +#[cfg(target_os = "macos")] +fn refresh_catalog_native() { + unsafe { pr_camera_refresh_catalog() } +} + +#[cfg(not(target_os = "macos"))] +fn refresh_catalog_native() {} + /// Starts the browser once. Safe to call at launch; callbacks only enqueue a string. pub fn start(ftp: &FtpState) { #[cfg(target_os = "macos")] @@ -247,21 +310,40 @@ pub fn camera_sync(cam: tauri::State<'_, CameraState>) -> CameraStatus { cam.status() } +/// Downloads the named files from the open camera into the ingest folder (JPEG + RAW sidecars if listed). +#[tauri::command] +pub fn camera_import(cam: tauri::State<'_, CameraState>, names: Vec) -> CameraStatus { + cam.import(&names); + cam.status() +} + +/// Re-reads the card listing (after a big burst the list can lag). +#[tauri::command] +pub fn camera_refresh(cam: tauri::State<'_, CameraState>) -> CameraStatus { + refresh_catalog_native(); + cam.status() +} + #[cfg(test)] mod tests { use super::*; #[test] - fn a_tethered_shot_queues_the_jpeg_and_the_raw() { + fn a_chosen_shot_queues_the_jpeg_and_the_raw() { let mut inner = Inner { devices: Vec::new(), files: Vec::new(), + pending: Vec::new(), tether: true, dir: String::new(), }; apply_event( &mut inner, - r#"{"kind":"devices","devices":[{"id":"abc","name":"Canon Digital Camera","vendorId":1193,"productId":13075,"state":"tethered","error":null}]}"#, + r#"{"kind":"devices","devices":[{"id":"abc","name":"Canon Digital Camera","vendorId":1193,"productId":13075,"state":"tethered","error":null,"catalogReady":true}]}"#, + ); + apply_event( + &mut inner, + r#"{"kind":"catalog","cameraId":"abc","files":[{"name":"IMG_0001.JPG","size":10,"isNew":true,"imported":false},{"name":"IMG_0001.CR3","size":20,"isNew":true,"imported":false}]}"#, ); apply_event( &mut inner, @@ -272,10 +354,9 @@ mod tests { r#"{"kind":"file","path":"/ingest/.usb/IMG_0001.CR3","name":"IMG_0001.CR3","size":20}"#, ); assert_eq!(inner.devices.len(), 1); - assert_eq!(inner.devices[0].state, "tethered"); + assert!(inner.devices[0].catalog_ready); assert_eq!(inner.files.len(), 2); - assert!(crate::ftp::is_jpeg_name("IMG_0001.JPG")); - assert!(crate::ftp::is_raw_name("IMG_0001.CR3")); + assert_eq!(inner.pending.len(), 2); } #[test] @@ -290,12 +371,22 @@ mod tests { error: None, clock: None, clock_offset: None, + catalog_ready: true, }], - files: Vec::new(), + files: vec![CameraFile { + name: "a.jpg".into(), + size: 1, + created_ms: None, + is_new: false, + imported: false, + }], + pending: Vec::new(), tether: true, dir: String::new(), }; apply_event(&mut inner, r#"{"kind":"devices","devices":[]}"#); + apply_event(&mut inner, r#"{"kind":"catalog","cameraId":"abc","files":[]}"#); assert!(inner.devices.is_empty()); + assert!(inner.files.is_empty()); } } diff --git a/apps/desktop/src-tauri/src/camera_mac.m b/apps/desktop/src-tauri/src/camera_mac.m index c43706a..72898a4 100644 --- a/apps/desktop/src-tauri/src/camera_mac.m +++ b/apps/desktop/src-tauri/src/camera_mac.m @@ -1,6 +1,7 @@ // USB still cameras speak PTP, so macOS never mounts them as a disk. Image Capture (and this file) -// talks to them through ImageCaptureCore: when a body is plugged in we open a session and download -// only the shots taken after the card catalog is ready (tether). The card's existing files stay put. +// talks to them through ImageCaptureCore: open a session, list what is on the card (and each new +// shot as it appears), and download only the files the photographer picks. Nothing is copied on its +// own — that is deliberate: a full card would flood the ingest folder. // One process can hold the PTP session; if EOS Utility has it, opening fails and we try again. #import @@ -42,11 +43,12 @@ static BOOL is_still(ICCameraItem *item) { @property (copy) NSString *state; // opening | tethered | busy | idle @property (copy) NSString *errorText; @property (assign) BOOL catalogReady; -@property (retain) NSMutableSet *seen; +@property (assign) BOOL openRequested; @property (retain) NSMutableSet *fetched; +@property (retain) NSMutableSet *seenAtConnect; +@property (retain) NSMutableDictionary *filesByName; /// synced | unsupported. Nil until the session is ready. @property (copy) NSString *clock; -/// Seconds the camera was ahead of this Mac, captured before the sync. @property (assign) double clockOffset; @property (assign) BOOL clockOffsetKnown; @property (assign) BOOL clockDone; @@ -61,7 +63,6 @@ static BOOL is_still(ICCameraItem *item) { @property (copy) NSString *dir; @property (assign) BOOL tether; @property (assign) BOOL retryScheduled; -/// PTP bodies the browser cannot see because another app owns the USB device (EOS Utility). @property (retain) NSArray *locked; @end @@ -117,6 +118,7 @@ static BOOL is_still(ICCameraItem *item) { @"productId": product ?: @0, @"state": who.length ? @"busy" : @"opening", @"error": who.length ? who : [NSNull null], + @"catalogReady": @NO, }]; } IOObjectRelease(dev); @@ -139,9 +141,11 @@ static BOOL is_still(ICCameraItem *item) { if (!cam) { cam = [PRCam new]; cam.uuid = uuid; - cam.seen = [NSMutableSet set]; cam.fetched = [NSMutableSet set]; + cam.seenAtConnect = [NSMutableSet set]; + cam.filesByName = [NSMutableDictionary dictionary]; cam.clockDone = NO; + cam.openRequested = NO; self.cams[uuid] = cam; } cam.device = (ICCameraDevice *)device; @@ -164,12 +168,50 @@ static BOOL is_still(ICCameraItem *item) { @"error": cam.errorText ?: [NSNull null], @"clock": cam.clock ?: [NSNull null], @"clockOffset": cam.clockOffsetKnown ? @(cam.clockOffset) : [NSNull null], + @"catalogReady": @(cam.catalogReady), }]; } if (self.locked) [list addObjectsFromArray:self.locked]; emit(@{@"kind": @"devices", @"devices": list}); } +- (void)publishCatalog:(PRCam *)cam { + NSMutableArray *files = [NSMutableArray array]; + for (NSString *name in cam.filesByName) { + ICCameraFile *file = cam.filesByName[name]; + BOOL isNew = ![cam.seenAtConnect containsObject:name]; + NSDate *created = file.creationDate; + [files addObject:@{ + @"name": name, + @"size": @(file.fileSize), + @"createdMs": created ? @((long long)(created.timeIntervalSince1970 * 1000.0)) : [NSNull null], + @"isNew": @(isNew), + @"imported": @([cam.fetched containsObject:name]), + }]; + } + [files sortUsingComparator:^NSComparisonResult(NSDictionary *a, NSDictionary *b) { + NSNumber *ca = a[@"createdMs"]; + NSNumber *cb = b[@"createdMs"]; + if ([ca isKindOfClass:[NSNumber class]] && [cb isKindOfClass:[NSNumber class]] && ![ca isEqual:[NSNull null]] && ![cb isEqual:[NSNull null]]) { + NSComparisonResult byDate = [cb compare:ca]; + if (byDate != NSOrderedSame) return byDate; + } + return [((NSString *)a[@"name"]) compare:b[@"name"]]; + }]; + emit(@{@"kind": @"catalog", @"cameraId": cam.uuid ?: @"", @"files": files}); +} + +- (void)indexItem:(ICCameraItem *)item cam:(PRCam *)cam { + if (!is_still(item) || !item.name) return; + cam.filesByName[item.name] = (ICCameraFile *)item; +} + +- (void)rebuildCatalog:(PRCam *)cam { + [cam.filesByName removeAllObjects]; + for (ICCameraItem *item in cam.device.mediaFiles) [self indexItem:item cam:cam]; + [self publishCatalog:cam]; +} + - (void)syncClock:(PRCam *)cam { if (cam.clockDone || !cam.device.hasOpenSession) return; if (cam.device.capabilities.count == 0) return; @@ -187,16 +229,22 @@ static BOOL is_still(ICCameraItem *item) { [self publish]; } -- (void)open:(PRCam *)cam { - cam.clockDone = NO; - cam.clock = nil; - cam.clockOffsetKnown = NO; +/// Apple: do not send requests until deviceDidBecomeReady. Opening earlier hangs some Canon bodies. +- (void)requestOpenIfReady:(PRCam *)cam { if (!self.tether) { cam.state = @"idle"; cam.errorText = nil; [self publish]; return; } + if (cam.device.hasOpenSession) { + cam.state = @"tethered"; + cam.errorText = nil; + [self publish]; + return; + } + if (cam.openRequested) return; + cam.openRequested = YES; cam.state = @"opening"; cam.errorText = nil; cam.device.delegate = self; @@ -204,12 +252,6 @@ static BOOL is_still(ICCameraItem *item) { [self publish]; } -- (void)markSeen:(PRCam *)cam { - for (ICCameraItem *item in cam.device.mediaFiles) { - if (item.name) [cam.seen addObject:item.name]; - } -} - - (void)scheduleRetry { if (self.retryScheduled || !self.tether) return; self.retryScheduled = YES; @@ -221,7 +263,10 @@ static BOOL is_still(ICCameraItem *item) { if (!hub.tether) return; for (NSString *key in hub.cams.allKeys) { PRCam *cam = hub.cams[key]; - if ([cam.state isEqualToString:@"busy"]) [hub open:cam]; + if ([cam.state isEqualToString:@"busy"] || [cam.state isEqualToString:@"opening"]) { + cam.openRequested = NO; + [hub requestOpenIfReady:cam]; + } } }); } @@ -242,7 +287,7 @@ static BOOL is_still(ICCameraItem *item) { } - (void)download:(ICCameraFile *)file cam:(PRCam *)cam { - if (!self.tether || self.dir.length == 0 || !file.name) return; + if (self.dir.length == 0 || !file.name) return; if ([cam.fetched containsObject:file.name]) return; NSFileManager *fm = [NSFileManager defaultManager]; [fm createDirectoryAtPath:self.dir withIntermediateDirectories:YES attributes:nil error:nil]; @@ -266,12 +311,17 @@ static BOOL is_still(ICCameraItem *item) { #pragma clang diagnostic pop } -- (void)consider:(ICCameraItem *)item cam:(PRCam *)cam { - if (!is_still(item) || !item.name) return; - BOOL fresh = item.inTemporaryStore || (cam.catalogReady && ![cam.seen containsObject:item.name]); - [cam.seen addObject:item.name]; - if (!fresh) return; - [self download:(ICCameraFile *)item cam:cam]; +- (void)importNames:(NSArray *)names { + if (self.dir.length == 0 || names.count == 0) return; + for (NSString *key in self.cams) { + PRCam *cam = self.cams[key]; + if (!cam.device.hasOpenSession) continue; + for (NSString *name in names) { + ICCameraFile *file = cam.filesByName[name]; + if (file) [self download:file cam:cam]; + } + [self publishCatalog:cam]; + } } #pragma mark ICDeviceBrowserDelegate @@ -282,7 +332,11 @@ static BOOL is_still(ICCameraItem *item) { if (![self accepts:device]) return; PRCam *cam = [self camFor:device]; cam.catalogReady = NO; - [self open:cam]; + cam.openRequested = NO; + cam.device.delegate = self; + cam.state = self.tether ? @"opening" : @"idle"; + [self publish]; + // Session opens from deviceDidBecomeReady — not here. } - (void)deviceBrowser:(ICDeviceBrowser *)browser didRemoveDevice:(ICDevice *)device moreGoing:(BOOL)moreGoing { @@ -291,12 +345,14 @@ static BOOL is_still(ICCameraItem *item) { NSString *uuid = device.UUIDString ?: device.name; if (uuid) [self.cams removeObjectForKey:uuid]; [self publish]; + emit(@{@"kind": @"catalog", @"cameraId": uuid ?: @"", @"files": @[]}); } #pragma mark ICDeviceDelegate - (void)device:(ICDevice *)device didOpenSessionWithError:(NSError *)error { PRCam *cam = [self camFor:device]; + cam.openRequested = NO; if (error) { cam.state = @"busy"; cam.errorText = error.localizedDescription; @@ -310,6 +366,7 @@ static BOOL is_still(ICCameraItem *item) { #pragma clang diagnostic ignored "-Wdeprecated-declarations" [cam.device requestEnableTethering]; #pragma clang diagnostic pop + [self syncClock:cam]; [self publish]; } @@ -317,6 +374,8 @@ static BOOL is_still(ICCameraItem *item) { (void)error; PRCam *cam = self.cams[device.UUIDString ?: @""]; if (!cam) return; + cam.openRequested = NO; + cam.catalogReady = NO; if (self.tether) { cam.state = @"busy"; [self scheduleRetry]; @@ -332,31 +391,39 @@ static BOOL is_still(ICCameraItem *item) { - (void)deviceDidBecomeReady:(ICDevice *)device { PRCam *cam = [self camFor:device]; - // The card is still being listed. Shots taken now are marked inTemporaryStore and downloaded; - // everything else waits until the catalog is complete, so the card itself is not copied. - if ([cam.state isEqualToString:@"opening"]) cam.state = @"tethered"; + [self requestOpenIfReady:cam]; [self syncClock:cam]; [self publish]; } - (void)deviceDidBecomeReadyWithCompleteContentCatalog:(ICCameraDevice *)device { PRCam *cam = [self camFor:device]; - [self markSeen:cam]; + // Snapshot what was already on the card so the UI can mark later shots as "new". + [cam.seenAtConnect removeAllObjects]; + for (ICCameraItem *item in cam.device.mediaFiles) { + if (item.name && is_still(item)) [cam.seenAtConnect addObject:item.name]; + } cam.catalogReady = YES; - cam.state = @"tethered"; + if ([cam.state isEqualToString:@"opening"]) cam.state = @"tethered"; cam.errorText = nil; + [self rebuildCatalog:cam]; [self syncClock:cam]; [self publish]; } - (void)cameraDevice:(ICCameraDevice *)camera didAddItems:(NSArray *)items { PRCam *cam = [self camFor:camera]; - for (ICCameraItem *item in items) [self consider:item cam:cam]; + // List only — never auto-download. The photographer picks what to pull. + for (ICCameraItem *item in items) [self indexItem:item cam:cam]; + [self publishCatalog:cam]; } - (void)cameraDevice:(ICCameraDevice *)camera didRemoveItems:(NSArray *)items { - (void)camera; - (void)items; + PRCam *cam = [self camFor:camera]; + for (ICCameraItem *item in items) { + if (item.name) [cam.filesByName removeObjectForKey:item.name]; + } + [self publishCatalog:cam]; } - (void)cameraDevice:(ICCameraDevice *)camera didReceiveThumbnail:(CGImageRef)thumbnail forItem:(ICCameraItem *)item error:(NSError *)error { @@ -396,8 +463,15 @@ static BOOL is_still(ICCameraItem *item) { } - (void)didDownloadFile:(ICCameraFile *)file error:(NSError *)error options:(NSDictionary *)options contextInfo:(void *)contextInfo { - if (contextInfo) CFBridgingRelease(contextInfo); - if (error || self.dir.length == 0) return; + NSString *camId = contextInfo ? CFBridgingRelease(contextInfo) : nil; + if (error || self.dir.length == 0) { + if (camId && file.name) { + PRCam *cam = self.cams[camId]; + [cam.fetched removeObject:file.name]; + [self publishCatalog:cam]; + } + return; + } NSString *saved = options[ICSavedFilename]; if (![saved isKindOfClass:[NSString class]] || saved.length == 0) saved = file.name; if (saved.length == 0) return; @@ -406,6 +480,10 @@ static BOOL is_still(ICCameraItem *item) { unsigned long long size = [attrs fileSize]; if (size == 0) return; emit(@{@"kind": @"file", @"path": path, @"name": saved, @"size": @(size)}); + if (camId) { + PRCam *cam = self.cams[camId]; + if (cam) [self publishCatalog:cam]; + } } @end @@ -453,7 +531,8 @@ void pr_camera_set_tether(int on) { for (NSString *key in g_hub.cams.allKeys) { PRCam *cam = g_hub.cams[key]; if (g_hub.tether) { - if (!cam.device.hasOpenSession) [g_hub open:cam]; + cam.openRequested = NO; + [g_hub requestOpenIfReady:cam]; } else if (cam.device.hasOpenSession) { cam.state = @"idle"; [cam.device requestCloseSession]; @@ -464,3 +543,26 @@ void pr_camera_set_tether(int on) { [g_hub publish]; }); } + +void pr_camera_import(const char *names_json) { + if (!names_json) return; + NSString *text = [NSString stringWithUTF8String:names_json]; + NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding]; + if (!data) return; + id parsed = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; + if (![parsed isKindOfClass:[NSArray class]]) return; + NSArray *names = (NSArray *)parsed; + on_main(^{ + [g_hub importNames:names]; + }); +} + +void pr_camera_refresh_catalog(void) { + on_main(^{ + if (!g_hub) return; + for (NSString *key in g_hub.cams.allKeys) { + PRCam *cam = g_hub.cams[key]; + if (cam.catalogReady) [g_hub rebuildCatalog:cam]; + } + }); +} diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index e7f4a1b..71677d9 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -185,7 +185,9 @@ pub fn run() { camera::camera_status, camera::camera_take, camera::camera_tether, - camera::camera_sync + camera::camera_sync, + camera::camera_import, + camera::camera_refresh ]) .run(context); if let Err(err) = result { diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 395cca9..0f7c228 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "PhotoReport", - "version": "0.3.25", + "version": "0.3.26", "identifier": "pt.photoreport.desktop", "build": { "devUrl": "http://localhost:5173",