Skip to content

Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.

Accounts never mix; sign-out asks to keep a copy; caches respect the disk

Yashwanth Kamireddib69a089dfcec
diff --git a/.uiverify/signout.mjs b/.uiverify/signout.mjs
new file mode 100644
index 0000000..0d1ea12
--- /dev/null
+++ b/.uiverify/signout.mjs
@@ -0,0 +1,47 @@
+// Sign Out asks, as macOS does: keep a copy here, or remove it. What has not reached iCloud
+// yet is said plainly; Cancel and Escape change nothing; the choice reaches the backend as
+// asked, and the window starts over.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub } 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++; };
+const settings = () => page.locator(".account-card, [aria-label*='Settings'], .sidebar-foot button").first().click();
+await settings();
+await page.waitForTimeout(400);
+const signOut = page.getByRole("button", { name: "Sign Out" });
+const sheet = page.getByRole("alertdialog");
+
+await signOut.click();
+ok(await sheet.isVisible(), "Sign Out asks first");
+ok(/Keep a copy of your iCloud data on this computer\?/.test(await sheet.innerText()), "whether to keep a copy");
+ok((await sheet.locator(".signout-unsent").count()) === 0, "nothing said about unsent changes when there are none");
+ok(await page.evaluate(() => document.activeElement?.textContent === "Keep a Copy"), "Keep a Copy has the focus: Return never removes");
+await page.keyboard.press("Escape");
+ok(!(await sheet.isVisible()), "Escape cancels");
+await signOut.click();
+await sheet.getByRole("button", { name: "Cancel" }).click();
+ok(!(await sheet.isVisible()) && (await page.evaluate(() => sessionStorage.getItem("__signedOut"))) === null, "Cancel signs nothing out");
+
+await page.evaluate(() => { window.__unsent = { changes: 2, files: 1, photos: 0 }; });
+await signOut.click();
+const said = await sheet.locator(".signout-unsent").innerText();
+ok(/2 changes and 1 file haven't reached iCloud yet/.test(said) && /lost/.test(said), `what would be lost is said "${said}"`);
+await Promise.all([page.waitForEvent("load"), sheet.getByRole("button", { name: "Remove from This Computer" }).click()]);
+ok(JSON.parse(await page.evaluate(() => sessionStorage.getItem("__signedOut")))?.keep === false, "Remove asks the backend to keep nothing");
+
+await page.evaluate(() => sessionStorage.removeItem("__signedOut"));
+await page.waitForTimeout(300);
+await settings();
+await page.waitForTimeout(400);
+await signOut.click();
+await Promise.all([page.waitForEvent("load"), page.keyboard.press("Enter")]);
+ok(JSON.parse(await page.evaluate(() => sessionStorage.getItem("__signedOut")))?.keep === true, "Return keeps a copy");
+
+await b.close();
+if (failures) process.exitCode = 1;
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index 3f3fbf9..e479895 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -122,7 +122,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
writable: true, isDefault: false },
{ guid: "home", title: "Home", colour: "#0088ff", ctag: null, sortOrder: 1, enabled: true,
writable: true, isDefault: true },
- { guid: "personal", title: "Asha", colour: "#1badf8", ctag: null, sortOrder: 2, enabled: true,
+ { guid: "personal", title: "Personal", colour: "#1badf8", ctag: null, sortOrder: 2, enabled: true,
writable: true, isDefault: false },
// As the app adds them: drawn from contacts and Apple's holiday feed, read-only.
{ guid: "quince:birthdays", title: "Birthdays", colour: "#8e8e93", ctag: null, sortOrder: 900,
@@ -606,7 +606,8 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
case "auth_resend_code": return null;
case "auth_send_sms": return null;
case "auth_submit_sms_code": return null;
- case "auth_sign_out": return null;
+ case "auth_sign_out": sessionStorage.setItem("__signedOut", JSON.stringify(args)); return null;
+ case "account_unsent": return window.__unsent ?? { changes: 0, files: 0, photos: 0 };
// One refresh covers every service, so there is one command to stub rather than
// a pair per screen.
case "sync_all":
diff --git a/Cargo.lock b/Cargo.lock
index 668419a..fab1075 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3645,6 +3645,7 @@ dependencies = [
"reqwest 0.12.28",
"serde",
"serde_json",
+ "sha2",
"tauri",
"tauri-build",
"tauri-plugin-dialog",
diff --git a/crates/quince-core/src/lib.rs b/crates/quince-core/src/lib.rs
index 6449ceb..07ec9d9 100644
--- a/crates/quince-core/src/lib.rs
+++ b/crates/quince-core/src/lib.rs
@@ -29,6 +29,20 @@ pub enum Error {
pub type Result<T> = std::result::Result<T, Error>;
+/// The `app_state` keys that are this computer's, not an account's.
+const COMPUTER_KEYS: &str = "key LIKE 'settings.%' OR key IN \
+ ('drive_folder_on', 'drive_folder_path', 'photos_folder_on', 'photos_folder_path')";
+
+/// Every table holding what an account brought: all but `app_state`, which is sorted key by key.
+fn account_tables(conn: &Connection) -> Result<Vec<String>> {
+ let mut stmt = conn.prepare(
+ "SELECT name FROM sqlite_master WHERE type = 'table'
+ AND name NOT LIKE 'sqlite_%' AND name != 'app_state'",
+ )?;
+ let rows = stmt.query_map([], |r| r.get::<_, String>(0))?;
+ Ok(rows.collect::<std::result::Result<_, _>>()?)
+}
+
/// A handle to the local library.
pub struct Library {
conn: Connection,
@@ -100,6 +114,54 @@ impl Library {
Ok(())
}
+ /// Everything learned from an account let go of — every reminder, note, event, contact,
+ /// file and photo, every sync position — for another account to start clean. Kept: this
+ /// computer's own choices (`settings.*`, which folders are on and where).
+ ///
+ /// Signed out and back in as someone else, the last account's data stayed and the new
+ /// one's was laid over it, from the old account's sync positions.
+ pub fn forget_account(&mut self) -> Result<()> {
+ let tx = self.conn.transaction()?;
+ for table in account_tables(&tx)? {
+ tx.execute(&format!("DELETE FROM \"{table}\""), [])?;
+ }
+ tx.execute(
+ &format!("DELETE FROM app_state WHERE NOT ({COMPUTER_KEYS})"),
+ [],
+ )?;
+ tx.commit()?;
+ Ok(())
+ }
+
+ /// This computer's own choices, which go with the computer, never with an account: carried
+ /// over when one account's library is set aside for another's.
+ pub fn computer_state(&self) -> Result<Vec<(String, String)>> {
+ let mut stmt = self.conn.prepare(&format!(
+ "SELECT key, value FROM app_state WHERE {COMPUTER_KEYS}"
+ ))?;
+ let rows = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?;
+ Ok(rows.collect::<std::result::Result<_, _>>()?)
+ }
+
+ /// Whether anything of an account is here at all — a record, a sync position, a fact.
+ pub fn holds_account(&self) -> Result<bool> {
+ for table in account_tables(&self.conn)? {
+ let any: bool = self.conn.query_row(
+ &format!("SELECT EXISTS (SELECT 1 FROM \"{table}\")"),
+ [],
+ |r| r.get(0),
+ )?;
+ if any {
+ return Ok(true);
+ }
+ }
+ Ok(self.conn.query_row(
+ &format!("SELECT EXISTS (SELECT 1 FROM app_state WHERE NOT ({COMPUTER_KEYS}))"),
+ [],
+ |r| r.get(0),
+ )?)
+ }
+
/// What was remembered under that name, if anything.
pub fn state(&self, key: &str) -> Result<Option<String>> {
let mut stmt = self
@@ -117,6 +179,61 @@ impl Library {
mod tests {
use super::*;
+ /// Another account signing in finds nothing of the last one's, and this computer's own
+ /// choices still where they were.
+ #[test]
+ fn an_account_is_forgotten_whole() {
+ let mut lib = Library::in_memory().unwrap();
+ lib.put_drive_children(
+ "root",
+ &[crate::drive::DriveItem {
+ drivewsid: "FILE::x::1".into(),
+ parent_id: Some("root".into()),
+ name: "Plan".into(),
+ extension: Some("pdf".into()),
+ kind: "FILE".into(),
+ size: Some(1),
+ child_count: None,
+ created_at: None,
+ modified_at: None,
+ etag: None,
+ }],
+ )
+ .unwrap();
+ lib.set_state("contacts.me", "C1").unwrap();
+ lib.set_state("settings.alerts.events", "1").unwrap();
+ lib.set_state("drive_folder_on", "1").unwrap();
+ lib.mark_synced("drive", Some("token")).unwrap();
+ assert!(lib.holds_account().unwrap());
+ assert_eq!(
+ lib.computer_state().unwrap().len(),
+ 2,
+ "the settings and the folder, nothing of the account's"
+ );
+ lib.forget_account().unwrap();
+ assert!(!lib.holds_account().unwrap(), "nothing left to set aside");
+ assert!(
+ lib.drive_children("root").unwrap().is_empty(),
+ "the files gone"
+ );
+ assert_eq!(
+ lib.state("contacts.me").unwrap(),
+ None,
+ "the account's own facts gone"
+ );
+ assert_eq!(
+ lib.sync_token("drive").unwrap(),
+ None,
+ "and where its sync had got to"
+ );
+ assert_eq!(
+ lib.state("settings.alerts.events").unwrap().as_deref(),
+ Some("1"),
+ "this computer's settings kept"
+ );
+ assert_eq!(lib.state("drive_folder_on").unwrap().as_deref(), Some("1"));
+ }
+
#[test]
fn a_new_library_is_migrated_to_the_latest_schema() {
let library = Library::in_memory().unwrap();
diff --git a/crates/quince-core/src/outbox.rs b/crates/quince-core/src/outbox.rs
index 7d4a946..ff4adbf 100644
--- a/crates/quince-core/src/outbox.rs
+++ b/crates/quince-core/src/outbox.rs
@@ -62,6 +62,14 @@ impl Library {
Ok(rows.collect::<std::result::Result<_, _>>()?)
}
+ /// Every change still waiting, whatever its service.
+ pub fn outbox_count(&self) -> Result<usize> {
+ let n: i64 = self
+ .conn
+ .query_row("SELECT count(*) FROM outbox", [], |r| r.get(0))?;
+ Ok(usize::try_from(n).unwrap_or(0))
+ }
+
/// Apple has it (or has refused it for good): no longer waiting.
pub fn outbox_done(&mut self, id: i64) -> Result<()> {
self.conn
diff --git a/crates/quince-media/src/lib.rs b/crates/quince-media/src/lib.rs
index e8f2e70..c3fe801 100644
--- a/crates/quince-media/src/lib.rs
+++ b/crates/quince-media/src/lib.rs
@@ -364,6 +364,21 @@ pub fn thumbnail_mtime(png_bytes: &[u8]) -> Option<i64> {
.and_then(|t| t.text.trim().parse().ok())
}
+/// Whether a freedesktop thumbnail was written by Quince (its `Software` chunk): the ones to
+/// remove with an account, and only those — every other app's stay.
+#[must_use]
+pub fn thumbnail_is_ours(png_bytes: &[u8]) -> bool {
+ let decoder = png::Decoder::new(std::io::Cursor::new(png_bytes));
+ let Ok(reader) = decoder.read_info() else {
+ return false;
+ };
+ reader
+ .info()
+ .uncompressed_latin1_text
+ .iter()
+ .any(|t| t.keyword == "Software" && t.text == "Quince")
+}
+
/// Whether bytes are a HEIF file (HEIC and its kin): an `ftyp` box naming a HEIF brand.
#[must_use]
pub fn is_heif(bytes: &[u8]) -> bool {
@@ -498,6 +513,22 @@ mod tests {
}
use super::*;
+
+ /// Only Quince's own thumbnails are told apart as ours: another app's are never touched.
+ #[test]
+ fn our_thumbnails_are_known_by_their_software_chunk() {
+ let mut plain = Vec::new();
+ image::DynamicImage::new_rgb8(4, 4)
+ .write_to(
+ &mut std::io::Cursor::new(&mut plain),
+ image::ImageFormat::Png,
+ )
+ .unwrap();
+ let ours = freedesktop_thumbnail(&plain, 128, "file:///home/test/a.png", 1).unwrap();
+ assert!(thumbnail_is_ours(&ours));
+ assert!(!thumbnail_is_ours(&plain));
+ assert!(!thumbnail_is_ours(b"not a png"));
+ }
use image::{DynamicImage, GenericImageView, Rgba, RgbaImage};
/// A tall picture with a red square at its top right — where a face sits in a portrait.
diff --git a/crates/quince-vfs/src/fuse.rs b/crates/quince-vfs/src/fuse.rs
index b4a6288..c1a8b21 100644
--- a/crates/quince-vfs/src/fuse.rs
+++ b/crates/quince-vfs/src/fuse.rs
@@ -23,6 +23,12 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH};
/// How long the kernel may keep what it was told about a name or a file. Short, as rclone's
/// is: a file changed on another device must not be read with its old length.
+/// This computer's own disk refusing, told to the app as the disk told it — "No space left on
+/// device" when it is full, never a vague input/output error that reads as a broken drive.
+fn disk(e: std::io::Error) -> Errno {
+ e.raw_os_error().map_or(Errno::EIO, Errno::from_i32)
+}
+
const TTL: Duration = Duration::from_secs(1);
/// How long a folder never opened before may take to come from Apple before the file manager
@@ -406,8 +412,8 @@ impl Inner {
.map_or_else(|| item.display_name(), str::to_string)
};
let staged = writes.staging(ino, &name);
- std::fs::create_dir_all(staged.parent().ok_or(Errno::EIO)?).map_err(|_| Errno::EIO)?;
- let file = std::fs::File::create(&staged).map_err(|_| Errno::EIO)?;
+ std::fs::create_dir_all(staged.parent().ok_or(Errno::EIO)?).map_err(disk)?;
+ let file = std::fs::File::create(&staged).map_err(disk)?;
if keep {
let size = u64::try_from(item.size.unwrap_or(0)).unwrap_or(0);
let (cache, remote, it) = (
@@ -423,7 +429,7 @@ impl Inner {
.rt
.block_on(async move { c.read(r.as_ref(), &i, at, len).await })
.map_err(|_| Errno::EIO)?;
- file.write_all_at(&bytes, at).map_err(|_| Errno::EIO)?;
+ file.write_all_at(&bytes, at).map_err(disk)?;
at += len;
}
}
@@ -1025,12 +1031,10 @@ impl Filesystem for DriveFs {
let staged = writes.staging(ino, name);
let made = staged
.parent()
- .map(std::fs::create_dir_all)
- .transpose()
- .is_ok()
- && std::fs::File::create(&staged).is_ok();
- if !made {
- return reply.error(Errno::EIO);
+ .map_or(Ok(()), std::fs::create_dir_all)
+ .and_then(|()| std::fs::File::create(&staged));
+ if let Err(e) = made {
+ return reply.error(disk(e));
}
writes
.items
@@ -1146,8 +1150,8 @@ impl Filesystem for DriveFs {
.write(true)
.open(w.staging(ino.0, &p.name))
.and_then(|f| f.write_all_at(data, offset));
- if written.is_err() {
- return reply.error(Errno::EIO);
+ if let Err(e) = written {
+ return reply.error(disk(e));
}
inner.with_pending(ino.0, |p| {
p.dirty = true;
diff --git a/probe/examples/drive_mount_live.rs b/probe/examples/drive_mount_live.rs
index 9839a01..f40af5e 100644
--- a/probe/examples/drive_mount_live.rs
+++ b/probe/examples/drive_mount_live.rs
@@ -194,6 +194,10 @@ fn main() -> Result<()> {
std::thread::sleep(std::time::Duration::from_secs(secs));
drop(session);
let _ = std::fs::remove_dir_all(&cache);
+ // Its journal left behind only when something is still waiting.
+ if std::fs::read(writes_dir.join("pending.json")).is_ok_and(|b| b == b"[]") {
+ let _ = std::fs::remove_dir_all(&writes_dir);
+ }
println!("unmounted");
// This probe's own throwaways, and nothing else, cleared from Recently Deleted.
if std::env::var("QUINCE_PURGE_TEST").is_ok() {
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 17545ab..fd514d3 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -14,6 +14,7 @@ futures-util = { version = "0.3", default-features = false, features = ["std"] }
# already needs, so nothing new is installed.
gstreamer = "0.25"
quince-vfs = { path = "../crates/quince-vfs" }
+sha2 = "0.10"
gstreamer-app = "0.25"
gstreamer-video = "0.25"
tauri = { version = "2", features = ["tray-icon", "image-png"] }
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 69b3b1f..0be2b4c 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -446,8 +446,22 @@ async fn auth_status(auth: State<'_, Auth>) -> UiResult<Status> {
/// Try the stored session. `false` just means a sign-in is needed — not an error.
#[tauri::command]
-async fn auth_resume(auth: State<'_, Auth>) -> UiResult<&'static str> {
- let mut client = auth.client.lock().await;
+async fn auth_resume(app: tauri::AppHandle, auth: State<'_, Auth>) -> UiResult<&'static str> {
+ let outcome = {
+ let mut client = auth.client.lock().await;
+ let outcome = resume_session(&mut client).await?;
+ if outcome == "library" {
+ signed_in(&app, &mut client).await?;
+ }
+ outcome
+ };
+ if outcome == "library" {
+ folders_up(&app).await;
+ }
+ Ok(outcome)
+}
+
+async fn resume_session(client: &mut Client) -> UiResult<&'static str> {
let resumed = match client.resume().await {
Ok(resumed) => resumed,
// Offline with a session kept: the library opens on what it holds, as a local-first
@@ -467,6 +481,13 @@ async fn auth_resume(auth: State<'_, Auth>) -> UiResult<&'static str> {
})
}
+/// The folders on this computer brought up, once the library is the signed-in account's: they
+/// are served by the session, so they are never up without one.
+async fn folders_up(app: &tauri::AppHandle) {
+ let app = app.clone();
+ let _ = tauri::async_runtime::spawn_blocking(move || mount::resume(&app)).await;
+}
+
/// Emitted when a lapsed session signed itself back in only as far as Apple's code.
const NEEDS_CODE: &str = "quince://needs-code";
@@ -485,10 +506,163 @@ async fn keep_signed_in(app: &tauri::AppHandle, client: &Arc<Mutex<Client>>) {
}
}
+/// Whose data the library holds: a hash of Apple's account id, never the id itself.
+pub const ACCOUNT_KEY: &str = "account";
+
+/// What of an account lives in the data folder beside the session: its library, and every
+/// cache and queue made from it. Moved as one when another account signs in.
+const ACCOUNT_FILES: [&str; 11] = [
+ "library.db",
+ "library.db-wal",
+ "library.db-shm",
+ "photos",
+ "photos-folder-cache",
+ "drive-cache",
+ "drive-writes",
+ "thumbnails",
+ "note-files",
+ "note-media",
+ "faces",
+];
+
+/// Where the accounts not signed in are kept, each under its own tag.
+const SET_ASIDE: &str = "accounts";
+
+/// An account as the library names it.
+pub fn account_tag(dsid: &str) -> String {
+ use sha2::Digest;
+ format!(
+ "{:x}",
+ sha2::Sha256::digest(format!("quince-account:{dsid}"))
+ )
+}
+
+/// The library made the signed-in account's, before anything else can use the session: called
+/// with the auth lock still held, so no sync, send or upload ever sees one account's session
+/// beside another's library.
+///
+/// Someone else's library here — a sign-out kept a copy, then another Apple ID signed in — is
+/// set aside whole under `accounts/`, never deleted and never mixed, and this account's own,
+/// if it was set aside before, comes back where it was: its records, its caches, what it had
+/// still to send. A library from before accounts were told apart is simply claimed.
+async fn claim_library(app: &tauri::AppHandle, client: &Client) -> Result<(), String> {
+ let Some(dsid) = client.session().dsid.as_deref() else {
+ return Ok(());
+ };
+ let tag = account_tag(dsid);
+ let data = app.state::<Data>();
+ let mut library = data.0.lock().await;
+ let known = library.state(ACCOUNT_KEY).map_err(|e| e.to_string())?;
+ if known.as_deref() == Some(tag.as_str()) {
+ return Ok(());
+ }
+ let dir = state_dir(app);
+ let home = dir.join(SET_ASIDE).join(&tag);
+ if known.is_some() || home.exists() {
+ let now = jiff::Timestamp::now().as_second();
+ let away = known.unwrap_or_else(|| format!("unclaimed-{now}"));
+ switch_library(&mut library, &dir, &away, &home)?;
+ photos::forget_links();
+ }
+ library
+ .set_state(ACCOUNT_KEY, &tag)
+ .map_err(|e| e.to_string())
+}
+
+/// One account's library and caches set aside under `away`, and the ones at `home` (if any)
+/// brought back in their place. The library is let go of while its files move and opened
+/// again after, whatever happened; this computer's settings stay with the computer.
+fn switch_library(
+ library: &mut Library,
+ dir: &std::path::Path,
+ away: &str,
+ home: &std::path::Path,
+) -> Result<(), String> {
+ let kept = library.computer_state().map_err(|e| e.to_string())?;
+ let empty = !library.holds_account().map_err(|e| e.to_string())?;
+ let shelf = dir.join(SET_ASIDE).join(away);
+ *library = Library::in_memory().map_err(|e| e.to_string())?;
+ let moved = move_account(dir, &shelf).and_then(|()| {
+ if home.exists() {
+ move_account(home, dir)?;
+ std::fs::remove_dir(home)?;
+ }
+ Ok(())
+ });
+ *library = Library::open(dir).map_err(|e| e.to_string())?;
+ for (key, value) in kept {
+ library.set_state(&key, &value).map_err(|e| e.to_string())?;
+ }
+ moved.map_err(|e| format!("The last account's data could not be set aside: {e}"))?;
+ // A library that held nothing — one emptied by a sign-out that kept nothing — is not kept.
+ if empty && away.starts_with("unclaimed-") {
+ let _ = std::fs::remove_dir_all(&shelf);
+ }
+ Ok(())
+}
+
+/// An account's files moved from one folder to another, all or none: whatever had moved goes
+/// back if one cannot, and nothing is moved over something already there.
+fn move_account(from: &std::path::Path, to: &std::path::Path) -> std::io::Result<()> {
+ std::fs::create_dir_all(to)?;
+ if let Some(taken) = ACCOUNT_FILES.iter().find(|n| to.join(n).exists()) {
+ return Err(std::io::Error::other(format!("{taken} is already there")));
+ }
+ let mut done = Vec::new();
+ for name in ACCOUNT_FILES {
+ if !from.join(name).exists() {
+ continue;
+ }
+ if let Err(e) = std::fs::rename(from.join(name), to.join(name)) {
+ for back in done {
+ let _ = std::fs::rename(to.join(back), from.join(back));
+ }
+ return Err(e);
+ }
+ done.push(name);
+ }
+ Ok(())
+}
+
+/// Whether the session and the library are the same account's — asked by everything that sends
+/// what the library holds to Apple, so that nothing of one account is ever sent with another's
+/// session (a switch that failed half-way, a session left from a crash).
+pub async fn same_account(app: &tauri::AppHandle) -> bool {
+ let session = app
+ .state::<Auth>()
+ .client
+ .lock()
+ .await
+ .session()
+ .dsid
+ .as_deref()
+ .map(account_tag);
+ let owner = app
+ .state::<Data>()
+ .0
+ .lock()
+ .await
+ .state(ACCOUNT_KEY)
+ .ok()
+ .flatten();
+ session.is_some() && session == owner
+}
+
+/// Signed in, then the library made this account's; if it could not be, signed out again with
+/// the reason, never left signed in over someone else's data.
+async fn signed_in(app: &tauri::AppHandle, client: &mut Client) -> Result<(), String> {
+ if let Err(e) = claim_library(app, client).await {
+ let _ = client.sign_out();
+ return Err(e);
+ }
+ Ok(())
+}
+
#[tauri::command]
async fn auth_sign_in(
apple_id: String,
password: String,
+ app: tauri::AppHandle,
auth: State<'_, Auth>,
) -> UiResult<&'static str> {
// Reject rather than queue. A second attempt would mean a second code sent to the
@@ -500,19 +674,32 @@ async fn auth_sign_in(
let mut client = auth.client.lock().await;
match client.sign_in(&apple_id, &password).await {
- Ok(SignInOutcome::Complete) => Ok("complete"),
+ Ok(SignInOutcome::Complete) => {
+ signed_in(&app, &mut client).await?;
+ drop(client);
+ folders_up(&app).await;
+ Ok("complete")
+ }
Ok(SignInOutcome::NeedsTwoFactor) => Ok("needs_two_factor"),
Err(e) => Err(e.to_string()),
}
}
#[tauri::command]
-async fn auth_submit_code(code: String, auth: State<'_, Auth>) -> UiResult<()> {
+async fn auth_submit_code(
+ code: String,
+ app: tauri::AppHandle,
+ auth: State<'_, Auth>,
+) -> UiResult<()> {
let mut client = auth.client.lock().await;
client
.submit_two_factor(&code)
.await
- .map_err(|e| e.to_string())
+ .map_err(|e| e.to_string())?;
+ signed_in(&app, &mut client).await?;
+ drop(client);
+ folders_up(&app).await;
+ Ok(())
}
/// Where Apple can send a code, and whether it already pushed one.
@@ -536,20 +723,88 @@ async fn auth_send_sms(phone_id: u64, auth: State<'_, Auth>) -> UiResult<()> {
}
#[tauri::command]
-async fn auth_submit_sms_code(phone_id: u64, code: String, auth: State<'_, Auth>) -> UiResult<()> {
+async fn auth_submit_sms_code(
+ phone_id: u64,
+ code: String,
+ app: tauri::AppHandle,
+ auth: State<'_, Auth>,
+) -> UiResult<()> {
let mut client = auth.client.lock().await;
client
.submit_sms_code(phone_id, &code)
.await
- .map_err(|e| e.to_string())
+ .map_err(|e| e.to_string())?;
+ signed_in(&app, &mut client).await?;
+ drop(client);
+ folders_up(&app).await;
+ Ok(())
}
+/// What of the signed-in account's has not reached Apple yet: asked before a sign-out, so a
+/// choice to keep nothing on this computer is made knowing what it loses.
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct Unsent {
+ /// Changes queued for Apple (a reminder ticked offline, say).
+ changes: usize,
+ /// Files written in the iCloud Drive folder and not yet uploaded.
+ files: usize,
+ /// Photos added and not yet uploaded.
+ photos: usize,
+}
+
+#[tauri::command]
+async fn account_unsent(app: tauri::AppHandle, data: State<'_, Data>) -> UiResult<Unsent> {
+ let (changes, photos) = {
+ let library = data.0.lock().await;
+ (
+ library.outbox_count().map_err(|e| e.to_string())?,
+ library
+ .unfinished_uploads()
+ .map_err(|e| e.to_string())?
+ .len(),
+ )
+ };
+ Ok(Unsent {
+ changes,
+ photos,
+ files: mount::unsent_files(&state_dir(&app)),
+ })
+}
+
+/// Signed out, keeping a copy of the account here or not, as the person chose.
+///
+/// Kept, everything stays as it was — the library, its caches, what waits to be sent — and is
+/// there again when the account signs back in; another account signing in first finds it set
+/// aside, not mixed in (see `claim_library`). Not kept, every record and cached file of the
+/// account is removed from this computer. Either way nothing is deleted from iCloud.
#[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();
+async fn auth_sign_out(keep: bool, app: tauri::AppHandle, auth: State<'_, Auth>) -> UiResult<()> {
+ // The folders go with the session they were served by — before the auth lock is taken,
+ // since what they are still answering may be waiting on it.
+ tauri::async_runtime::spawn_blocking(mount::release)
+ .await
+ .map_err(|e| e.to_string())?;
let mut client = auth.client.lock().await;
- client.sign_out().map_err(|e| e.to_string())
+ client.sign_out().map_err(|e| e.to_string())?;
+ if !keep {
+ let data = app.state::<Data>();
+ let mut library = data.0.lock().await;
+ library.forget_account().map_err(|e| e.to_string())?;
+ let dir = state_dir(&app);
+ for name in ACCOUNT_FILES
+ .iter()
+ .filter(|n| !n.starts_with("library.db"))
+ {
+ let _ = std::fs::remove_dir_all(dir.join(name));
+ }
+ photos::forget_links();
+ drop(library);
+ drop(client);
+ let app = app.clone();
+ let _ = tauri::async_runtime::spawn_blocking(move || mount::forget_thumbnails(&app)).await;
+ }
+ Ok(())
}
/// Services Apple advertises for this account, for the sidebar.
@@ -3840,7 +4095,10 @@ fn main() {
let mut library = Library::open(&dir)?;
adopt_writer(&mut library);
app.manage(Data(Mutex::new(library)));
- mount::resume(app.handle());
+ // A photo cache past what this computer can spare now — the disk filled since —
+ // is brought back under its budget first thing.
+ let trim = app.handle().clone();
+ tauri::async_runtime::spawn_blocking(move || photos::trim_cache(&trim));
// 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
@@ -3906,6 +4164,7 @@ fn main() {
auth_send_sms,
auth_submit_sms_code,
auth_sign_out,
+ account_unsent,
account_services,
account_info,
settings_get,
@@ -4041,6 +4300,79 @@ fn main() {
#[cfg(test)]
mod tests {
+
+ /// Two Apple IDs on one computer: each one's library and caches set aside whole while the
+ /// other is signed in, and back exactly as they were — never mixed, never deleted — with
+ /// this computer's settings staying put through both switches.
+ #[test]
+ fn accounts_are_set_aside_and_brought_back_whole() {
+ let dir = tempfile::tempdir().unwrap();
+ let dir = dir.path();
+ let mut lib = Library::open(dir).unwrap();
+ lib.set_state(ACCOUNT_KEY, "a").unwrap();
+ lib.set_state("contacts.me", "A's card").unwrap();
+ lib.set_state("settings.alerts.events", "0").unwrap();
+ std::fs::create_dir_all(dir.join("photos")).unwrap();
+ std::fs::write(dir.join("photos").join("one"), b"A's photo").unwrap();
+
+ // B signs in: A goes aside, B starts clean.
+ switch_library(&mut lib, dir, "a", &dir.join(SET_ASIDE).join("b")).unwrap();
+ assert_eq!(
+ lib.state("contacts.me").unwrap(),
+ None,
+ "nothing of A's in B's library"
+ );
+ assert!(
+ !dir.join("photos").join("one").exists(),
+ "nor in its caches"
+ );
+ assert_eq!(
+ lib.state("settings.alerts.events").unwrap().as_deref(),
+ Some("0")
+ );
+ assert!(dir.join(SET_ASIDE).join("a").join("library.db").exists());
+ lib.set_state(ACCOUNT_KEY, "b").unwrap();
+ lib.set_state("contacts.me", "B's card").unwrap();
+ lib.set_state("settings.alerts.events", "1").unwrap();
+
+ // A again: B aside, A back as it was.
+ switch_library(&mut lib, dir, "b", &dir.join(SET_ASIDE).join("a")).unwrap();
+ assert_eq!(lib.state(ACCOUNT_KEY).unwrap().as_deref(), Some("a"));
+ assert_eq!(
+ lib.state("contacts.me").unwrap().as_deref(),
+ Some("A's card")
+ );
+ assert_eq!(
+ std::fs::read(dir.join("photos").join("one")).unwrap(),
+ b"A's photo"
+ );
+ assert_eq!(
+ lib.state("settings.alerts.events").unwrap().as_deref(),
+ Some("1"),
+ "the computer's latest setting, not the one A left"
+ );
+ assert!(
+ !dir.join(SET_ASIDE).join("a").exists(),
+ "its shelf put away"
+ );
+ assert!(dir.join(SET_ASIDE).join("b").join("library.db").exists());
+ }
+
+ /// A move that cannot finish undoes itself, and never lands over what is already there.
+ #[test]
+ fn a_move_is_all_or_nothing() {
+ let dir = tempfile::tempdir().unwrap();
+ let (from, to) = (dir.path().join("from"), dir.path().join("to"));
+ std::fs::create_dir_all(from.join("photos")).unwrap();
+ std::fs::create_dir_all(to.join("faces")).unwrap();
+ std::fs::write(from.join("library.db"), b"mine").unwrap();
+ assert!(move_account(&from, &to).is_err(), "something already there");
+ assert!(
+ from.join("library.db").exists() && from.join("photos").exists(),
+ "nothing moved"
+ );
+ }
+
use super::*;
/// Apple serves contact pictures as PNG, which is not what the first version of this
diff --git a/src-tauri/src/mount.rs b/src-tauri/src/mount.rs
index d64b43f..be42bdd 100644
--- a/src-tauri/src/mount.rs
+++ b/src-tauri/src/mount.rs
@@ -103,6 +103,21 @@ impl Remote for AppRemote {
Box::pin(async move {
let (http, docws, params) = context(&app, "docws").await?;
let drivews = context(&app, "drivews").await?.1;
+ // iCloud with no room for it: said as that, and tried again as the folder retries,
+ // so it goes up once space is freed — never an opaque refusal from Apple.
+ let len = tokio::fs::metadata(&path).await.map_or(0, |m| m.len());
+ let setup = app
+ .state::<Auth>()
+ .client
+ .lock()
+ .await
+ .setup_url()
+ .to_string();
+ if let Ok(s) = quince_icloud::drive::storage(&http, &setup, params.clone()).await {
+ if s.total_bytes > 0 && s.used_bytes.saturating_add(len) > s.total_bytes {
+ return Err("Your iCloud storage is full. It uploads when there's room.".into());
+ }
+ }
let progress: quince_icloud::drive::Progress = Arc::new(|_, _| {});
quince_icloud::drive::upload(&http, &docws, &drivews, params, &folder, &path, progress)
.await
@@ -279,9 +294,10 @@ fn mounted(which: Which) -> Option<PathBuf> {
.map(|(_, p, _)| p.clone())
}
-/// The most the Drive folder's downloads may keep on this computer: 10 GB, or a fifth of the
-/// disk's free space when that is less — a full disk is never the price of a folder.
-fn budget(dir: &std::path::Path) -> u64 {
+/// The most a cache may keep on this computer — the Drive folder's downloads, Photos' pictures:
+/// 10 GB, or a fifth of the disk's free space when that is less — a full disk is never the price
+/// of a cache.
+pub(crate) fn budget(dir: &std::path::Path) -> u64 {
const MOST: u64 = 10 * 1024 * 1024 * 1024;
#[cfg(unix)]
{
@@ -448,6 +464,49 @@ pub fn resume(app: &AppHandle) {
}
}
+/// Files written in the iCloud Drive folder and not yet sent: from the folder while it is up,
+/// from what it wrote down when it went away while it is not.
+pub fn unsent_files(data_dir: &std::path::Path) -> usize {
+ if let Some(w) = WRITES
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .as_ref()
+ {
+ return w.waiting().files as usize;
+ }
+ let dir = data_dir.join("drive-writes");
+ if !dir.exists() {
+ return 0;
+ }
+ quince_vfs::writes::Writes::new(&dir)
+ .map(|w| {
+ w.load()
+ .iter()
+ .filter(|(_, p)| !quince_vfs::writes::stays_local(&p.name))
+ .count()
+ })
+ .unwrap_or(0)
+}
+
+/// Every thumbnail the folders left where file managers look for them, removed — with the
+/// account they pictured, on a sign-out that keeps nothing. Only Quince's own; no other app's.
+pub fn forget_thumbnails(app: &AppHandle) {
+ let Some(root) = thumbnail_cache(app) else {
+ return;
+ };
+ for size in ["normal", "large", "x-large", "xx-large"] {
+ for f in std::fs::read_dir(root.join(size))
+ .into_iter()
+ .flatten()
+ .flatten()
+ {
+ if std::fs::read(f.path()).is_ok_and(|b| quince_media::thumbnail_is_ours(&b)) {
+ let _ = std::fs::remove_file(f.path());
+ }
+ }
+ }
+}
+
/// When signing out or quitting: both folders go with the session.
pub fn release() {
stop(Which::Drive);
diff --git a/src-tauri/src/outbox.rs b/src-tauri/src/outbox.rs
index a3b89fb..ff7589f 100644
--- a/src-tauri/src/outbox.rs
+++ b/src-tauri/src/outbox.rs
@@ -82,7 +82,12 @@ struct Refused {
async fn drain_reminders(app: &AppHandle) -> Outcome {
let auth = app.state::<Auth>();
let data = app.state::<Data>();
- let Ok((http, root, params)) = cloudkit_context(&auth).await else {
+ let session = if crate::same_account(app).await {
+ cloudkit_context(&auth).await
+ } else {
+ Err(String::new())
+ };
+ let Ok((http, root, params)) = session else {
// Not signed in, or the session is being renewed: nothing can go yet.
return if data
.0
diff --git a/src-tauri/src/photos.rs b/src-tauri/src/photos.rs
index 412ea02..f53e9be 100644
--- a/src-tauri/src/photos.rs
+++ b/src-tauri/src/photos.rs
@@ -20,6 +20,13 @@ const LINK_LIFE: Duration = Duration::from_secs(45 * 60);
/// Every master's links seen this run, and when.
static LINKS: Mutex<Option<HashMap<String, (Links, Instant)>>> = Mutex::new(None);
+/// Every link let go of: they were the last account's.
+pub fn forget_links() {
+ *LINKS
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) = None;
+}
+
/// Links a pass brought, kept for the pictures it will be asked for.
pub fn remember(links: HashMap<String, Links>) {
let now = Instant::now();
@@ -251,6 +258,15 @@ pub async fn picture(app: &AppHandle, id: &str, size: Size) -> Result<Vec<u8>, S
pub async fn cached(app: &AppHandle, id: &str, size: Size) -> Result<PathBuf, String> {
let path = cache_path(app, id, size);
if tokio::fs::metadata(&path).await.is_ok() {
+ // Seen now: the last to go when the cache is trimmed (see `trim_cache`).
+ if size != Size::Thumb {
+ let touched = path.clone();
+ tokio::task::spawn_blocking(move || {
+ if let Ok(f) = std::fs::File::open(&touched) {
+ let _ = f.set_modified(std::time::SystemTime::now());
+ }
+ });
+ }
return Ok(path);
}
if size == Size::Full && is_heic(app, id).await {
@@ -412,6 +428,68 @@ pub async fn repair_poster(app: &AppHandle, id: &str) -> bool {
true
}
+/// Every picture the cache holds that can go — all but the grid's thumbnails, which every view
+/// draws from and which are small — with its size and when it was last seen.
+fn trimmable(root: &std::path::Path) -> Vec<(PathBuf, u64, std::time::SystemTime)> {
+ let mut out = Vec::new();
+ let Ok(sizes) = std::fs::read_dir(root) else {
+ return out;
+ };
+ for dir in sizes.flatten() {
+ if dir.file_name() == Size::Thumb.name() || !dir.path().is_dir() {
+ continue;
+ }
+ for f in std::fs::read_dir(dir.path())
+ .into_iter()
+ .flatten()
+ .flatten()
+ {
+ if let Ok(m) = f.metadata() {
+ // A download still being written is never cut from under it.
+ if m.is_file() && f.path().extension().is_none_or(|e| e != "part") {
+ let seen = m.modified().unwrap_or(std::time::UNIX_EPOCH);
+ out.push((f.path(), m.len(), seen));
+ }
+ }
+ }
+ }
+ out
+}
+
+/// The photo cache held to its budget (`mount::budget`: 10 GB, or a fifth of the free space when
+/// less), as Photos on a Mac with "Optimize Storage" keeps what was looked at last and lets the
+/// rest go: the longest unseen go first, down to four fifths of it, so a trim is not needed again
+/// at once. A picture seen in the last five minutes stays — it is on screen. Thumbnails always
+/// stay. Answers the room left under the budget.
+pub fn trim_cache(app: &AppHandle) -> u64 {
+ let root = crate::state_dir(app).join("photos");
+ if std::fs::create_dir_all(&root).is_err() {
+ return 0;
+ }
+ trim(&root, crate::mount::budget(&root))
+}
+
+fn trim(root: &std::path::Path, budget: u64) -> u64 {
+ let mut files = trimmable(root);
+ let mut used: u64 = files.iter().map(|(_, len, _)| len).sum();
+ if used > budget {
+ files.sort_by_key(|(_, _, seen)| *seen);
+ let recent = std::time::SystemTime::now() - Duration::from_secs(5 * 60);
+ for (path, len, seen) in files {
+ if used <= budget / 5 * 4 {
+ break;
+ }
+ if seen > recent {
+ continue;
+ }
+ if std::fs::remove_file(&path).is_ok() {
+ used -= len;
+ }
+ }
+ }
+ budget.saturating_sub(used)
+}
+
/// Keeps the newest photos' whole pictures, and videos, on disk ahead of being opened — as
/// Photos on a Mac keeps originals — so a photo opens at full quality and a video plays at once,
/// never waiting on the network. Newest first, two at a time, at most 600 and 3 GB a pass, after
@@ -452,7 +530,15 @@ pub fn keep_ahead(app: AppHandle) {
})
.filter(|(id, size)| !cache_path(&app, id, *size).exists())
.collect();
- let budget = std::sync::atomic::AtomicU64::new(3 * 1024 * 1024 * 1024);
+ // At most 3 GB a pass, and never past the cache's budget: a computer short of space
+ // keeps fewer ahead, not a full disk.
+ let room = {
+ let app = app.clone();
+ tauri::async_runtime::spawn_blocking(move || trim_cache(&app))
+ .await
+ .unwrap_or(0)
+ };
+ let budget = std::sync::atomic::AtomicU64::new(room.min(3 * 1024 * 1024 * 1024));
futures_util::stream::iter(wanted)
.for_each_concurrent(2, |(id, size)| {
let (app, budget) = (app.clone(), &budget);
@@ -471,6 +557,8 @@ pub fn keep_ahead(app: AppHandle) {
}
})
.await;
+ let trim = app.clone();
+ let _ = tauri::async_runtime::spawn_blocking(move || trim_cache(&trim)).await;
RUNNING.store(false, std::sync::atomic::Ordering::SeqCst);
});
}
@@ -1767,6 +1855,10 @@ async fn one(app: &AppHandle, u: quince_core::photos::Upload) -> bool {
say(app, &u, "cancelled", 0, 0, None);
return true;
}
+ // Never sent with a session that is not the library's own account's.
+ if !crate::same_account(app).await {
+ return false;
+ }
let auth = app.state::<Auth>();
let (http, ck, params, upload_root) = {
let client = auth.client.lock().await;
@@ -2026,6 +2118,38 @@ async fn refresh_photos(app: &AppHandle) {
#[cfg(test)]
mod tests {
+
+ /// Over its budget, the cache lets the longest-unseen pictures go first, down to four
+ /// fifths; thumbnails and what was seen in the last minutes stay.
+ #[test]
+ fn the_cache_keeps_to_its_budget_longest_unseen_first() {
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path();
+ let put = |size: &str, name: &str, ago: u64| {
+ std::fs::create_dir_all(root.join(size)).unwrap();
+ let p = root.join(size).join(name);
+ std::fs::write(&p, vec![0u8; 100]).unwrap();
+ let f = std::fs::File::options().write(true).open(&p).unwrap();
+ f.set_modified(std::time::SystemTime::now() - Duration::from_secs(ago))
+ .unwrap();
+ };
+ put("thumb", "t", 99_999);
+ put("original", "oldest", 9_000);
+ put("full", "older", 8_000);
+ put("full", "old", 7_000);
+ put("original", "now", 10);
+ // 400 bytes held against 300: down to 240 — the two longest unseen go.
+ let room = trim(root, 300);
+ assert!(!root.join("original/oldest").exists() && !root.join("full/older").exists());
+ assert!(root.join("full/old").exists(), "no more than needed");
+ assert!(
+ root.join("original/now").exists(),
+ "what is on screen stays"
+ );
+ assert!(root.join("thumb/t").exists(), "thumbnails always stay");
+ assert_eq!(room, 100);
+ }
+
use super::*;
#[test]
diff --git a/src-tauri/src/refresh.rs b/src-tauri/src/refresh.rs
index 90333fb..71fc121 100644
--- a/src-tauri/src/refresh.rs
+++ b/src-tauri/src/refresh.rs
@@ -104,6 +104,9 @@ struct Context {
contacts: Option<String>,
cloudkit: Option<String>,
drive: Option<String>,
+ /// The account it is all for (`account_tag`): nothing it brings is kept in a library that
+ /// is not that account's.
+ account: Option<String>,
}
async fn context(client: &Arc<Mutex<Client>>) -> Context {
@@ -116,6 +119,7 @@ async fn context(client: &Arc<Mutex<Client>>) -> Context {
contacts: session.service_url("contacts"),
cloudkit: session.service_url("ckdatabasews"),
drive: session.service_url("drivews"),
+ account: session.dsid.as_deref().map(crate::account_tag),
}
}
@@ -160,6 +164,7 @@ async fn run(client: &Arc<Mutex<Client>>, data: &Mutex<Library>, services: &[&st
"calendar",
"Calendar",
data,
+ ctx.account.as_deref(),
fetched,
|library, snapshot| {
let summary = quince_icloud::sync::apply_calendar(library, snapshot)?;
@@ -195,6 +200,7 @@ async fn run(client: &Arc<Mutex<Client>>, data: &Mutex<Library>, services: &[&st
"reminders",
"Reminders",
data,
+ ctx.account.as_deref(),
fetched,
move |library, f| {
let (lists, count, _) =
@@ -230,17 +236,24 @@ async fn run(client: &Arc<Mutex<Client>>, data: &Mutex<Library>, services: &[&st
since.as_deref(),
)
.await;
- store("notes", "Notes", data, fetched, move |library, f| {
- let (folders, notes, _) = quince_icloud::notes::apply_cloudkit(library, f)?;
- if full {
- library.mark_full_sync("notes")?;
- }
- Ok(format!(
- "{notes} note{} in {folders} folder{}",
- plural(notes),
- plural(folders)
- ))
- })
+ store(
+ "notes",
+ "Notes",
+ data,
+ ctx.account.as_deref(),
+ fetched,
+ move |library, f| {
+ let (folders, notes, _) = quince_icloud::notes::apply_cloudkit(library, f)?;
+ if full {
+ library.mark_full_sync("notes")?;
+ }
+ Ok(format!(
+ "{notes} note{} in {folders} folder{}",
+ plural(notes),
+ plural(folders)
+ ))
+ },
+ )
.await
}
});
@@ -254,10 +267,17 @@ async fn run(client: &Arc<Mutex<Client>>, data: &Mutex<Library>, services: &[&st
let _one = crate::CONTACTS_PASS.lock().await;
let fetched =
quince_icloud::contacts::fetch(&ctx.http, root, ctx.params.clone()).await;
- store("contacts", "Contacts", data, fetched, |library, people| {
- let count = quince_icloud::contacts::apply(library, people)?;
- Ok(format!("{count} contact{}", plural(count)))
- })
+ store(
+ "contacts",
+ "Contacts",
+ data,
+ ctx.account.as_deref(),
+ fetched,
+ |library, people| {
+ let count = quince_icloud::contacts::apply(library, people)?;
+ Ok(format!("{count} contact{}", plural(count)))
+ },
+ )
.await
}
});
@@ -278,14 +298,21 @@ async fn run(client: &Arc<Mutex<Client>>, data: &Mutex<Library>, services: &[&st
quince_core::drive::ROOT,
)
.await;
- store("drive", "iCloud Drive", data, fetched, |library, items| {
- let n = quince_icloud::drive::store_folder(
- library,
- quince_core::drive::ROOT,
- &items,
- )?;
- Ok(format!("{n} item{} at the top of iCloud Drive", plural(n)))
- })
+ store(
+ "drive",
+ "iCloud Drive",
+ data,
+ ctx.account.as_deref(),
+ fetched,
+ |library, items| {
+ let n = quince_icloud::drive::store_folder(
+ library,
+ quince_core::drive::ROOT,
+ &items,
+ )?;
+ Ok(format!("{n} item{} at the top of iCloud Drive", plural(n)))
+ },
+ )
.await
}
});
@@ -306,12 +333,19 @@ async fn run(client: &Arc<Mutex<Client>>, data: &Mutex<Library>, services: &[&st
since.as_deref(),
)
.await;
- store("photos", "Photos", data, fetched, |library, f| {
- let (_, links) = quince_icloud::photos::apply(library, f)?;
- crate::photos::remember(links);
- let n = library.photos(quince_core::photos::View::Library)?.len();
- Ok(format!("{n} photo{}", plural(n)))
- })
+ store(
+ "photos",
+ "Photos",
+ data,
+ ctx.account.as_deref(),
+ fetched,
+ |library, f| {
+ let (_, links) = quince_icloud::photos::apply(library, f)?;
+ crate::photos::remember(links);
+ let n = library.photos(quince_core::photos::View::Library)?.len();
+ Ok(format!("{n} photo{}", plural(n)))
+ },
+ )
.await
}
});
@@ -406,6 +440,7 @@ async fn store<T, F>(
service: &'static str,
label: &'static str,
data: &Mutex<Library>,
+ account: Option<&str>,
fetched: quince_icloud::Result<T>,
apply: F,
) -> ServiceReport
@@ -413,6 +448,18 @@ where
F: FnOnce(&mut Library, T) -> quince_icloud::Result<String>,
{
let mut library = data.lock().await;
+ // Fetched for an account that is no longer the library's — signed out, or another signed
+ // in, while it was on the way: dropped, never laid over someone else's data.
+ let owner = library.state(crate::ACCOUNT_KEY).ok().flatten();
+ if account.is_none() || owner.as_deref() != account {
+ return ServiceReport {
+ service,
+ label,
+ outcome: Outcome::Failed,
+ detail: Some("Signed out while this was being read.".into()),
+ last_synced_at: None,
+ };
+ }
let result = fetched.and_then(|value| apply(&mut library, value));
match result {
Ok(detail) => ServiceReport {
diff --git a/src/App.tsx b/src/App.tsx
index 1636b9d..58ca871 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -57,9 +57,11 @@ export default function App() {
};
}, []);
- async function signOut() {
- await api.signOut().catch(() => {});
- setPhase("signin");
+ // Signed out, the window starts over: nothing of the account is left in its memory either —
+ // no picture, no list, no cached answer — for whoever signs in next.
+ async function signOut(keep: boolean) {
+ await api.signOut(keep);
+ window.location.reload();
}
// Filling the library is the library's own business now: one refresh covers every
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 6c6d98b..3df61e2 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -73,7 +73,9 @@ export const api = {
sendSms: (phoneId: number) => invoke<void>("auth_send_sms", { phoneId }),
submitSmsCode: (phoneId: number, code: string) =>
invoke<void>("auth_submit_sms_code", { phoneId, code }),
- signOut: () => invoke<void>("auth_sign_out"),
+ signOut: (keep: boolean) => invoke<void>("auth_sign_out", { keep }),
+ /** What of the account has not reached iCloud yet: asked before a sign-out. */
+ unsent: () => invoke<{ changes: number; files: number; photos: number }>("account_unsent"),
services: () => invoke<string[]>("account_services"),
eventSave: (draft: EventWrite) => invoke<string>("event_save", { draft }),
diff --git a/src/screens/Library.tsx b/src/screens/Library.tsx
index d0636d6..510f681 100644
--- a/src/screens/Library.tsx
+++ b/src/screens/Library.tsx
@@ -51,7 +51,7 @@ const SCREENS: { key: string; name: string }[] = [
const LAST_KEY = "quince.library.screen";
const RAIL_KEY = "quince.library.rail";
-export function Library({ onSignOut }: { onSignOut: () => void }) {
+export function Library({ onSignOut }: { onSignOut: (keep: boolean) => Promise<void> }) {
const [services, setServices] = useState<string[]>([]);
const [selected, setSelected] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
diff --git a/src/screens/SettingsView.tsx b/src/screens/SettingsView.tsx
index 31133e2..7b5db11 100644
--- a/src/screens/SettingsView.tsx
+++ b/src/screens/SettingsView.tsx
@@ -5,6 +5,7 @@ import { freshness, useSync } from "../lib/sync";
import { setTheme, storedTheme, type Theme } from "../lib/theme";
import { AppIcon } from "../components/AppIcon";
import { AccountAvatar } from "../components/Account";
+import { Portal } from "../components/Portal";
/** The app each service's freshness belongs to, for its icon. */
const ICON: Record<string, string> = {
@@ -37,14 +38,87 @@ function size(bytes: number): string {
* changes something is here — every switch is one the backend obeys, every figure is read
* from Apple or from this computer's library.
*/
-export function SettingsView({ onSignOut }: { onSignOut: () => void }) {
+type Unsent = { changes: number; files: number; photos: number };
+
+/** What has not reached iCloud yet, as a sentence's subject: "2 changes and 1 file". */
+function unsentPhrase(u: Unsent): string | null {
+ const n = (k: number, one: string, many: string) => `${k} ${k === 1 ? one : many}`;
+ const parts = [
+ u.changes > 0 && n(u.changes, "change", "changes"),
+ u.files > 0 && n(u.files, "file", "files"),
+ u.photos > 0 && n(u.photos, "photo", "photos"),
+ ].filter((p): p is string => Boolean(p));
+ if (parts.length === 0) return null;
+ return parts.length === 1 ? parts[0] : `${parts.slice(0, -1).join(", ")} and ${parts[parts.length - 1]}`;
+}
+
+/**
+ * Signing out asks what macOS asks: keep a copy here, or remove it. Kept, everything is here
+ * again on signing back in — and another Apple ID signing in meanwhile finds it set aside, never
+ * mixed with its own. What has not reached iCloud yet is said plainly, since removing loses it.
+ */
+function SignOutSheet({
+ unsent,
+ onCancel,
+ onChoose,
+}: {
+ unsent: Unsent;
+ onCancel: () => void;
+ onChoose: (keep: boolean) => void;
+}) {
+ const waiting = unsentPhrase(unsent);
+ const total = unsent.changes + unsent.files + unsent.photos;
+ return (
+ <Portal>
+ <div className="modal-veil" onClick={onCancel}>
+ <div
+ className="modal-sheet px-ask"
+ role="alertdialog"
+ aria-modal="true"
+ aria-label="Keep a copy of your iCloud data on this computer?"
+ onClick={(e) => e.stopPropagation()}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ e.stopPropagation();
+ onCancel();
+ }
+ }}
+ >
+ <h2>Keep a copy of your iCloud data on this computer?</h2>
+ <p>
+ A copy keeps your notes, photos, files and everything else here, ready when you sign back in. Nothing is
+ deleted from iCloud either way.
+ </p>
+ {waiting && (
+ <p className="signout-unsent">
+ {waiting} {total === 1 ? "hasn't" : "haven't"} reached iCloud yet. Keep a copy and{" "}
+ {total === 1 ? "it goes" : "they go"} up when you sign back in; remove it and{" "}
+ {total === 1 ? "it's" : "they're"} lost.
+ </p>
+ )}
+ <div className="px-ask-actions is-stacked">
+ <button className="is-act" autoFocus onClick={() => onChoose(true)}>
+ Keep a Copy
+ </button>
+ <button className="is-act danger" onClick={() => onChoose(false)}>
+ Remove from This Computer
+ </button>
+ <button onClick={onCancel}>Cancel</button>
+ </div>
+ </div>
+ </div>
+ </Portal>
+ );
+}
+
+export function SettingsView({ onSignOut }: { onSignOut: (keep: boolean) => Promise<void> }) {
const [account, setAccount] = useState<AccountInfo | null>(null);
const [storage, setStorage] = useState<{ usedBytes: number; totalBytes: number } | null>(null);
const [alerts, setAlerts] = useState<{ reminderAlerts: boolean; eventAlerts: boolean } | null>(null);
const [theme, chooseTheme] = useState<Theme>(storedTheme);
const [version, setVersion] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
- const [confirming, setConfirming] = useState(false);
+ const [signingOut, setSigningOut] = useState<Unsent | null>(null);
const [savedReport, setSavedReport] = useState<string | null>(null);
const [folder, setFolder] = useState<DriveFolder | null>(null);
const [folderBusy, setFolderBusy] = useState(false);
@@ -96,19 +170,24 @@ export function SettingsView({ onSignOut }: { onSignOut: () => void }) {
<strong>{account?.name ?? "Your Apple Account"}</strong>
<span>{account?.email ?? ""}</span>
</div>
- {confirming ? (
- <span className="settings-confirm">
- <button className="quiet" onClick={() => setConfirming(false)}>Cancel</button>
- <button className="quiet danger" onClick={onSignOut}>Sign Out</button>
- </span>
- ) : (
- <button className="quiet" onClick={() => setConfirming(true)}>Sign Out</button>
- )}
+ <button
+ className="quiet"
+ onClick={() =>
+ api.unsent().then(setSigningOut, () => setSigningOut({ changes: 0, files: 0, photos: 0 }))
+ }
+ >
+ Sign Out
+ </button>
</section>
- {confirming && (
- <p className="settings-note">
- Signing out removes your iCloud data and sign-in from this computer. Nothing is deleted from iCloud.
- </p>
+ {signingOut && (
+ <SignOutSheet
+ unsent={signingOut}
+ onCancel={() => setSigningOut(null)}
+ onChoose={(keep) => {
+ setSigningOut(null);
+ onSignOut(keep).catch((e) => setError(messageOf(e)));
+ }}
+ />
)}
{account?.dataProtection != null && (
diff --git a/src/styles/photos.css b/src/styles/photos.css
index 1a07c7e..e13d97b 100644
--- a/src/styles/photos.css
+++ b/src/styles/photos.css
@@ -910,6 +910,8 @@
.px-ask-actions button:hover { background: color-mix(in srgb, var(--text) 17%, transparent); }
.px-ask-actions button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.px-ask-actions .is-act { color: var(--accent); }
+.px-ask-actions.is-stacked { grid-template-columns: 1fr; gap: 8px; }
+.px-ask .signout-unsent { color: var(--text); font-weight: 500; }
.px-ask-actions .is-act.danger { color: var(--danger); }
/* ---- a video, as Photos plays one: the film alone, its controls in a capsule floating over