Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
iCloud Photos as a folder: by date, album, favourites, videos (read-only)
Yashwanth Kamireddidc0989a573cd
diff --git a/.uiverify/settings-drive-folder.mjs b/.uiverify/settings-drive-folder.mjsindex bc8bec8..e1bfab4 100644--- a/.uiverify/settings-drive-folder.mjs+++ b/.uiverify/settings-drive-folder.mjs@@ -29,5 +29,14 @@ await sw.click();await page.waitForTimeout(300);const row = await page.locator(".settings-row", { has: sw }).innerText();ok((await sw.getAttribute("aria-checked")) === "false" && /already has files in it/.test(row), `one that cannot come up is left off, and says why "${row.replace(/\n/g, " ")}"`);+// The Photos folder: its own switch, beside Drive's, independent of it.+const ph = page.getByRole("switch", { name: "iCloud Photos folder" });+ok((await ph.getAttribute("aria-checked")) === "false" && (await sw.getAttribute("aria-checked")) === "false", "the Photos folder has its own switch, off");+await ph.click();+await page.waitForTimeout(200);+ok((await ph.getAttribute("aria-checked")) === "true" && (await sw.getAttribute("aria-checked")) === "false", "turned on alone, Drive's left as it was");+ok(/\/home\/test\/iCloud Photos/.test(await page.locator(".settings-row", { has: ph }).innerText()), "and says where it is");+await page.locator(".settings-row", { has: ph }).getByRole("button", { name: "Open" }).click();+ok((await page.evaluate(() => window.__opened)).includes("photos"), "Open shows it");await b.close();process.exitCode = failures ? 1 : (process.exitCode ?? 0);diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjsindex b7e117b..de794a0 100644--- a/.uiverify/stub.mjs+++ b/.uiverify/stub.mjs@@ -522,6 +522,9 @@ export function installStub({ screen, services, twoFactor, calendarFixture, noteif (window.__driveFolderRefuse) return { ...window.__driveFolder, on: false, problem: window.__driveFolderRefuse };return (window.__driveFolder = { on: args.on, path: "/home/test/iCloud Drive", problem: null });case "drive_folder_open": (window.__opened ??= []).push("drive"); return null;+ case "photos_folder_status": return window.__photosFolder ??= { on: false, path: "/home/test/iCloud Photos", problem: null };+ case "photos_folder_set": return (window.__photosFolder = { on: args.on, path: "/home/test/iCloud Photos", problem: null });+ case "photos_folder_open": (window.__opened ??= []).push("photos"); return null;case "photo_video_turn": (window.__turnAsks ??= []).push(args); return window.__turn ?? [1, 0, 0, 1];case "contacts_import": (window.__imports ??= []).push(args); return window.__importAnswer ?? [2, 0, 0];case "plugin:dialog|open": return window.__pick ?? null;diff --git a/crates/quince-vfs/src/fuse.rs b/crates/quince-vfs/src/fuse.rsindex b393d8a..b9faf1e 100644--- a/crates/quince-vfs/src/fuse.rs+++ b/crates/quince-vfs/src/fuse.rs@@ -53,6 +53,8 @@ struct Inner {writes: Option<Arc<Writes>>,/// The account's storage as last asked, `(used, total)`.space: Mutex<Option<((u64, u64), std::time::Instant)>>,+ /// Nothing in it can be changed (the Photos folder, for now).+ read_only: bool,}pub struct DriveFs(Arc<Inner>);@@ -80,6 +82,7 @@ impl DriveFs {filled: Mutex::new(std::collections::HashSet::new()),writes: None,space: Mutex::new(None),+ read_only: false,}))}@@ -95,6 +98,13 @@ impl DriveFs {self}+ /// Nothing in it can be changed: every change answered "read-only file system".+ #[must_use]+ pub fn read_only(mut self) -> Self {+ self.inner_mut().read_only = true;+ self+ }+/// Files can be written, their bytes kept in `dir` until Apple has them. What was waiting/// when the folder last went away is picked up again and sent.///@@ -274,7 +284,8 @@ impl Inner {} else {FileType::RegularFile},- perm: match (dir, self.writes.is_some()) {+ perm: match (dir, self.writes.is_some() && !self.read_only) {+ (true, _) if self.read_only => 0o555,(true, _) => 0o755,(false, true) => 0o644,(false, false) => 0o444,@@ -799,6 +810,9 @@ impl Filesystem for DriveFs {return reply.error(Errno::ENOENT);};// Only a file's length is Apple's to keep; modes and times are taken as they are.+ if size.is_some() && inner.read_only {+ return reply.error(Errno::EROFS);+ }if let (Some(size), false) = (size, item.is_container()) {if let Err(e) = inner.begin_writing(ino.0, &item, size > 0) {return reply.error(e);@@ -886,7 +900,7 @@ impl Filesystem for DriveFs {}let writing = flags.acc_mode() != OpenAccMode::O_RDONLY;let truncate = flags.0 & libc::O_TRUNC != 0;- if writing && inner.writes.is_none() {+ if writing && (inner.writes.is_none() || inner.read_only) {return reply.error(Errno::EROFS);}if inner.pending(ino.0).is_none() {@@ -901,7 +915,10 @@ impl Filesystem for DriveFs {let cmdline = std::fs::read(format!("/proc/{pid}/cmdline")).map(|b| String::from_utf8_lossy(&b).into_owned()).unwrap_or_default();- if is_thumbnailer(&comm, &cmdline) && !inner.cache.whole(&item) {+ if is_thumbnailer(&comm, &cmdline)+ && !inner.cache.whole(&item)+ && !inner.remote.is_local(&item)+ {return reply.error(Errno::EACCES);}return reply.opened(FileHandle(0), FopenFlags::empty());@@ -937,6 +954,9 @@ impl Filesystem for DriveFs {flags: i32,reply: ReplyCreate,) {+ if self.0.read_only {+ return reply.error(Errno::EROFS);+ }let inner = &self.0;let Some(writes) = inner.writes.clone() else {return reply.error(Errno::EROFS);@@ -1060,6 +1080,24 @@ impl Filesystem for DriveFs {let Some(item) = inner.item(ino.0) else {return reply.error(Errno::ENOENT);};+ // Kept whole by the app already (a photo's original): read from there, no second copy.+ if let Some(path) = inner.remote.file(&item) {+ inner.rt.spawn(async move {+ let bytes = path.await.and_then(|p| {+ let mut buf = vec![0u8; size as usize];+ let n = std::fs::File::open(p)+ .and_then(|f| f.read_at(&mut buf, offset))+ .map_err(|e| e.to_string())?;+ buf.truncate(n);+ Ok(buf)+ });+ match bytes {+ Ok(b) => reply.data(&b),+ Err(_) => reply.error(Errno::EIO),+ }+ });+ return;+ }let (cache, remote) = (Arc::clone(&inner.cache), Arc::clone(&inner.remote));// Answered when the bytes are here, without holding up the folder's other requests.inner.rt.spawn(async move {@@ -1163,6 +1201,9 @@ impl Filesystem for DriveFs {_umask: u32,reply: ReplyEntry,) {+ if self.0.read_only {+ return reply.error(Errno::EROFS);+ }let inner = &self.0;let Some(folder) = inner.item(parent.0) else {return reply.error(Errno::ENOENT);@@ -1183,6 +1224,9 @@ impl Filesystem for DriveFs {}fn unlink(&self, _req: &Request, parent: INodeNo, name: &OsStr, reply: ReplyEmpty) {+ if self.0.read_only {+ return reply.error(Errno::EROFS);+ }match self.0.remove(parent.0, name, false) {Ok(()) => reply.ok(),Err(e) => reply.error(e),@@ -1190,6 +1234,9 @@ impl Filesystem for DriveFs {}fn rmdir(&self, _req: &Request, parent: INodeNo, name: &OsStr, reply: ReplyEmpty) {+ if self.0.read_only {+ return reply.error(Errno::EROFS);+ }match self.0.remove(parent.0, name, true) {Ok(()) => reply.ok(),Err(e) => reply.error(e),@@ -1206,6 +1253,9 @@ impl Filesystem for DriveFs {_flags: RenameFlags,reply: ReplyEmpty,) {+ if self.0.read_only {+ return reply.error(Errno::EROFS);+ }match Inner::rename(&self.0, parent.0, name, newparent.0, newname) {Ok(()) => reply.ok(),Err(e) => reply.error(e),diff --git a/crates/quince-vfs/src/lib.rs b/crates/quince-vfs/src/lib.rsindex 4230e34..68b9e26 100644--- a/crates/quince-vfs/src/lib.rs+++ b/crates/quince-vfs/src/lib.rs@@ -47,6 +47,16 @@ pub trait Remote: Send + Sync + 'static {fn delete(&self, _item: &DriveItem) -> Fut<()> {Box::pin(async { Err("read-only".to_string()) })}+ /// Where a file's whole bytes are already kept on this computer by the app (fetched once if+ /// need be): read from there, not copied into the folder's own cache. `None`: no such+ /// place, the cache is used.+ fn file(&self, _item: &DriveItem) -> Option<Fut<PathBuf>> {+ None+ }+ /// Whether a file's bytes are on this computer already, without fetching them.+ fn is_local(&self, _item: &DriveItem) -> bool {+ false+ }/// The account's iCloud storage, `(used, total)` in bytes: a file manager checks there is/// room before it copies anything in.fn space(&self) -> Fut<(u64, u64)> {diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 924e191..69b3b1f 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -15,6 +15,7 @@ macro_rules! quiet {mod alerts;mod cpu;mod mount;+mod mount_photos;mod outbox;mod photos;mod poster;@@ -3956,6 +3957,9 @@ fn main() {mount::drive_folder_status,mount::drive_folder_set,mount::drive_folder_open,+ mount::photos_folder_status,+ mount::photos_folder_set,+ mount::photos_folder_open,photos::photo_video_turn,photos::photos_set_flag,photos::photos_burst,diff --git a/src-tauri/src/mount.rs b/src-tauri/src/mount.rsindex ef23132..bf1af68 100644--- a/src-tauri/src/mount.rs+++ b/src-tauri/src/mount.rs@@ -20,9 +20,9 @@ const PATH_KEY: &str = "drive_folder_path";/// How long a file's download link is used before asking Apple for a fresh one.const LINK_LIFE: Duration = Duration::from_secs(20 * 60);-/// The mount while it is up; dropping it lets the folder go.+/// The folders while they are up; dropping one lets its folder go.#[cfg(target_os = "linux")]-static SESSION: Mutex<Option<(PathBuf, fuser::BackgroundSession)>> = Mutex::new(None);+static SESSIONS: Mutex<Vec<(Which, PathBuf, fuser::BackgroundSession)>> = Mutex::new(Vec::new());struct AppRemote {app: AppHandle,@@ -212,18 +212,47 @@ impl Store for AppStore {}}-/// Where the folder goes: as moved, or "iCloud Drive" in the home folder, where iCloud for-/// Windows puts it in a user's folder.-fn place(app: &AppHandle) -> PathBuf {+/// The two folders: iCloud Drive and iCloud Photos, each its own switch and place, each+/// needing only its own service (someone with iCloud Photos off still has Drive).+#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub enum Which {+ Drive,+ Photos,+}++impl Which {+ fn on_key(self) -> &'static str {+ match self {+ Which::Drive => ON_KEY,+ Which::Photos => "photos_folder_on",+ }+ }+ fn path_key(self) -> &'static str {+ match self {+ Which::Drive => PATH_KEY,+ Which::Photos => "photos_folder_path",+ }+ }+ /// Its folder's name in the home folder, as iCloud for Windows names them.+ fn folder(self) -> &'static str {+ match self {+ Which::Drive => "iCloud Drive",+ Which::Photos => "iCloud Photos",+ }+ }+}++/// Where a folder goes: as moved, or its own name in the home folder.+fn place(app: &AppHandle, which: Which) -> PathBuf {let data = app.state::<Data>();let library = data.0.blocking_lock();library- .state(PATH_KEY)+ .state(which.path_key()).ok().flatten().map(PathBuf::from)- .or_else(|| app.path().home_dir().ok().map(|h| h.join("iCloud Drive")))- .unwrap_or_else(|| PathBuf::from("iCloud Drive"))+ .or_else(|| app.path().home_dir().ok().map(|h| h.join(which.folder())))+ .unwrap_or_else(|| PathBuf::from(which.folder()))}/// What Settings shows: whether it is up, where, and what stopped it if anything did.@@ -236,19 +265,29 @@ pub struct FolderStatus {}#[cfg(target_os = "linux")]-fn mounted() -> Option<PathBuf> {- SESSION+fn mounted(which: Which) -> Option<PathBuf> {+ SESSIONS.lock().unwrap_or_else(std::sync::PoisonError::into_inner)- .as_ref()- .map(|(p, _)| p.clone())+ .iter()+ .find(|(w, ..)| *w == which)+ .map(|(_, p, _)| p.clone())+}++/// Where every file manager looks for thumbnails (~/.cache/thumbnails).+fn thumbnail_cache(app: &AppHandle) -> Option<PathBuf> {+ std::env::var_os("XDG_CACHE_HOME")+ .map(PathBuf::from)+ .filter(|p| p.is_absolute())+ .or_else(|| app.path().home_dir().ok().map(|h| h.join(".cache")))+ .map(|c| c.join("thumbnails"))}-/// The folder brought up at `at`. Never over a folder with something in it: a mount would-/// hide what is there.+/// A folder brought up at `at`. Never over a folder with something in it: a mount would hide+/// what is there.#[cfg(target_os = "linux")]-fn start(app: &AppHandle, at: &std::path::Path) -> Result<(), String> {- if mounted().is_some() {+fn start(app: &AppHandle, which: Which, at: &std::path::Path) -> Result<(), String> {+ if mounted(which).is_some() {return Ok(());}if !std::path::Path::new("/dev/fuse").exists() {@@ -262,43 +301,58 @@ fn start(app: &AppHandle, at: &std::path::Path) -> Result<(), String> {));}}- let cache = crate::state_dir(app).join("drive-cache");- let cache = Arc::new(quince_vfs::Cache::new(&cache).map_err(|e| e.to_string())?);- let remote = Arc::new(AppRemote {- app: app.clone(),- links: Arc::new(Mutex::new(HashMap::new())),- });- let store = Arc::new(AppStore(app.clone()));let rt = tauri::async_runtime::handle().inner().clone();- // Apple's pictures go where every file manager looks for thumbnails, so none of them- // downloads a file to draw one.- let thumbs = std::env::var_os("XDG_CACHE_HOME")- .map(PathBuf::from)- .filter(|p| p.is_absolute())- .or_else(|| app.path().home_dir().ok().map(|h| h.join(".cache")))- .map(|c| c.join("thumbnails"));- // What is written here waits beside the library (owner-only) until Apple has it.- let mut fs = quince_vfs::fuse::DriveFs::new(remote, store, cache, rt)- .with_writes(&crate::state_dir(app).join("drive-writes"))- .map_err(|e| e.to_string())?;- if let Some(thumbs) = thumbs {+ let mut fs = match which {+ Which::Drive => {+ let cache = crate::state_dir(app).join("drive-cache");+ let cache = Arc::new(quince_vfs::Cache::new(&cache).map_err(|e| e.to_string())?);+ let remote = Arc::new(AppRemote {+ app: app.clone(),+ links: Arc::new(Mutex::new(HashMap::new())),+ });+ // What is written here waits beside the library (owner-only) until Apple has it.+ quince_vfs::fuse::DriveFs::new(remote, Arc::new(AppStore(app.clone())), cache, rt)+ .with_writes(&crate::state_dir(app).join("drive-writes"))+ .map_err(|e| e.to_string())?+ }+ Which::Photos => {+ // Read through the app's own photo cache; the folder keeps no second copy.+ let unused = crate::state_dir(app).join("photos-folder-cache");+ let cache = Arc::new(quince_vfs::Cache::new(&unused).map_err(|e| e.to_string())?);+ quince_vfs::fuse::DriveFs::new(+ Arc::new(crate::mount_photos::PhotosRemote(app.clone())),+ Arc::new(crate::mount_photos::PhotosStore(app.clone())),+ cache,+ rt,+ )+ .read_only()+ }+ };+ // Pictures go where every file manager looks for thumbnails, so none of them downloads a+ // file to draw one.+ if let Some(thumbs) = thumbnail_cache(app) {fs = fs.with_thumbnails(at.to_path_buf(), thumbs);}let session = quince_vfs::fuse::mount(fs, at).map_err(|e| format!("The folder could not be mounted: {e}"))?;- *SESSION+ SESSIONS.lock()- .unwrap_or_else(std::sync::PoisonError::into_inner) = Some((at.to_path_buf(), session));+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .push((which, at.to_path_buf(), session));Ok(())}#[cfg(target_os = "linux")]-fn stop() {- let gone = SESSION- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .take();- if let Some((at, session)) = gone {+fn stop(which: Which) {+ let gone: Vec<_> = {+ let mut sessions = SESSIONS+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let (go, keep): (Vec<_>, Vec<_>) = sessions.drain(..).partition(|(w, ..)| *w == which);+ *sessions = keep;+ go+ };+ for (_, at, session) in gone {drop(session);// The empty folder the mount stood on is put away too, as it was made for it.let _ = std::fs::remove_dir(at);@@ -306,77 +360,110 @@ fn stop() {}#[cfg(not(target_os = "linux"))]-fn start(_app: &AppHandle, _at: &std::path::Path) -> Result<(), String> {- Err("The iCloud Drive folder is not on this system yet.".into())+fn start(_app: &AppHandle, _which: Which, _at: &std::path::Path) -> Result<(), String> {+ Err("These folders are not on this system yet.".into())}#[cfg(not(target_os = "linux"))]-fn stop() {}+fn stop(_which: Which) {}#[cfg(not(target_os = "linux"))]-fn mounted() -> Option<PathBuf> {+fn mounted(_which: Which) -> Option<PathBuf> {None}-fn status(app: &AppHandle, problem: Option<String>) -> FolderStatus {- let at = mounted().unwrap_or_else(|| place(app));+fn status(app: &AppHandle, which: Which, problem: Option<String>) -> FolderStatus {+ let at = mounted(which).unwrap_or_else(|| place(app, which));FolderStatus {- on: mounted().is_some(),+ on: mounted(which).is_some(),path: at.to_string_lossy().into_owned(),problem,}}-/// At start: brought up if it was on.+/// At start: each brought up if it was on.pub fn resume(app: &AppHandle) {- let wanted = {- let data = app.state::<Data>();- let library = data.0.blocking_lock();- library.state(ON_KEY).ok().flatten().as_deref() == Some("1")- };- if wanted {- if let Err(e) = start(app, &place(app)) {- quiet!("the iCloud Drive folder could not come up: {e}");+ for which in [Which::Drive, Which::Photos] {+ let wanted = {+ let data = app.state::<Data>();+ let library = data.0.blocking_lock();+ library.state(which.on_key()).ok().flatten().as_deref() == Some("1")+ };+ if wanted {+ if let Err(e) = start(app, which, &place(app, which)) {+ quiet!("a folder could not come up: {e}");+ }}}}-/// When signing out: the folder goes with the session.+/// When signing out or quitting: both folders go with the session.pub fn release() {- stop();+ stop(Which::Drive);+ stop(Which::Photos);}-#[tauri::command]-pub async fn drive_folder_status(app: AppHandle) -> Result<FolderStatus, String> {- tauri::async_runtime::spawn_blocking(move || status(&app, None))- .await- .map_err(|e| e.to_string())-}--/// Turn the folder on or off, remembered for the next start.-#[tauri::command]-pub async fn drive_folder_set(on: bool, app: AppHandle) -> Result<FolderStatus, String> {+async fn set(app: AppHandle, which: Which, on: bool) -> Result<FolderStatus, String> {tauri::async_runtime::spawn_blocking(move || {let problem = if on {- start(&app, &place(&app)).err()+ start(&app, which, &place(&app, which)).err()} else {- stop();+ stop(which);None};let data = app.state::<Data>();let mut library = data.0.blocking_lock();- let _ = library.set_state(ON_KEY, if on && problem.is_none() { "1" } else { "0" });+ let _ = library.set_state(+ which.on_key(),+ if on && problem.is_none() { "1" } else { "0" },+ );drop(library);- status(&app, problem)+ status(&app, which, problem)}).await.map_err(|e| e.to_string())}-/// The folder opened in the system's file manager.-#[tauri::command]-pub async fn drive_folder_open(app: AppHandle) -> Result<(), String> {+fn open(app: &AppHandle, which: Which) -> Result<(), String> {use tauri_plugin_opener::OpenerExt;- let at = mounted().ok_or("The iCloud Drive folder is off.")?;+ let at = mounted(which).ok_or("That folder is off.")?;app.opener().open_path(at.to_string_lossy(), None::<&str>).map_err(|e| e.to_string())}++#[tauri::command]+pub async fn drive_folder_status(app: AppHandle) -> Result<FolderStatus, String> {+ tauri::async_runtime::spawn_blocking(move || status(&app, Which::Drive, None))+ .await+ .map_err(|e| e.to_string())+}++/// Turn the iCloud Drive folder on or off, remembered for the next start.+#[tauri::command]+pub async fn drive_folder_set(on: bool, app: AppHandle) -> Result<FolderStatus, String> {+ set(app, Which::Drive, on).await+}++/// The iCloud Drive folder opened in the system's file manager.+#[tauri::command]+pub async fn drive_folder_open(app: AppHandle) -> Result<(), String> {+ open(&app, Which::Drive)+}++#[tauri::command]+pub async fn photos_folder_status(app: AppHandle) -> Result<FolderStatus, String> {+ tauri::async_runtime::spawn_blocking(move || status(&app, Which::Photos, None))+ .await+ .map_err(|e| e.to_string())+}++/// Turn the iCloud Photos folder on or off, remembered for the next start.+#[tauri::command]+pub async fn photos_folder_set(on: bool, app: AppHandle) -> Result<FolderStatus, String> {+ set(app, Which::Photos, on).await+}++/// The iCloud Photos folder opened in the system's file manager.+#[tauri::command]+pub async fn photos_folder_open(app: AppHandle) -> Result<(), String> {+ open(&app, Which::Photos)+}diff --git a/src-tauri/src/mount_photos.rs b/src-tauri/src/mount_photos.rsnew file mode 100644index 0000000..e0effa4--- /dev/null+++ b/src-tauri/src/mount_photos.rs@@ -0,0 +1,253 @@+//! iCloud Photos as a folder (quince-vfs, read-only for now), laid out as people look for+//! photos: by when they were taken, in their albums, the favourites, the videos.+//!+//! Library/2026/10 October/IMG_1234.HEIC+//! Albums/Trips/Goa/IMG_0042.JPG+//! Favorites/… Videos/…+//!+//! Each file is the original, under its own name and dated when it was taken. Its bytes are+//! read from the app's own photo cache (fetched once if they are not there), never copied a+//! second time; thumbnails are the app's own, so a file manager browsing downloads nothing.+//! Hidden and Recently Deleted are never shown.++use crate::photos::{cache_path, cached, Size};+use crate::Data;+use quince_core::drive::DriveItem;+use quince_core::photos::{Photo, View};+use quince_vfs::{Fut, Remote, Store, ROOT};+use std::collections::HashMap;+use std::path::PathBuf;+use tauri::{AppHandle, Manager};++const LIBRARY: &str = "PH::library";+const ALBUMS: &str = "PH::albums";+const FAVORITES: &str = "PH::favorites";+const VIDEOS: &str = "PH::videos";+const FILE: &str = "PHOTO::";++const MONTHS: [&str; 12] = [+ "January",+ "February",+ "March",+ "April",+ "May",+ "June",+ "July",+ "August",+ "September",+ "October",+ "November",+ "December",+];++fn folder(id: String, parent: &str, name: String) -> DriveItem {+ DriveItem {+ drivewsid: id,+ parent_id: Some(parent.to_string()),+ name,+ extension: None,+ kind: "FOLDER".into(),+ size: None,+ child_count: None,+ created_at: None,+ modified_at: None,+ etag: None,+ }+}++/// A photo as a file: its own name (or one made from its id and kind), its size, the time it+/// was taken.+fn file(p: &Photo, parent: &str) -> DriveItem {+ let name = p.filename.clone().unwrap_or_else(|| {+ let ext = match p.kind {+ quince_core::photos::Kind::Video => "MOV",+ _ => "JPG",+ };+ format!("{}.{ext}", p.id)+ });+ let (stem, ext) = match name.rsplit_once('.') {+ Some((s, e)) if !s.is_empty() => (s.to_string(), Some(e.to_string())),+ _ => (name, None),+ };+ DriveItem {+ drivewsid: format!("{FILE}{}", p.id),+ parent_id: Some(parent.to_string()),+ name: stem,+ extension: ext,+ kind: "FILE".into(),+ size: p.size,+ child_count: None,+ created_at: p.added_at,+ modified_at: Some(p.taken_at),+ etag: p.change_tag.clone(),+ }+}++/// (year, month 1–12) a photo was taken in, in this computer's time zone.+fn taken(p: &Photo) -> (i16, i8) {+ let zone = jiff::tz::TimeZone::system();+ jiff::Timestamp::from_second(p.taken_at)+ .map(|t| t.to_zoned(zone).date())+ .map_or((1970, 1), |d| (d.year(), d.month()))+}++/// What a folder holds, read from the library (the app keeps it in step with Apple).+fn children(app: &AppHandle, id: &str) -> Option<Vec<DriveItem>> {+ let data = app.state::<Data>();+ let library = data.0.blocking_lock();+ let photos = |view: View| library.photos(view).unwrap_or_default();+ Some(match id {+ ROOT => vec![+ folder(LIBRARY.into(), ROOT, "Library".into()),+ folder(ALBUMS.into(), ROOT, "Albums".into()),+ folder(FAVORITES.into(), ROOT, "Favorites".into()),+ folder(VIDEOS.into(), ROOT, "Videos".into()),+ ],+ LIBRARY => {+ let mut years: Vec<i16> = photos(View::Library).iter().map(|p| taken(p).0).collect();+ years.sort_unstable();+ years.dedup();+ years+ .into_iter()+ .rev()+ .map(|y| folder(format!("PH::y:{y}"), LIBRARY, y.to_string()))+ .collect()+ }+ FAVORITES => photos(View::Favorites)+ .iter()+ .map(|p| file(p, FAVORITES))+ .collect(),+ VIDEOS => photos(View::Videos)+ .iter()+ .map(|p| file(p, VIDEOS))+ .collect(),+ ALBUMS => albums_in(&library, None, ALBUMS),+ _ => {+ if let Some(y) = id.strip_prefix("PH::y:") {+ let y: i16 = y.parse().ok()?;+ let mut months: Vec<i8> = photos(View::Library)+ .iter()+ .filter(|p| taken(p).0 == y)+ .map(|p| taken(p).1)+ .collect();+ months.sort_unstable();+ months.dedup();+ months+ .into_iter()+ .map(|m| {+ let name =+ format!("{m:02} {}", MONTHS[usize::try_from(m - 1).unwrap_or(0)]);+ folder(format!("PH::m:{y}-{m}"), id, name)+ })+ .collect()+ } else if let Some(ym) = id.strip_prefix("PH::m:") {+ let (y, m) = ym.split_once('-')?;+ let (y, m): (i16, i8) = (y.parse().ok()?, m.parse().ok()?);+ photos(View::Library)+ .iter()+ .filter(|p| taken(p) == (y, m))+ .map(|p| file(p, id))+ .collect()+ } else {+ let album = id.strip_prefix("PH::album:")?;+ let is_folder = library+ .albums()+ .ok()?+ .iter()+ .any(|a| a.id == album && a.folder);+ if is_folder {+ albums_in(&library, Some(album), id)+ } else {+ library+ .album_photos(album)+ .ok()?+ .iter()+ .filter(|p| !p.hidden && !p.deleted)+ .map(|p| file(p, id))+ .collect()+ }+ }+ }+ })+}++/// The albums (and album folders) directly inside `parent`, in Photos' own order.+fn albums_in(library: &quince_core::Library, parent: Option<&str>, at: &str) -> Vec<DriveItem> {+ let mut albums: Vec<_> = library+ .albums()+ .unwrap_or_default()+ .into_iter()+ .filter(|a| a.parent.as_deref() == parent)+ .collect();+ albums.sort_by_key(|a| a.position);+ albums+ .into_iter()+ .map(|a| folder(format!("PH::album:{}", a.id), at, a.name))+ .collect()+}++pub struct PhotosStore(pub AppHandle);++impl Store for PhotosStore {+ fn children(&self, folder: &str) -> Option<Vec<DriveItem>> {+ children(&self.0, folder)+ }+}++pub struct PhotosRemote(pub AppHandle);++impl Remote for PhotosRemote {+ fn list(&self, folder: &str) -> Fut<Vec<DriveItem>> {+ // Nothing to ask Apple: the library is kept in step by the app's own sync.+ let (app, folder) = (self.0.clone(), folder.to_string());+ Box::pin(async move {+ tauri::async_runtime::spawn_blocking(move || {+ children(&app, &folder).unwrap_or_default()+ })+ .await+ .map_err(|e| e.to_string())+ })+ }++ fn read(&self, _item: &DriveItem, _offset: u64, _len: u64) -> Fut<Vec<u8>> {+ // Every photo is read from the app's cache (file): never through the folder's own.+ Box::pin(async { Err("read through the photo cache".to_string()) })+ }++ fn file(&self, item: &DriveItem) -> Option<Fut<PathBuf>> {+ let id = item.drivewsid.strip_prefix(FILE)?.to_string();+ let app = self.0.clone();+ Some(Box::pin(+ async move { cached(&app, &id, Size::Original).await },+ ))+ }++ fn is_local(&self, item: &DriveItem) -> bool {+ item.drivewsid+ .strip_prefix(FILE)+ .is_some_and(|id| cache_path(&self.0, id, Size::Original).exists())+ }++ fn thumbnails(&self, folder: &str) -> Fut<HashMap<String, Vec<u8>>> {+ let (app, folder) = (self.0.clone(), folder.to_string());+ Box::pin(async move {+ let (a, f) = (app.clone(), folder.clone());+ let files =+ tauri::async_runtime::spawn_blocking(move || children(&a, &f).unwrap_or_default())+ .await+ .map_err(|e| e.to_string())?;+ let mut out = HashMap::new();+ for item in files.iter().filter(|i| i.kind == "FILE") {+ let Some(id) = item.drivewsid.strip_prefix(FILE) else {+ continue;+ };+ if let Ok(path) = cached(&app, id, Size::Thumb).await {+ if let Ok(bytes) = tokio::fs::read(&path).await {+ out.insert(item.drivewsid.clone(), bytes);+ }+ }+ }+ Ok(out)+ })+ }+}diff --git a/src-tauri/src/photos.rs b/src-tauri/src/photos.rsindex 068f904..412ea02 100644--- a/src-tauri/src/photos.rs+++ b/src-tauri/src/photos.rs@@ -232,7 +232,7 @@ pub async fn fitted(app: &AppHandle, id: &str, long: u32) -> Result<Vec<u8>, Strlast.ok_or_else(|| "No picture of that photo could be made.".into())}-fn cache_path(app: &AppHandle, id: &str, size: Size) -> PathBuf {+pub(crate) fn cache_path(app: &AppHandle, id: &str, size: Size) -> PathBuf {crate::state_dir(app).join("photos").join(size.name())diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex 0b27e26..b69c384 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -100,6 +100,10 @@ export const api = {driveFolderStatus: () => invoke<DriveFolder>("drive_folder_status"),driveFolderSet: (on: boolean) => invoke<DriveFolder>("drive_folder_set", { on }),driveFolderOpen: () => invoke<void>("drive_folder_open"),+ /** The iCloud Photos folder on this computer: the same, for photos (read-only for now). */+ photosFolderStatus: () => invoke<DriveFolder>("photos_folder_status"),+ photosFolderSet: (on: boolean) => invoke<DriveFolder>("photos_folder_set", { on }),+ photosFolderOpen: () => invoke<void>("photos_folder_open"),photoPlay: (id: string) => invoke<void>("photo_play", { id }),/** Where the window's player fetches videos from (a loopback server), or null without one. */videoBase: () => invoke<string | null>("video_base"),diff --git a/src/screens/SettingsView.tsx b/src/screens/SettingsView.tsxindex 8496448..c44cd24 100644--- a/src/screens/SettingsView.tsx+++ b/src/screens/SettingsView.tsx@@ -38,6 +38,8 @@ export function SettingsView({ onSignOut }: { onSignOut: () => void }) {const [savedReport, setSavedReport] = useState<string | null>(null);const [folder, setFolder] = useState<DriveFolder | null>(null);const [folderBusy, setFolderBusy] = useState(false);+ const [photosFolder, setPhotosFolder] = useState<DriveFolder | null>(null);+ const [photosBusy, setPhotosBusy] = useState(false);const { report, syncing, refresh } = useSync();useEffect(() => {@@ -46,6 +48,7 @@ export function SettingsView({ onSignOut }: { onSignOut: () => void }) {api.settingsGet().then(setAlerts, (e) => setError(messageOf(e)));getVersion().then(setVersion, () => {});api.driveFolderStatus().then(setFolder, () => {});+ api.photosFolderStatus().then(setPhotosFolder, () => {});}, []);// A switch moves the moment it is pressed, and goes back with the reason if it could not@@ -168,6 +171,40 @@ export function SettingsView({ onSignOut }: { onSignOut: () => void }) {<span className="switch-knob" /></button></div>+ <div className="settings-row">+ <AppIcon app="photos" />+ <span className="settings-label settings-stack">+ iCloud Photos folder+ <span className={`settings-hint${photosFolder?.problem ? " is-trouble" : ""}`}>+ {photosFolder?.problem ??+ (photosFolder?.on ? photosFolder.path : "Your photos by date and album, for every other app")}+ </span>+ </span>+ {photosFolder?.on && (+ <button className="quiet" onClick={() => api.photosFolderOpen().catch((e) => setError(messageOf(e)))}>+ Open+ </button>+ )}+ <button+ className="switch"+ role="switch"+ aria-checked={photosFolder?.on ?? false}+ aria-label="iCloud Photos folder"+ disabled={!photosFolder || photosBusy}+ onClick={() => {+ if (!photosFolder) return;+ const on = !photosFolder.on;+ setPhotosFolder({ ...photosFolder, on, problem: null });+ setPhotosBusy(true);+ api+ .photosFolderSet(on)+ .then(setPhotosFolder, (e) => setPhotosFolder({ ...photosFolder, problem: messageOf(e) }))+ .finally(() => setPhotosBusy(false));+ }}+ >+ <span className="switch-knob" />+ </button>+ </div></section><h2 className="settings-heading">Appearance</h2>