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: what is still to send, told in Settings
Yashwanth Kamireddi9615fda8bcde
diff --git a/.uiverify/settings-drive-folder.mjs b/.uiverify/settings-drive-folder.mjsindex e1bfab4..fbada30 100644--- a/.uiverify/settings-drive-folder.mjs+++ b/.uiverify/settings-drive-folder.mjs@@ -19,6 +19,16 @@ 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");+ok(/Up to date/.test(await page.locator(".settings-row", { has: sw }).innerText()), "up to date while nothing waits");+// What the folder has still to send, told as it changes (read every two seconds).+await page.evaluate(() => { window.__driveWaiting = { files: 2, sending: 1, failure: null }; });+await page.waitForTimeout(2300);+ok(/Uploading 2 files…/.test(await page.locator(".settings-row", { has: sw }).innerText()), "uploading, as it happens");+await page.evaluate(() => { window.__driveWaiting = { files: 1, sending: 0, failure: "iCloud is busy right now. Nothing was changed — try again in a minute." }; });+await page.waitForTimeout(2300);+const stuck = page.locator(".settings-row", { has: sw }).locator(".settings-hint");+ok(/1 file waiting — iCloud is busy/.test(await stuck.innerText()) && /is-trouble/.test(await stuck.getAttribute("class")), "and why something waits, marked");+await page.evaluate(() => { window.__driveWaiting = null; });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();diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjsindex de794a0..3f3fbf9 100644--- a/.uiverify/stub.mjs+++ b/.uiverify/stub.mjs@@ -517,10 +517,13 @@ 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_status": {+ const f = (window.__driveFolder ??= { on: false, path: "/home/test/iCloud Drive", problem: null });+ return f.on && window.__driveWaiting ? { ...f, waiting: window.__driveWaiting } : f;+ }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 });+ return (window.__driveFolder = { on: args.on, path: "/home/test/iCloud Drive", problem: null, waiting: args.on ? { files: 0, sending: 0, failure: null } : 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 });diff --git a/crates/quince-vfs/src/fuse.rs b/crates/quince-vfs/src/fuse.rsindex b9faf1e..b4a6288 100644--- a/crates/quince-vfs/src/fuse.rs+++ b/crates/quince-vfs/src/fuse.rs@@ -98,6 +98,12 @@ impl DriveFs {self}+ /// What is written here and not yet at Apple, for the app to show (before mounting).+ #[must_use]+ pub fn writes(&self) -> Option<Arc<Writes>> {+ self.0.writes.clone()+ }+/// Nothing in it can be changed: every change answered "read-only file system".#[must_use]pub fn read_only(mut self) -> Self {@@ -440,6 +446,8 @@ impl Inner {modified: SystemTime::now(),sender: false,quiet_since: None,+ sending: false,+ failure: None,},);Ok(())@@ -524,6 +532,7 @@ impl Inner {let out = out_dir.join(&p.name);let copied = std::fs::create_dir_all(&out_dir).is_ok()&& std::fs::copy(writes.staging(ino, &p.name), &out).is_ok();+ me.with_pending(ino, |p| p.sending = true);let result = if copied {let r = writes::send(me.remote.as_ref(),@@ -538,6 +547,10 @@ impl Inner {} else {Err("the bytes could not be read".into())};+ me.with_pending(ino, |p| {+ p.sending = false;+ p.failure = result.as_ref().err().map(|e| e.chars().take(160).collect());+ });match result {Ok(sent) => {if !sent.conflicted {@@ -1035,6 +1048,8 @@ impl Filesystem for DriveFs {modified: SystemTime::now(),sender: false,quiet_since: None,+ sending: false,+ failure: None,},);innerdiff --git a/crates/quince-vfs/src/writes.rs b/crates/quince-vfs/src/writes.rsindex 1d63d98..f4cb368 100644--- a/crates/quince-vfs/src/writes.rs+++ b/crates/quince-vfs/src/writes.rs@@ -45,6 +45,22 @@ pub struct Pending {/// Since when nothing has touched it: it is sent once left alone (SETTLE).#[serde(skip)]pub quiet_since: Option<std::time::Instant>,+ /// On its way to Apple right now.+ #[serde(skip)]+ pub sending: bool,+ /// Why the last try did not go, said once it has failed (cleared when it goes).+ #[serde(skip)]+ pub failure: Option<String>,+}++/// What is waiting to go, as a person is told it: how many files, how many on their way now,+/// and the reason one would not go, if one would not.+#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Waiting {+ pub files: u32,+ pub sending: u32,+ pub failure: Option<String>,}/// Names programs use for their own scratch files, which never leave this computer: Vim's@@ -147,6 +163,24 @@ impl Writes {let _ = std::fs::remove_dir_all(self.dir.join(ino.to_string()));}+ /// What is waiting to go: scratch files, which never go, are not counted.+ #[must_use]+ pub fn waiting(&self) -> Waiting {+ let items = self+ .items+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let mut w = Waiting::default();+ for p in items.values().filter(|p| p.dirty && !stays_local(&p.name)) {+ w.files += 1;+ w.sending += u32::from(p.sending);+ if w.failure.is_none() {+ w.failure.clone_from(&p.failure);+ }+ }+ w+ }+/// The lane sends under one name wait in, one after another.pub fn lane(&self, key: &str) -> std::sync::Arc<tokio::sync::Mutex<()>> {let mut lanes = self@@ -317,6 +351,8 @@ mod tests {modified: SystemTime::now(),sender: false,quiet_since: None,+ sending: false,+ failure: None,};std::fs::create_dir_all(w.staging(7, "a.txt").parent().unwrap()).unwrap();std::fs::write(w.staging(7, "a.txt"), b"hi").unwrap();diff --git a/crates/quince-vfs/tests/writes.rs b/crates/quince-vfs/tests/writes.rsindex a84927c..40372dc 100644--- a/crates/quince-vfs/tests/writes.rs+++ b/crates/quince-vfs/tests/writes.rs@@ -17,6 +17,8 @@ struct World {folders: Mutex<HashMap<String, Vec<DriveItem>>>,bytes: Mutex<HashMap<String, Vec<u8>>>,uploads: Mutex<Vec<String>>,+ /// Apple refusing every change, as when it is down.+ refuse: Mutex<bool>,/// How long each step at "Apple" takes: slow, as on a real connection.slow: Mutex<Duration>,deleted: Mutex<Vec<String>>,@@ -115,6 +117,9 @@ impl Remote for Apple {Box::pin(async move { Ok(b) })}fn upload(&self, folder: &DriveItem, path: &Path) -> Fut<DriveItem> {+ if *self.0.refuse.lock().unwrap() {+ return Box::pin(async { Err("iCloud is busy right now".to_string()) });+ }let bytes = std::fs::read(path).unwrap();let mut name = path.file_name().unwrap().to_str().unwrap().to_string();// A name already taken is filed as "name 2", as Apple files it.@@ -151,6 +156,9 @@ impl Remote for Apple {Box::pin(async { Ok(()) })}fn delete(&self, it: &DriveItem) -> Fut<()> {+ if *self.0.refuse.lock().unwrap() {+ return Box::pin(async { Err("iCloud is busy right now".to_string()) });+ }let slow = *self.0.slow.lock().unwrap() / 5;let (world, id) = (Arc::clone(&self.0), it.drivewsid.clone());Box::pin(async move {@@ -407,3 +415,79 @@ fn a_save_during_a_send_waits_its_turn() {);drop(session);}++/// What is waiting is told as it is: one file on its way while Apple is slow, nothing once it+/// is there, and Apple's reason while it refuses — so nothing ever waits unseen.+#[test]+fn what_is_waiting_is_told() {+ if !Path::new("/dev/fuse").exists() {+ return;+ }+ let world = Arc::new(World::default());+ world+ .folders+ .lock()+ .unwrap()+ .insert(ROOT.into(), Vec::new());+ *world.slow.lock().unwrap() = Duration::from_millis(1500);+ let rt = tokio::runtime::Runtime::new().unwrap();+ let (cache, staging, at) = (+ tempfile::tempdir().unwrap(),+ tempfile::tempdir().unwrap(),+ tempfile::tempdir().unwrap(),+ );+ let fs = fuse::DriveFs::new(+ Arc::new(Apple(Arc::clone(&world))),+ Arc::new(Library(Arc::clone(&world))),+ Arc::new(Cache::new(cache.path()).unwrap()),+ rt.handle().clone(),+ )+ .with_writes(staging.path())+ .unwrap();+ let writes = fs.writes().unwrap();+ let session = fuse::mount(fs, at.path()).unwrap();+ std::fs::write(at.path().join("a.txt"), b"a").unwrap();+ std::fs::write(at.path().join(".a.txt.swp"), b"vim").unwrap();+ assert_eq!(+ writes.waiting().files,+ 1,+ "one waiting; the scratch file is not counted"+ );+ let mut seen_sending = false;+ for _ in 0..60 {+ let w = writes.waiting();+ seen_sending |= w.sending == 1;+ if w.files == 0 {+ break;+ }+ std::thread::sleep(Duration::from_millis(100));+ }+ assert!(seen_sending, "told while on its way");+ assert_eq!(+ writes.waiting().files,+ 0,+ "nothing waiting once Apple has it"+ );+ *world.refuse.lock().unwrap() = true;+ *world.slow.lock().unwrap() = Duration::ZERO;+ std::fs::write(at.path().join("b.txt"), b"b").unwrap();+ let mut why = None;+ for _ in 0..60 {+ why = writes.waiting().failure;+ if why.is_some() {+ break;+ }+ std::thread::sleep(Duration::from_millis(100));+ }+ assert_eq!(+ why.as_deref(),+ Some("iCloud is busy right now"),+ "Apple's reason, while it refuses"+ );+ assert_eq!(+ writes.waiting().files,+ 1,+ "and the file still waiting, not lost"+ );+ drop(session);+}diff --git a/src-tauri/src/mount.rs b/src-tauri/src/mount.rsindex bf1af68..ad75201 100644--- a/src-tauri/src/mount.rs+++ b/src-tauri/src/mount.rs@@ -24,6 +24,9 @@ const LINK_LIFE: Duration = Duration::from_secs(20 * 60);#[cfg(target_os = "linux")]static SESSIONS: Mutex<Vec<(Which, PathBuf, fuser::BackgroundSession)>> = Mutex::new(Vec::new());+/// What the iCloud Drive folder has written and not yet sent, while it is up.+static WRITES: Mutex<Option<Arc<quince_vfs::writes::Writes>>> = Mutex::new(None);+struct AppRemote {app: AppHandle,links: Arc<Mutex<HashMap<String, (String, Instant)>>>,@@ -262,6 +265,8 @@ pub struct FolderStatus {pub on: bool,pub path: String,pub problem: Option<String>,+ /// Files written into it and not yet at Apple (the Drive folder).+ pub waiting: Option<quince_vfs::writes::Waiting>,}#[cfg(target_os = "linux")]@@ -333,6 +338,11 @@ fn start(app: &AppHandle, which: Which, at: &std::path::Path) -> Result<(), Striif let Some(thumbs) = thumbnail_cache(app) {fs = fs.with_thumbnails(at.to_path_buf(), thumbs);}+ if which == Which::Drive {+ *WRITES+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner) = fs.writes();+ }let session = quince_vfs::fuse::mount(fs, at).map_err(|e| format!("The folder could not be mounted: {e}"))?;SESSIONS@@ -352,6 +362,11 @@ fn stop(which: Which) {*sessions = keep;go};+ if which == Which::Drive {+ *WRITES+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner) = None;+ }for (_, at, session) in gone {drop(session);// The empty folder the mount stood on is put away too, as it was made for it.@@ -372,10 +387,21 @@ fn mounted(_which: Which) -> Option<PathBuf> {fn status(app: &AppHandle, which: Which, problem: Option<String>) -> FolderStatus {let at = mounted(which).unwrap_or_else(|| place(app, which));+ let on = mounted(which).is_some();+ let waiting = if which == Which::Drive && on {+ WRITES+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .as_ref()+ .map(|w| w.waiting())+ } else {+ None+ };FolderStatus {- on: mounted(which).is_some(),+ on,path: at.to_string_lossy().into_owned(),problem,+ waiting,}}diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex b69c384..6c6d98b 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -762,4 +762,10 @@ export function turnStyle(turn: Turn | null | undefined, w: number, h: number):}/** The iCloud Drive folder on this computer (see src-tauri/src/mount.rs). */-export type DriveFolder = { on: boolean; path: string; problem: string | null };+export type DriveFolder = {+ on: boolean;+ path: string;+ problem: string | null;+ /** Files written into the folder and not yet at Apple (the Drive folder only). */+ waiting?: { files: number; sending: number; failure: string | null } | null;+};diff --git a/src/screens/SettingsView.tsx b/src/screens/SettingsView.tsxindex c44cd24..31133e2 100644--- a/src/screens/SettingsView.tsx+++ b/src/screens/SettingsView.tsx@@ -15,6 +15,16 @@ const ICON: Record<string, string> = {drive: "drivews",};+/** The Drive folder's line when it is up: up to date, uploading, or why something is waiting. */+function folderState(f: DriveFolder): string {+ const w = f.waiting;+ const files = (n: number) => `${n} ${n === 1 ? "file" : "files"}`;+ if (!w || w.files === 0) return `Up to date · ${f.path}`;+ if (w.failure) return `${files(w.files)} waiting — ${w.failure}`;+ if (w.sending > 0) return `Uploading ${files(w.files)}…`;+ return `${files(w.files)} waiting to upload`;+}+function size(bytes: number): string {const gb = bytes / 1024 ** 3;if (gb >= 1) return `${gb >= 10 ? gb.toFixed(0) : gb.toFixed(1)} GB`;@@ -50,6 +60,16 @@ export function SettingsView({ onSignOut }: { onSignOut: () => void }) {api.driveFolderStatus().then(setFolder, () => {});api.photosFolderStatus().then(setPhotosFolder, () => {});}, []);+ // While the Drive folder is up, what it has still to send is read every two seconds (a+ // local question; nothing asked of Apple), so nothing ever waits unseen.+ const folderOn = folder?.on ?? false;+ useEffect(() => {+ if (!folderOn) return undefined;+ const t = window.setInterval(() => {+ api.driveFolderStatus().then(setFolder, () => {});+ }, 2000);+ return () => window.clearInterval(t);+ }, [folderOn]);// A switch moves the moment it is pressed, and goes back with the reason if it could not// be kept.@@ -139,8 +159,8 @@ export function SettingsView({ onSignOut }: { onSignOut: () => void }) {<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 className={`settings-hint${folder?.problem || folder?.waiting?.failure ? " is-trouble" : ""}`}>+ {folder?.problem ?? (folder?.on ? folderState(folder) : "Your iCloud Drive in Files and every other app")}</span></span>{folder?.on && (