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 Drive folder in the app: Settings switch, off by default, read-only
Yashwanth Kamireddi51f38aa96ad6
diff --git a/.uiverify/settings-drive-folder.mjs b/.uiverify/settings-drive-folder.mjsnew file mode 100644index 0000000..bc8bec8--- /dev/null+++ b/.uiverify/settings-drive-folder.mjs@@ -0,0 +1,33 @@+// Settings → On This Computer: the iCloud Drive folder, off until turned on. The switch moves+// at once; once on, where it is and an Open button; one that cannot come up says why and is+// left off.+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";+const b = await engine.launch();+const ctx = await b.newContext({ viewport: { width: 1200, height: 900 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });+const page = await ctx.newPage();+page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };+await page.locator(".account-card, [aria-label*='Settings'], .sidebar-foot button").first().click();+await page.waitForTimeout(400);+const sw = page.getByRole("switch", { name: "iCloud Drive folder" });+ok((await sw.getAttribute("aria-checked")) === "false", "off until turned on");+await sw.click();+await page.waitForTimeout(200);+ok((await sw.getAttribute("aria-checked")) === "true", "turned on");+ok(/\/home\/test\/iCloud Drive/.test(await page.locator(".settings-row", { has: sw }).innerText()), "and says where the folder is");+await page.locator(".settings-row", { has: sw }).getByRole("button", { name: "Open" }).click();+ok((await page.evaluate(() => window.__opened)).includes("drive"), "Open shows it in the file manager");+await sw.click();+await page.waitForTimeout(200);+ok((await sw.getAttribute("aria-checked")) === "false", "and off again");+await page.evaluate(() => { window.__driveFolderRefuse = "/home/test/iCloud Drive already has files in it. Choose an empty folder."; });+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, " ")}"`);+await b.close();+process.exitCode = failures ? 1 : (process.exitCode ?? 0);diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjsindex 8c90699..b7e117b 100644--- a/.uiverify/stub.mjs+++ b/.uiverify/stub.mjs@@ -517,6 +517,11 @@ export function installStub({ screen, services, twoFactor, calendarFixture, notecase "contact_me": return window.__me ?? (contactsFixture ? "c1" : null);case "contact_set_me": await new Promise((r) => setTimeout(r, 600)); window.__me = args.guid; return null;case "contacts_export": (window.__exports ??= []).push(args); return `/home/test/Downloads/${args.fileName}`;+ case "drive_folder_status": return window.__driveFolder ??= { on: false, path: "/home/test/iCloud Drive", problem: null };+ case "drive_folder_set":+ if (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 "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/Cargo.lock b/Cargo.lockindex 94e042e..b3f09a4 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3618,6 +3618,7 @@ version = "0.1.0"dependencies = ["anyhow","base64 0.22.1",+ "fuser","futures-util","gstreamer","gstreamer-app",@@ -3630,6 +3631,7 @@ dependencies = ["quince-core","quince-icloud","quince-media",+ "quince-vfs","reqwest 0.12.28","serde","serde_json",@@ -5323,6 +5325,7 @@ dependencies = ["libc","mio","pin-project-lite",+ "signal-hook-registry","socket2","tokio-macros","windows-sys 0.61.2",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex c846b26..17545ab 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -13,6 +13,7 @@ futures-util = { version = "0.3", default-features = false, features = ["std"] }# A video's poster when Apple's is blank: one frame read with GStreamer, which WebKitGTK# already needs, so nothing new is installed.gstreamer = "0.25"+quince-vfs = { path = "../crates/quince-vfs" }gstreamer-app = "0.25"gstreamer-video = "0.25"tauri = { version = "2", features = ["tray-icon", "image-png"] }@@ -23,7 +24,7 @@ quince-icloud = { path = "../crates/quince-icloud" }reqwest.workspace = trueserde.workspace = trueserde_json.workspace = true-tokio = { workspace = true }+tokio = { workspace = true, features = ["signal"] }anyhow.workspace = truejiff = "0.2.37"uuid.workspace = true@@ -35,6 +36,9 @@ zbus = "5"tauri-plugin-single-instance = "2"libc = "0.2"+[target.'cfg(target_os = "linux")'.dependencies]+fuser = { version = "0.18", default-features = false }+[dev-dependencies]image = { version = "0.25", default-features = false, features = ["jpeg"] }tempfile = "3"diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex c3e180d..1d68f5e 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -14,6 +14,7 @@ macro_rules! quiet {mod alerts;mod cpu;+mod mount;mod outbox;mod photos;mod poster;@@ -544,6 +545,8 @@ async fn auth_submit_sms_code(phone_id: u64, code: String, auth: State<'_, Auth>#[tauri::command]async fn auth_sign_out(auth: State<'_, Auth>) -> UiResult<()> {+ // The iCloud Drive folder goes with the session it was served by.+ mount::release();let mut client = auth.client.lock().await;client.sign_out().map_err(|e| e.to_string())}@@ -3827,6 +3830,37 @@ fn main() {let mut library = Library::open(&dir)?;adopt_writer(&mut library);app.manage(Data(Mutex::new(library)));+ mount::resume(app.handle());+ // Logging out or shutting down ends the app with a signal, not through its own+ // quit, and a crash ends it with neither: either way the iCloud Drive folder is+ // let go of first, never left behind answering "Transport endpoint is not+ // connected".+ #[cfg(unix)]+ {+ let handle = app.handle().clone();+ tauri::async_runtime::spawn(async move {+ use tokio::signal::unix::{signal, SignalKind};+ let (Ok(mut term), Ok(mut int), Ok(mut hup)) = (+ signal(SignalKind::terminate()),+ signal(SignalKind::interrupt()),+ signal(SignalKind::hangup()),+ ) else {+ return;+ };+ tokio::select! {+ _ = term.recv() => {}+ _ = int.recv() => {}+ _ = hup.recv() => {}+ }+ mount::release();+ handle.exit(0);+ });+ let before = std::panic::take_hook();+ std::panic::set_hook(Box::new(move |info| {+ mount::release();+ before(info);+ }));+ }app.manage(Occasions {feed: Mutex::new((None, Vec::new())),});@@ -3910,6 +3944,9 @@ fn main() {photos::photos_in_album,photos::photo_set_flag,photos::photo_play,+ mount::drive_folder_status,+ mount::drive_folder_set,+ mount::drive_folder_open,photos::photo_video_turn,photos::photos_set_flag,photos::photos_burst,@@ -3978,8 +4015,15 @@ fn main() {reminder_set_done,reminder_set_repeat,])- .run(tauri::generate_context!())- .expect("Quince failed to start");+ .build(tauri::generate_context!())+ .expect("Quince failed to start")+ .run(|_app, event| {+ // The iCloud Drive folder goes with the app: left mounted, it would answer+ // nothing ("Transport endpoint is not connected").+ if let tauri::RunEvent::Exit = event {+ mount::release();+ }+ });}#[cfg(test)]diff --git a/src-tauri/src/mount.rs b/src-tauri/src/mount.rsnew file mode 100644index 0000000..b5367e0--- /dev/null+++ b/src-tauri/src/mount.rs@@ -0,0 +1,287 @@+//! iCloud Drive as a folder on this computer (quince-vfs), served by the app itself: its+//! signed-in session, its library, and what it learns kept in the library for the window too.+//! Off until it is turned on in Settings; read-only for now. See docs/mount-design.md.++use crate::{Auth, Data};+use quince_core::drive::DriveItem;+use quince_vfs::{Fut, Remote, Store};+use std::collections::HashMap;+use std::path::PathBuf;+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};+use tauri::{AppHandle, Manager};++/// Whether the folder is wanted, kept in the library.+const ON_KEY: &str = "drive_folder_on";+/// Where it is mounted, when moved from the default.+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.+#[cfg(target_os = "linux")]+static SESSION: Mutex<Option<(PathBuf, fuser::BackgroundSession)>> = Mutex::new(None);++struct AppRemote {+ app: AppHandle,+ links: Arc<Mutex<HashMap<String, (String, Instant)>>>,+}++/// The session's address for one Apple service, with the auth lock let go first.+async fn context(+ app: &AppHandle,+ service: &str,+) -> Result<(reqwest::Client, String, Vec<(String, String)>), String> {+ let auth = app.state::<Auth>();+ let client = auth.client.lock().await;+ let root = client+ .session()+ .service_url(service)+ .ok_or("Apple hasn't offered iCloud Drive for this account.")?;+ Ok((client.http().clone(), root, client.service_params()))+}++impl Remote for AppRemote {+ fn list(&self, folder: &str) -> Fut<Vec<DriveItem>> {+ let (app, folder) = (self.app.clone(), folder.to_string());+ Box::pin(async move {+ let (http, root, params) = context(&app, "drivews").await?;+ let _one = crate::DRIVE_PASS.lock().await;+ let items = quince_icloud::drive::fetch_folder(&http, &root, params, &folder)+ .await+ .map_err(|e| e.to_string())?;+ // Kept, so the window's Drive knows it too and the next look needs no network.+ let data = app.state::<Data>();+ let mut library = data.0.lock().await;+ quince_icloud::drive::store_folder(&mut library, &folder, &items)+ .map_err(|e| e.to_string())?;+ Ok(items)+ })+ }++ fn read(&self, item: &DriveItem, offset: u64, len: u64) -> Fut<Vec<u8>> {+ let (app, links, item) = (self.app.clone(), Arc::clone(&self.links), item.clone());+ Box::pin(async move {+ let key = format!("{}~{}", item.drivewsid, item.etag.as_deref().unwrap_or(""));+ let known = links+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .get(&key)+ .filter(|(_, at)| at.elapsed() < LINK_LIFE)+ .map(|(u, _)| u.clone());+ // A link Apple no longer honours is asked for again, once.+ for fresh in [known.is_none(), true] {+ let url = match (&known, fresh) {+ (Some(u), false) => u.clone(),+ _ => {+ let (http, docws, params) = context(&app, "docws").await?;+ let u = quince_icloud::drive::download_url(&http, &docws, params, &item)+ .await+ .map_err(|e| e.to_string())?;+ links+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .insert(key.clone(), (u.clone(), Instant::now()));+ u+ }+ };+ let http = app.state::<Auth>().client.lock().await.http().clone();+ let r = http+ .get(&url)+ .header("Range", format!("bytes={offset}-{}", offset + len - 1))+ .send()+ .await+ .map_err(|e| e.to_string())?;+ let status = r.status().as_u16();+ if matches!(status, 401 | 403 | 404 | 410) && !fresh {+ continue;+ }+ let whole = status == 200;+ if status != 206 && !whole {+ return Err(format!("Apple answered {status}"));+ }+ let bytes = r.bytes().await.map_err(|e| e.to_string())?;+ // A server that ignores the range sends the whole file: the part is cut from it.+ return Ok(if whole {+ let from = usize::try_from(offset)+ .unwrap_or(usize::MAX)+ .min(bytes.len());+ let to = usize::try_from(offset + len)+ .unwrap_or(usize::MAX)+ .min(bytes.len());+ bytes[from..to].to_vec()+ } else {+ bytes.to_vec()+ });+ }+ Err("Apple would not send the file".into())+ })+ }+}++struct AppStore(AppHandle);++impl Store for AppStore {+ fn children(&self, folder: &str) -> Option<Vec<DriveItem>> {+ // Called on the folder's own threads, never the async runtime's: waiting is allowed.+ let data = self.0.state::<Data>();+ let library = data.0.blocking_lock();+ library.drive_children(folder).ok()+ }+}++/// 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 {+ let data = app.state::<Data>();+ let library = data.0.blocking_lock();+ library+ .state(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"))+}++/// What Settings shows: whether it is up, where, and what stopped it if anything did.+#[derive(serde::Serialize, Clone, Debug)]+#[serde(rename_all = "camelCase")]+pub struct FolderStatus {+ pub on: bool,+ pub path: String,+ pub problem: Option<String>,+}++#[cfg(target_os = "linux")]+fn mounted() -> Option<PathBuf> {+ SESSION+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .as_ref()+ .map(|(p, _)| p.clone())+}++/// The 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() {+ return Ok(());+ }+ if !std::path::Path::new("/dev/fuse").exists() {+ return Err("This computer has no FUSE, which the folder needs. Install your system's fuse3 package.".into());+ }+ if let Ok(mut entries) = std::fs::read_dir(at) {+ if entries.next().is_some() {+ return Err(format!(+ "{} already has files in it. Choose an empty folder.",+ at.display()+ ));+ }+ }+ 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();+ let fs = quince_vfs::fuse::DriveFs::new(remote, store, cache, rt);+ let session = quince_vfs::fuse::mount(fs, at)+ .map_err(|e| format!("The folder could not be mounted: {e}"))?;+ *SESSION+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner) = Some((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 {+ 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);+ }+}++#[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())+}+#[cfg(not(target_os = "linux"))]+fn stop() {}+#[cfg(not(target_os = "linux"))]+fn mounted() -> Option<PathBuf> {+ None+}++fn status(app: &AppHandle, problem: Option<String>) -> FolderStatus {+ let at = mounted().unwrap_or_else(|| place(app));+ FolderStatus {+ on: mounted().is_some(),+ path: at.to_string_lossy().into_owned(),+ problem,+ }+}++/// At start: 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}");+ }+ }+}++/// When signing out: the folder goes with the session.+pub fn release() {+ stop();+}++#[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> {+ tauri::async_runtime::spawn_blocking(move || {+ let problem = if on {+ start(&app, &place(&app)).err()+ } else {+ stop();+ 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" });+ drop(library);+ status(&app, 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> {+ use tauri_plugin_opener::OpenerExt;+ let at = mounted().ok_or("The iCloud Drive folder is off.")?;+ app.opener()+ .open_path(at.to_string_lossy(), None::<&str>)+ .map_err(|e| e.to_string())+}diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex f034960..0b27e26 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -96,6 +96,10 @@ export const api = {/** A video (or a Live Photo's moving part) opened in this computer's own player. *//** How a video's picture is turned, as its file records it (served upright: drawn here). */photoVideoTurn: (id: string, which: "original" | "video") => invoke<Turn>("photo_video_turn", { id, which }),+ /** The iCloud Drive folder on this computer: whether it is up, where, and what stopped it. */+ driveFolderStatus: () => invoke<DriveFolder>("drive_folder_status"),+ driveFolderSet: (on: boolean) => invoke<DriveFolder>("drive_folder_set", { on }),+ driveFolderOpen: () => invoke<void>("drive_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"),@@ -752,3 +756,6 @@ export function turnStyle(turn: Turn | null | undefined, w: number, h: number):transform: `matrix(${turn[0]}, ${turn[1]}, ${turn[2]}, ${turn[3]}, 0, 0)`,};}++/** The iCloud Drive folder on this computer (see src-tauri/src/mount.rs). */+export type DriveFolder = { on: boolean; path: string; problem: string | null };diff --git a/src/screens/SettingsView.tsx b/src/screens/SettingsView.tsxindex ad5e0df..8496448 100644--- a/src/screens/SettingsView.tsx+++ b/src/screens/SettingsView.tsx@@ -1,6 +1,6 @@import { useEffect, useState } from "react";import { getVersion } from "@tauri-apps/api/app";-import { api, messageOf, type AccountInfo } from "../lib/ipc";+import { api, type DriveFolder, messageOf, type AccountInfo } from "../lib/ipc";import { freshness, useSync } from "../lib/sync";import { setTheme, storedTheme, type Theme } from "../lib/theme";import { AppIcon } from "../components/AppIcon";@@ -36,6 +36,8 @@ export function SettingsView({ onSignOut }: { onSignOut: () => void }) {const [error, setError] = useState<string | null>(null);const [confirming, setConfirming] = useState(false);const [savedReport, setSavedReport] = useState<string | null>(null);+ const [folder, setFolder] = useState<DriveFolder | null>(null);+ const [folderBusy, setFolderBusy] = useState(false);const { report, syncing, refresh } = useSync();useEffect(() => {@@ -43,6 +45,7 @@ export function SettingsView({ onSignOut }: { onSignOut: () => void }) {api.storageInfo().then(setStorage, () => {});api.settingsGet().then(setAlerts, (e) => setError(messageOf(e)));getVersion().then(setVersion, () => {});+ api.driveFolderStatus().then(setFolder, () => {});}, []);// A switch moves the moment it is pressed, and goes back with the reason if it could not@@ -126,6 +129,47 @@ export function SettingsView({ onSignOut }: { onSignOut: () => void }) {</div></section>+ <h2 className="settings-heading">On This Computer</h2>+ <section className="settings-group">+ <div className="settings-row">+ <AppIcon app="drivews" />+ <span className="settings-label settings-stack">+ iCloud Drive folder+ {/* Where it is, and — when it could not come up — why, in a sentence. */}+ <span className={`settings-hint${folder?.problem ? " is-trouble" : ""}`}>+ {folder?.problem ?? (folder?.on ? folder.path : "Your iCloud Drive in Files and every other app")}+ </span>+ </span>+ {folder?.on && (+ <button className="quiet" onClick={() => api.driveFolderOpen().catch((e) => setError(messageOf(e)))}>+ Open+ </button>+ )}+ <button+ className="switch"+ role="switch"+ aria-checked={folder?.on ?? false}+ aria-label="iCloud Drive folder"+ disabled={!folder || folderBusy}+ onClick={() => {+ if (!folder) return;+ const on = !folder.on;+ // Moves at once; Apple's answer only matters when the folder could not come up.+ setFolder({ ...folder, on, problem: null });+ setFolderBusy(true);+ api+ .driveFolderSet(on)+ .then(setFolder, (e) => {+ setFolder({ ...folder, problem: messageOf(e) });+ })+ .finally(() => setFolderBusy(false));+ }}+ >+ <span className="switch-knob" />+ </button>+ </div>+ </section>+<h2 className="settings-heading">Appearance</h2><section className="settings-group"><div className="settings-row">diff --git a/src/styles/app.css b/src/styles/app.cssindex 2ddbb24..ac0bc46 100644--- a/src/styles/app.css+++ b/src/styles/app.css@@ -2091,3 +2091,7 @@one out of sight is not drawn at all. */.screen-slot { display: contents; }.screen-slot[hidden] { display: none !important; }+/* A label with a line under it: what the row is, then where or why. */+.settings-stack { display: flex; flex-direction: column; gap: 2px; min-width: 0; }+.settings-stack .settings-hint { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.settings-hint.is-trouble { color: var(--danger); white-space: normal; }