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.

Daily-driving fixes: kept screens, no hover flicker, busy-zone retries, trust

Yashwanth Kamireddi005e9c2dfa4d
diff --git a/.uiverify/calendar-look.mjs b/.uiverify/calendar-look.mjs
index f391b39..5c38d71 100644
--- a/.uiverify/calendar-look.mjs
+++ b/.uiverify/calendar-look.mjs
@@ -2,7 +2,8 @@
// ENGINE=webkit node .uiverify/calendar-look.mjs <out-dir> [width] [height]
import { engine } from "./engine.mjs";
import { SERVICES, installStub } from "./stub.mjs";
-const [out, w = "1920", h = "1040"] = process.argv.slice(2);
+// Never into the repository: with no folder given, the system's temporary one.
+const [out = (await import("node:os")).tmpdir(), w = "1920", h = "1040"] = process.argv.slice(2);
const b = await engine.launch();
const ctx = await b.newContext({ viewport: { width: +w, height: +h }, colorScheme: "dark" });
await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null,
diff --git a/.uiverify/contacts-vcard.mjs b/.uiverify/contacts-vcard.mjs
index 1951ed8..afe5f1d 100644
--- a/.uiverify/contacts-vcard.mjs
+++ b/.uiverify/contacts-vcard.mjs
@@ -41,5 +41,12 @@ await page.waitForTimeout(300);
const paths = await page.evaluate(() => window.__imports?.at(-1)?.paths);
ok(JSON.stringify(paths) === JSON.stringify(["/home/test/people.vcf", "/home/test/google.csv"]), `every chosen file, vCard and CSV, is imported at once ${JSON.stringify(paths)}`);
ok(/2 contacts imported/.test(await page.locator(".drive-saved").innerText()), "and the count is said");
+// Importing an export of the same book: everyone already there is left out, and said so.
+await page.evaluate(() => { window.__importAnswer = [0, 0, 123]; });
+await page.getByRole("button", { name: "More" }).click();
+await page.getByRole("menuitem", { name: "Import Contacts…" }).click();
+await page.waitForTimeout(300);
+const said = await page.locator(".drive-saved").innerText();
+ok(/0 contacts imported, 123 contacts already in Contacts were left out/.test(said), `people already in Contacts are left out, and that is said "${said}"`);
await b.close();
process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/csp.mjs b/.uiverify/csp.mjs
new file mode 100644
index 0000000..ef3bf1b
--- /dev/null
+++ b/.uiverify/csp.mjs
@@ -0,0 +1,48 @@
+// The window's content security policy (tauri.conf.json): Quince's own code and pictures, its
+// local video server and nothing else — no page anywhere on the internet can be loaded into it.
+// Every screen, a photo and a note are visited under that exact policy, and not one load the
+// app makes is refused by it.
+import fs from "node:fs";
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const csp = JSON.parse(fs.readFileSync(new URL("../src-tauri/tauri.conf.json", import.meta.url))).app.security.csp;
+const b = await engine.launch();
+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null,
+ calendarFixture: true, notesFixture: true, contactsFixture: true, driveFixture: true, remindersFixture: true });
+await ctx.addInitScript(() => {
+ window.__refused = [];
+ document.addEventListener("securitypolicyviolation", (e) => window.__refused.push(`${e.violatedDirective} ${e.blockedURI}`));
+});
+const page = await ctx.newPage();
+page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });
+// The policy as Tauri sends it, in the page's own head.
+await page.route("http://localhost:4173/", async (route) => {
+ const res = await route.fetch();
+ const html = (await res.text()).replace("<head>", `<head><meta http-equiv="Content-Security-Policy" content="${csp}">`);
+ await route.fulfill({ response: res, body: html, headers: { ...res.headers(), "content-type": "text/html" } });
+});
+await page.goto("http://localhost:4173/", { waitUntil: "networkidle" });
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+ok(await page.evaluate(() => !!document.querySelector('meta[http-equiv="Content-Security-Policy"]')), "the policy is in force");
+for (const s of ["Reminders", "Notes", "iCloud Drive", "Photos", "Calendar", "Contacts"]) {
+ await openScreen(page, s);
+ await page.waitForTimeout(500);
+}
+await openScreen(page, "Photos");
+await page.locator(".px-tile").first().dblclick();
+await page.waitForTimeout(600);
+await page.keyboard.press("Escape");
+await openScreen(page, "Notes");
+await page.locator(".note-row").first().click().catch(() => {});
+await page.waitForTimeout(400);
+// And a page from anywhere else is refused, as it must be.
+await page.evaluate(() => { const i = new Image(); i.src = "https://example.com/x.png"; document.body.append(i); });
+await page.waitForTimeout(300);
+const refused = await page.evaluate(() => window.__refused);
+const ours = refused.filter((r) => !r.includes("example.com"));
+ok(ours.length === 0, `nothing the app loads is refused ${JSON.stringify(ours.slice(0, 5))}`);
+ok(refused.some((r) => r.includes("example.com")), "a picture from elsewhere on the internet is refused");
+await b.close();
+process.exitCode = failures ? 1 : (process.exitCode ?? 0);
diff --git a/.uiverify/drive-widths.mjs b/.uiverify/drive-widths.mjs
new file mode 100644
index 0000000..2904080
--- /dev/null
+++ b/.uiverify/drive-widths.mjs
@@ -0,0 +1,42 @@
+// Drive at every window width, as a half-screen window on his desktop showed it: the bar is
+// laid out once — the name with its count under it, the controls beside it or, with too
+// little room, under it — and never moves when the count arrives a moment later. Nothing runs
+// off the edge; at half a screen the controls are icons with their names kept for screen
+// readers and tooltips.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+for (const [w, h] of [[1920, 1040], [960, 1040], [700, 900], [480, 800]]) {
+ const ctx = await b.newContext({ viewport: { width: w, height: h } });
+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, driveFixture: true });
+ await ctx.addInitScript(() => { window.__slowDrive = 900; });
+ 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" });
+ await openScreen(page, "iCloud Drive").catch(() => openScreen(page, "Drive"));
+ await page.waitForTimeout(150);
+ const box = () => page.evaluate(() => {
+ const bar = document.querySelector(".drive > .cal-bar"), up = [...bar.querySelectorAll("button")].find((x) => /Upload/.test(x.textContent));
+ const r = bar.getBoundingClientRect(), u = up.getBoundingClientRect();
+ return { h: Math.round(r.height), upTop: Math.round(u.top), upRight: Math.round(u.right), right: Math.round(r.right),
+ scroll: document.querySelector("main.content").scrollWidth - document.querySelector("main.content").clientWidth,
+ count: document.querySelector(".drive-count")?.textContent.trim() ?? "" };
+ });
+ const before = await box();
+ await page.waitForFunction(() => (document.querySelector(".drive-count")?.textContent.trim() ?? "").length > 0, null, { timeout: 8000 }).catch(() => {});
+ await page.waitForTimeout(200);
+ const after = await box();
+ ok(after.count.length > 0 && before.h === after.h && before.upTop === after.upTop,
+ `${w}px: the bar does not move when the count arrives (${before.h}→${after.h}px high, Upload at ${before.upTop}→${after.upTop}; "${after.count}")`);
+ ok(after.upRight <= after.right + 1 && after.scroll <= 0, `${w}px: nothing runs off the edge`);
+ if (w === 960) {
+ const recents = page.locator(".drive > .cal-bar button[title='Recents']");
+ ok((await recents.evaluate((e) => getComputedStyle(e).fontSize)) === "0px" && (await recents.getAttribute("title")) === "Recents",
+ "960px: the controls are icons, each still named");
+ }
+ await ctx.close();
+}
+await b.close();
+process.exitCode = failures ? 1 : (process.exitCode ?? 0);
diff --git a/.uiverify/look-all.mjs b/.uiverify/look-all.mjs
index 83a5a7e..8e51910 100644
--- a/.uiverify/look-all.mjs
+++ b/.uiverify/look-all.mjs
@@ -1,7 +1,7 @@
// Not a check: every screen with fixture data, to look at. node look-all.mjs <dir> [w] [h] [scheme]
import { engine } from "./engine.mjs";
import { SERVICES, installStub, openScreen } from "./stub.mjs";
-const [out = ".", w = "1400", h = "850", scheme = "dark"] = process.argv.slice(2);
+const [out = (await import("node:os")).tmpdir(), w = "1400", h = "850", scheme = "dark"] = process.argv.slice(2);
const b = await engine.launch();
const ctx = await b.newContext({ viewport: { width: +w, height: +h }, colorScheme: scheme });
await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null,
diff --git a/.uiverify/look-calendar.mjs b/.uiverify/look-calendar.mjs
index 57650fc..716f67f 100644
--- a/.uiverify/look-calendar.mjs
+++ b/.uiverify/look-calendar.mjs
@@ -1,7 +1,7 @@
// Not a check: Calendar's Week and Day views, to look at. node look-calendar.mjs <dir>
import { engine } from "./engine.mjs";
import { SERVICES, installStub, openScreen } from "./stub.mjs";
-const out = process.argv[2] ?? ".";
+const out = process.argv[2] ?? (await import("node:os")).tmpdir();
const b = await engine.launch();
const ctx = await b.newContext({ viewport: { width: 1400, height: 850 }, colorScheme: "dark" });
await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, calendarFixture: true });
diff --git a/.uiverify/look-icons.mjs b/.uiverify/look-icons.mjs
index 3767cb6..debd630 100644
--- a/.uiverify/look-icons.mjs
+++ b/.uiverify/look-icons.mjs
@@ -1,7 +1,7 @@
// Not a check: renders the sidebar's icons large, in both themes, to look at.
import { engine } from "./engine.mjs";
import { SERVICES, installStub } from "./stub.mjs";
-const out = process.argv[2] ?? ".";
+const out = process.argv[2] ?? (await import("node:os")).tmpdir();
const b = await engine.launch();
for (const scheme of ["dark", "light"]) {
const ctx = await b.newContext({ viewport: { width: 1100, height: 420 }, colorScheme: scheme, deviceScaleFactor: 3 });
diff --git a/.uiverify/look-reminder.mjs b/.uiverify/look-reminder.mjs
index c9e8510..5ec8fbf 100644
--- a/.uiverify/look-reminder.mjs
+++ b/.uiverify/look-reminder.mjs
@@ -11,5 +11,5 @@ await p.locator(".rx-list", { hasText: "GYM" }).click();
await p.waitForTimeout(300);
await p.getByRole("button", { name: "Details for Evening run" }).click();
await p.waitForTimeout(300);
-await p.screenshot({ path: process.argv[2] });
+await p.screenshot({ path: process.argv[2] ?? `${(await import("node:os")).tmpdir()}/reminder.png` });
await b.close();
diff --git a/.uiverify/notes-look.mjs b/.uiverify/notes-look.mjs
index 1d9ba02..c1156a7 100644
--- a/.uiverify/notes-look.mjs
+++ b/.uiverify/notes-look.mjs
@@ -2,7 +2,8 @@
// ENGINE=webkit node .uiverify/notes-look.mjs <out-dir> [width] [height]
import { engine } from "./engine.mjs";
import { SERVICES, installStub } from "./stub.mjs";
-const [out, w = "1920", h = "1040"] = process.argv.slice(2);
+// Never into the repository: with no folder given, the system's temporary one.
+const [out = (await import("node:os")).tmpdir(), w = "1920", h = "1040"] = process.argv.slice(2);
const b = await engine.launch();
for (const scheme of ["dark", "light"]) {
const ctx = await b.newContext({ viewport: { width: +w, height: +h }, colorScheme: scheme });
diff --git a/.uiverify/reminders-repeat-tick.mjs b/.uiverify/reminders-repeat-tick.mjs
new file mode 100644
index 0000000..3bc9b80
--- /dev/null
+++ b/.uiverify/reminders-repeat-tick.mjs
@@ -0,0 +1,35 @@
+// Ticking a repeating reminder answers at once like any other: the circle fills the moment it
+// is clicked, while Apple is still making the next one; then the row rolls on, open again with
+// its next date, as on the phone. (It used to show nothing until Apple answered.)
+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: 800 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, remindersFixture: true });
+await ctx.addInitScript(() => {
+ const now = Math.floor(Date.now() / 1000);
+ window.__extraReminders = [{ guid: "rr", listGuid: "l1", title: "Take vitamins", notes: null, dueAt: now + 3600, allDay: false,
+ completedAt: null, priority: 0, flagged: false, parentGuid: null, etag: null, recurFrequency: 0, recurInterval: 1 }];
+});
+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" });
+await openScreen(page, "Reminders");
+await page.locator(".rx-list", { hasText: "Daily" }).click();
+await page.waitForTimeout(300);
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+const row = page.locator(".rx-row", { has: page.getByLabel("Rename Take vitamins") });
+const due = () => row.innerText();
+const before = await due();
+await page.evaluate(() => { window.__doneDelay = 1500; });
+await row.locator(".rx-tick").click();
+await page.waitForTimeout(80);
+ok((await row.locator(".rx-tick").getAttribute("aria-checked")) === "true", "the circle fills at once, while Apple is still making the next one");
+await page.waitForTimeout(700);
+ok((await row.count()) === 1, "and the row stays — a repeating one never leaves");
+await page.waitForTimeout(1500);
+ok((await row.locator(".rx-tick").getAttribute("aria-checked")) === "false", "once Apple has it, it is open again");
+ok((await due()) !== before, `with its next date (${(await due()).replace(/\n/g, " ")})`);
+await b.close();
+process.exitCode = failures ? 1 : (process.exitCode ?? 0);
diff --git a/.uiverify/screens-kept.mjs b/.uiverify/screens-kept.mjs
new file mode 100644
index 0000000..4499d37
--- /dev/null
+++ b/.uiverify/screens-kept.mjs
@@ -0,0 +1,58 @@
+// Screens are kept once opened, as a Mac app's windows are: coming back to one is instant and
+// finds it as it was left — the same page, its scroll, its selection, the photo open in it —
+// while out of sight it is inert and answers no keys.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const b = await engine.launch();
+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });
+await ctx.addInitScript(() => {
+ const P = (id, t) => ({ id, master: `m${id}`, takenAt: t, addedAt: t, kind: "image", width: 4032, height: 3024, duration: null,
+ filename: `IMG_${id}.JPG`, size: 1, uti: "public.jpeg", favorite: false, hidden: false, deleted: false, deletedAt: null, subtype: 0, changeTag: null });
+ window.__photos = Array.from({ length: 600 }, (_, i) => P(`q${i}`, 1792600000 - i * 40000));
+});
+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 openScreen(page, "Photos");
+await page.waitForTimeout(500);
+await page.locator(".px-scroll").evaluate((e) => { e.scrollTop = 1500; e.__kept = true; });
+await page.waitForTimeout(300);
+// A photo on screen there, clicked where it is.
+const spot = await page.evaluate(() => {
+ const t = [...document.querySelectorAll(".px-tile")].find((e) => { const r = e.getBoundingClientRect(); return r.top > 200 && r.bottom < innerHeight - 100; });
+ const r = t.getBoundingClientRect();
+ return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
+});
+await page.mouse.click(spot.x, spot.y);
+const picked = await page.locator('.px-tile[aria-selected="true"]').getAttribute("data-id");
+await openScreen(page, "Notes");
+await page.waitForTimeout(300);
+ok((await page.locator(".screen-slot[hidden][inert] .px-scroll").count()) === 1, "Photos, out of sight, is kept — hidden and inert");
+await openScreen(page, "Photos");
+await page.waitForTimeout(100);
+const back = await page.locator(".px-scroll").evaluate((e) => ({ same: e.__kept === true, top: e.scrollTop }));
+ok(back.same, "coming back finds the same page, not one built again");
+ok(Math.abs(back.top - 1500) < 2, `at the place it was left (${back.top})`);
+ok((await page.locator('.px-tile[aria-selected="true"]').getAttribute("data-id")) === picked, "with the same photo chosen");
+
+// Keys typed on another screen never reach a kept one.
+await page.mouse.dblclick(spot.x, spot.y);
+await page.waitForTimeout(300);
+const at = (await page.locator(".px-viewer-when").innerText()).replace(/\n/g, " ");
+await openScreen(page, "Calendar");
+await page.waitForTimeout(400);
+await page.locator("body").press("ArrowRight");
+await page.locator("body").press("Escape");
+await page.waitForTimeout(200);
+await openScreen(page, "Photos");
+await page.waitForTimeout(200);
+ok((await page.locator(".px-viewer").count()) === 1 && (await page.locator(".px-viewer-when").innerText()).replace(/\n/g, " ") === at,
+ `the photo left open is still open, on the same photo — another screen's keys never reached it (${at})`);
+ok(Math.abs((await page.locator(".px-scroll").evaluate((e) => e.scrollTop)) - 1500) < 2, "and the grid under it still where it was");
+ok((await page.locator(".screen-slot:not([hidden])").count()) === 1, "only one screen is ever showing");
+await b.close();
+process.exitCode = failures ? 1 : (process.exitCode ?? 0);
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index 9a1ea61..6972021 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -192,7 +192,9 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
if (!remindersFixture || remindersFixture === "lists") return [];
// Opt-in for measuring a switch: each list's own reminders, after a real read's wait.
if (window.__slowItems) await new Promise((r) => setTimeout(r, window.__slowItems));
- return window.__filterLists ? reminderItems.filter((r) => r.listGuid === args.listGuid) : reminderItems;
+ // A test's own extra reminders (__extraReminders), kept as Apple keeps them.
+ const every = [...reminderItems, ...(window.__extraReminders ?? [])];
+ return window.__filterLists ? every.filter((r) => r.listGuid === args.listGuid) : every;
}
case "reminders_due_between": return calendarFixture ? dueReminders : [];
case "reminder_create":
@@ -206,6 +208,11 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
(window.__done ??= []).push(args);
// A slow network, when a test asks for one.
if (window.__doneDelay) await new Promise((r) => setTimeout(r, window.__doneDelay));
+ {
+ // A repeating one rolls on, as Apple rolls it: open again, a day (or its unit) on.
+ const r = (window.__extraReminders ?? []).find((x) => x.guid === args.guid);
+ if (r && r.recurFrequency !== null && r.recurFrequency !== undefined && args.done) r.dueAt += 86400 * (r.recurInterval ?? 1);
+ }
return null;
case "reminder_set_repeat": return null;
case "reminder_edit": {
@@ -510,7 +517,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
case "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 "contacts_import": (window.__imports ??= []).push(args); return [2, 0];
+ case "contacts_import": (window.__imports ??= []).push(args); return window.__importAnswer ?? [2, 0, 0];
case "plugin:dialog|open": return window.__pick ?? null;
case "contact_lists": return !contactsFixture ? [] : (window.__lists ??= [
{ guid: "L1", name: "Family", members: ["c2"], etag: "e1" },
@@ -543,7 +550,10 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
if (window.__settingsFail) throw "Couldn't save that setting.";
(window.__settings ??= {})[args.key] = args.on;
return null;
- case "drive_children": return !driveFixture ? [] : driveItems;
+ case "drive_children":
+ // A slow read, when a test asks for one.
+ if (window.__slowDrive) await new Promise((r) => setTimeout(r, window.__slowDrive));
+ return !driveFixture ? [] : driveItems;
case "drive_recents": {
if (!driveFixture) return [];
const now = Math.floor(Date.now() / 1000);
diff --git a/Cargo.lock b/Cargo.lock
index 284e7de..50baeb6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -230,7 +230,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b"
dependencies = [
"atk-sys",
- "glib",
+ "glib 0.18.5",
"libc",
]
@@ -240,8 +240,8 @@ version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086"
dependencies = [
- "glib-sys",
- "gobject-sys",
+ "glib-sys 0.18.1",
+ "gobject-sys 0.18.0",
"libc",
"system-deps 6.2.2",
]
@@ -252,6 +252,12 @@ version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+[[package]]
+name = "atomic_refcell"
+version = "0.1.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "21e4227379beff4205943696e6c3e0cd809bacdf3f0edd6e3dd153e2269571a4"
+
[[package]]
name = "autocfg"
version = "1.5.1"
@@ -417,7 +423,7 @@ checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2"
dependencies = [
"bitflags 2.13.2",
"cairo-sys-rs",
- "glib",
+ "glib 0.18.5",
"libc",
"once_cell",
"thiserror 1.0.69",
@@ -429,7 +435,7 @@ version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51"
dependencies = [
- "glib-sys",
+ "glib-sys 0.18.1",
"libc",
"system-deps 6.2.2",
]
@@ -1096,6 +1102,12 @@ version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
+[[package]]
+name = "either"
+version = "1.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
+
[[package]]
name = "embed-resource"
version = "3.0.11"
@@ -1432,7 +1444,7 @@ dependencies = [
"gdk-pixbuf",
"gdk-sys",
"gio",
- "glib",
+ "glib 0.18.5",
"libc",
"pango",
]
@@ -1445,7 +1457,7 @@ checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec"
dependencies = [
"gdk-pixbuf-sys",
"gio",
- "glib",
+ "glib 0.18.5",
"libc",
"once_cell",
]
@@ -1456,9 +1468,9 @@ version = "0.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7"
dependencies = [
- "gio-sys",
- "glib-sys",
- "gobject-sys",
+ "gio-sys 0.18.1",
+ "glib-sys 0.18.1",
+ "gobject-sys 0.18.0",
"libc",
"system-deps 6.2.2",
]
@@ -1471,9 +1483,9 @@ checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7"
dependencies = [
"cairo-sys-rs",
"gdk-pixbuf-sys",
- "gio-sys",
- "glib-sys",
- "gobject-sys",
+ "gio-sys 0.18.1",
+ "glib-sys 0.18.1",
+ "gobject-sys 0.18.0",
"libc",
"pango-sys",
"pkg-config",
@@ -1487,8 +1499,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "140071d506d223f7572b9f09b5e155afbd77428cd5cc7af8f2694c41d98dfe69"
dependencies = [
"gdk-sys",
- "glib-sys",
- "gobject-sys",
+ "glib-sys 0.18.1",
+ "gobject-sys 0.18.0",
"libc",
"pkg-config",
"system-deps 6.2.2",
@@ -1503,7 +1515,7 @@ dependencies = [
"gdk",
"gdkx11-sys",
"gio",
- "glib",
+ "glib 0.18.5",
"libc",
"x11",
]
@@ -1515,7 +1527,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2e7445fe01ac26f11601db260dd8608fe172514eb63b3b5e261ea6b0f4428d"
dependencies = [
"gdk-sys",
- "glib-sys",
+ "glib-sys 0.18.1",
"libc",
"system-deps 6.2.2",
"x11",
@@ -1580,8 +1592,8 @@ dependencies = [
"futures-core",
"futures-io",
"futures-util",
- "gio-sys",
- "glib",
+ "gio-sys 0.18.1",
+ "glib 0.18.5",
"libc",
"once_cell",
"pin-project-lite",
@@ -1595,13 +1607,26 @@ version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2"
dependencies = [
- "glib-sys",
- "gobject-sys",
+ "glib-sys 0.18.1",
+ "gobject-sys 0.18.0",
"libc",
"system-deps 6.2.2",
"winapi",
]
+[[package]]
+name = "gio-sys"
+version = "0.22.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c28739f914c15b87a9856000bed9cbd5b3a8afbca5e982d9a299e1601422cb5"
+dependencies = [
+ "glib-sys 0.22.9",
+ "gobject-sys 0.22.9",
+ "libc",
+ "system-deps 9.0.0",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "glib"
version = "0.18.5"
@@ -1614,10 +1639,10 @@ dependencies = [
"futures-executor",
"futures-task",
"futures-util",
- "gio-sys",
- "glib-macros",
- "glib-sys",
- "gobject-sys",
+ "gio-sys 0.18.1",
+ "glib-macros 0.18.5",
+ "glib-sys 0.18.1",
+ "gobject-sys 0.18.0",
"libc",
"memchr",
"once_cell",
@@ -1625,6 +1650,27 @@ dependencies = [
"thiserror 1.0.69",
]
+[[package]]
+name = "glib"
+version = "0.22.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e4cf9e5bd8713f1990a92c422998826e0fb34824277b46bc59757373483c6694"
+dependencies = [
+ "bitflags 2.13.2",
+ "futures-channel",
+ "futures-core",
+ "futures-executor",
+ "futures-task",
+ "futures-util",
+ "gio-sys 0.22.9",
+ "glib-macros 0.22.9",
+ "glib-sys 0.22.9",
+ "gobject-sys 0.22.9",
+ "libc",
+ "memchr",
+ "smallvec",
+]
+
[[package]]
name = "glib-macros"
version = "0.18.5"
@@ -1639,6 +1685,18 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "glib-macros"
+version = "0.22.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c9597c68fa7bdf4154a3079642cd21c4dccac0b0bdd2897d82861523bf91e7b9"
+dependencies = [
+ "heck 0.5.0",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.5",
+]
+
[[package]]
name = "glib-sys"
version = "0.18.1"
@@ -1649,6 +1707,16 @@ dependencies = [
"system-deps 6.2.2",
]
+[[package]]
+name = "glib-sys"
+version = "0.22.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "99b38907e67e40dec9b60f858bcada952598719cb512a13eb13d6cdcd16f8295"
+dependencies = [
+ "libc",
+ "system-deps 9.0.0",
+]
+
[[package]]
name = "glob"
version = "0.3.4"
@@ -1661,11 +1729,145 @@ version = "0.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44"
dependencies = [
- "glib-sys",
+ "glib-sys 0.18.1",
"libc",
"system-deps 6.2.2",
]
+[[package]]
+name = "gobject-sys"
+version = "0.22.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "07595c9ba696bd9819cb6a8df39f08078f3dd679508fe052dd558492c2053834"
+dependencies = [
+ "glib-sys 0.22.9",
+ "libc",
+ "system-deps 9.0.0",
+]
+
+[[package]]
+name = "gstreamer"
+version = "0.25.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f4237e2066a25ecb7e54be6c066409e30615920265b9799b8d560ef8ac9857c6"
+dependencies = [
+ "cfg-if",
+ "futures-channel",
+ "futures-core",
+ "futures-util",
+ "glib 0.22.10",
+ "gstreamer-sys",
+ "itertools",
+ "kstring",
+ "libc",
+ "muldiv",
+ "num-integer",
+ "num-rational",
+ "option-operations",
+ "pastey",
+ "pin-project-lite",
+ "smallvec",
+ "thiserror 2.0.20",
+]
+
+[[package]]
+name = "gstreamer-app"
+version = "0.25.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97f8ae9238c2352398dcc084de28df3f7099af216ac6c160b52318d23f25c010"
+dependencies = [
+ "futures-core",
+ "futures-sink",
+ "glib 0.22.10",
+ "gstreamer",
+ "gstreamer-app-sys",
+ "gstreamer-base",
+ "libc",
+]
+
+[[package]]
+name = "gstreamer-app-sys"
+version = "0.25.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0798b8aef6694341d40bb81edc759f8979b896b59f9f0f45d8cfa3bb7bf2e743"
+dependencies = [
+ "glib-sys 0.22.9",
+ "gstreamer-base-sys",
+ "gstreamer-sys",
+ "libc",
+ "system-deps 9.0.0",
+]
+
+[[package]]
+name = "gstreamer-base"
+version = "0.25.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "17cbd8f59586a369c40d4b0d2f3a61cf9e9287b3cf5503cdcd8e7c5faa99265e"
+dependencies = [
+ "atomic_refcell",
+ "cfg-if",
+ "glib 0.22.10",
+ "gstreamer",
+ "gstreamer-base-sys",
+ "libc",
+]
+
+[[package]]
+name = "gstreamer-base-sys"
+version = "0.25.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b05f77bfd76b5afee6b29c27dae19eaf5018b5cf8d0d17520f3de44c6385c32"
+dependencies = [
+ "glib-sys 0.22.9",
+ "gobject-sys 0.22.9",
+ "gstreamer-sys",
+ "libc",
+ "system-deps 9.0.0",
+]
+
+[[package]]
+name = "gstreamer-sys"
+version = "0.25.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "436d9532847489a8285d57b8c3670762c12a18f777fdc2ab159b52e0e6f521b9"
+dependencies = [
+ "cfg-if",
+ "glib-sys 0.22.9",
+ "gobject-sys 0.22.9",
+ "libc",
+ "system-deps 9.0.0",
+]
+
+[[package]]
+name = "gstreamer-video"
+version = "0.25.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ffe4d77b2a5e679973d9c6b6c052da8cda86b83f5c268872f8691fde693fde84"
+dependencies = [
+ "cfg-if",
+ "futures-channel",
+ "glib 0.22.10",
+ "gstreamer",
+ "gstreamer-base",
+ "gstreamer-video-sys",
+ "libc",
+ "thiserror 2.0.20",
+]
+
+[[package]]
+name = "gstreamer-video-sys"
+version = "0.25.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef455da22edca97ac9299d682b868227f3d9217b303748ce0161b31ae82dc106"
+dependencies = [
+ "glib-sys 0.22.9",
+ "gobject-sys 0.22.9",
+ "gstreamer-base-sys",
+ "gstreamer-sys",
+ "libc",
+ "system-deps 9.0.0",
+]
+
[[package]]
name = "gtk"
version = "0.18.2"
@@ -1679,7 +1881,7 @@ dependencies = [
"gdk",
"gdk-pixbuf",
"gio",
- "glib",
+ "glib 0.18.5",
"gtk-sys",
"gtk3-macros",
"libc",
@@ -1697,9 +1899,9 @@ dependencies = [
"cairo-sys-rs",
"gdk-pixbuf-sys",
"gdk-sys",
- "gio-sys",
- "glib-sys",
- "gobject-sys",
+ "gio-sys 0.18.1",
+ "glib-sys 0.18.1",
+ "gobject-sys 0.18.0",
"libc",
"pango-sys",
"system-deps 6.2.2",
@@ -2151,6 +2353,15 @@ dependencies = [
"once_cell",
]
+[[package]]
+name = "itertools"
+version = "0.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc"
+dependencies = [
+ "either",
+]
+
[[package]]
name = "itoa"
version = "1.0.18"
@@ -2164,7 +2375,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc"
dependencies = [
"bitflags 1.3.2",
- "glib",
+ "glib 0.18.5",
"javascriptcore-rs-sys",
]
@@ -2174,8 +2385,8 @@ version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124"
dependencies = [
- "glib-sys",
- "gobject-sys",
+ "glib-sys 0.18.1",
+ "gobject-sys 0.18.0",
"libc",
"system-deps 6.2.2",
]
@@ -2338,6 +2549,15 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "kstring"
+version = "2.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a09b82a7f771ed02dc0dd9b27130a0fa5499fa15ed3027116c1e5e4e591bd9e"
+dependencies = [
+ "static_assertions",
+]
+
[[package]]
name = "lazy_static"
version = "1.5.0"
@@ -2350,7 +2570,7 @@ version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03589b9607c868cc7ae54c0b2a22c8dc03dd41692d48f2d7df73615c6a95dc0a"
dependencies = [
- "glib",
+ "glib 0.18.5",
"gtk",
"gtk-sys",
"libappindicator-sys",
@@ -2596,6 +2816,12 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "muldiv"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "956787520e75e9bd233246045d19f42fb73242759cc57fba9611d940ae96d4b0"
+
[[package]]
name = "ndk"
version = "0.9.0"
@@ -2982,6 +3208,15 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
+[[package]]
+name = "option-operations"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aca39cf52b03268400c16eeb9b56382ea3c3353409309b63f5c8f0b1faf42754"
+dependencies = [
+ "pastey",
+]
+
[[package]]
name = "ordered-stream"
version = "0.2.0"
@@ -2999,7 +3234,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4"
dependencies = [
"gio",
- "glib",
+ "glib 0.18.5",
"libc",
"once_cell",
"pango-sys",
@@ -3011,8 +3246,8 @@ version = "0.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5"
dependencies = [
- "glib-sys",
- "gobject-sys",
+ "glib-sys 0.18.1",
+ "gobject-sys 0.18.0",
"libc",
"system-deps 6.2.2",
]
@@ -3046,6 +3281,12 @@ dependencies = [
"windows-link 0.2.1",
]
+[[package]]
+name = "pastey"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
+
[[package]]
name = "pbkdf2"
version = "0.12.2"
@@ -3335,6 +3576,10 @@ dependencies = [
"anyhow",
"base64 0.22.1",
"futures-util",
+ "gstreamer",
+ "gstreamer-app",
+ "gstreamer-video",
+ "image",
"jiff",
"libc",
"notify-rust",
@@ -3781,8 +4026,8 @@ checksum = "a15ad77d9e70a92437d8f74c35d99b4e4691128df018833e99f90bcd36152672"
dependencies = [
"block2",
"dispatch2",
- "glib-sys",
- "gobject-sys",
+ "glib-sys 0.18.1",
+ "gobject-sys 0.18.0",
"gtk-sys",
"js-sys",
"log",
@@ -4344,7 +4589,7 @@ checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f"
dependencies = [
"futures-channel",
"gio",
- "glib",
+ "glib 0.18.5",
"libc",
"soup3-sys",
]
@@ -4355,9 +4600,9 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27"
dependencies = [
- "gio-sys",
- "glib-sys",
- "gobject-sys",
+ "gio-sys 0.18.1",
+ "glib-sys 0.18.1",
+ "gobject-sys 0.18.0",
"libc",
"system-deps 6.2.2",
]
@@ -4499,6 +4744,19 @@ dependencies = [
"version-compare",
]
+[[package]]
+name = "system-deps"
+version = "9.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a0dae2cbca1f0ff93795713cfe0a4c02f760e3c0b8ae2ab4ec4045808ff429f"
+dependencies = [
+ "cfg-expr 0.20.10",
+ "heck 0.5.0",
+ "pkg-config",
+ "toml 1.1.6+spec-1.1.0",
+ "version-compare",
+]
+
[[package]]
name = "tao"
version = "0.35.3"
@@ -5606,10 +5864,10 @@ dependencies = [
"gdk",
"gdk-sys",
"gio",
- "gio-sys",
- "glib",
- "glib-sys",
- "gobject-sys",
+ "gio-sys 0.18.1",
+ "glib 0.18.5",
+ "glib-sys 0.18.1",
+ "gobject-sys 0.18.0",
"gtk",
"gtk-sys",
"javascriptcore-rs",
@@ -5628,9 +5886,9 @@ dependencies = [
"bitflags 1.3.2",
"cairo-sys-rs",
"gdk-sys",
- "gio-sys",
- "glib-sys",
- "gobject-sys",
+ "gio-sys 0.18.1",
+ "glib-sys 0.18.1",
+ "gobject-sys 0.18.0",
"gtk-sys",
"javascriptcore-rs-sys",
"libc",
diff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rs
index 897c35d..2d0e29a 100644
--- a/crates/quince-auth/src/lib.rs
+++ b/crates/quince-auth/src/lib.rs
@@ -10,6 +10,17 @@
//! A webview never asks for one, so it has nothing to persist and signs you out. We store
//! it in the OS keyring.
+/// What went wrong, said on the terminal in a development build only, and never with anything
+/// of the person's in it — no names, record ids, addresses or Apple's answers. A release build
+/// says nothing at all: Quince keeps no diagnostics and sends none anywhere.
+macro_rules! quiet {
+ ($($t:tt)*) => {
+ if cfg!(debug_assertions) {
+ eprintln!($($t)*);
+ }
+ };
+}
+
pub mod session;
pub mod srp;
@@ -688,7 +699,7 @@ impl Client {
// Settings, or pressing "Send again". Not fatal if it fails: the code screen
// still offers sending it again, and a text.
if let Err(e) = self.resend_to_devices().await {
- eprintln!("asking Apple to send the code: {e}");
+ quiet!("asking Apple to send the code: {e}");
}
Ok(SignInOutcome::NeedsTwoFactor)
}
diff --git a/crates/quince-icloud/src/calendar.rs b/crates/quince-icloud/src/calendar.rs
index 7f56e4b..6a5d789 100644
--- a/crates/quince-icloud/src/calendar.rs
+++ b/crates/quince-icloud/src/calendar.rs
@@ -276,10 +276,8 @@ fn now_seconds() -> i64 {
/// {"ChangeSet":…}` — which says nothing to a person about what happened or what to do. The
/// sentence says that; the path, status and body go to the log for whoever has to look.
fn refusal(path: &str, status: reqwest::StatusCode, body: &str) -> Error {
- eprintln!(
- "calendar: {path} answered {status}: {}",
- body.chars().take(300).collect::<String>()
- );
+ let _ = (path, body);
+ quiet!("calendar: a request was refused ({status})");
match status.as_u16() {
409 | 412 => Error::Conflict,
400 | 422 => Error::Refused("iCloud didn't accept that change, so nothing was saved.".into()),
diff --git a/crates/quince-icloud/src/cloudkit.rs b/crates/quince-icloud/src/cloudkit.rs
index e5d18ff..8ff394a 100644
--- a/crates/quince-icloud/src/cloudkit.rs
+++ b/crates/quince-icloud/src/cloudkit.rs
@@ -70,6 +70,17 @@ fn trouble_with(zone_result: &Value) -> Option<ZoneTrouble> {
/// How many times a busy CloudKit is asked before saying so.
const BUSY_TRIES: u32 = 3;
+
+/// A record refused only because the zone was mid-write for someone else — Apple's
+/// "Sync zone CAS Op-Lock failed. There was a concurrent write … Retry request", coded
+/// ZONE_BUSY or TRY_AGAIN_LATER — measured deleting notes one after another. Nothing was
+/// applied; the same change, sent again, goes through.
+fn zone_was_busy(code: &str, reason: &str) -> bool {
+ matches!(code, "ZONE_BUSY" | "TRY_AGAIN_LATER")
+ || reason
+ .to_ascii_lowercase()
+ .contains("sync zone cas op-lock failed")
+}
/// The longest single wait a busy CloudKit is given, whatever it asks for.
const LONGEST_WAIT: u64 = 30;
@@ -123,13 +134,17 @@ impl<'a> ZoneClient<'a> {
let text = response.text().await.unwrap_or_default();
// A zone busy with another write answers 409 ZONE_BUSY — "rejected, retry", the
// whole request not applied — measured when a phone and this app wrote at once.
- // It is a wait like 503's, not a conflict over the record.
- let zone_busy = status.as_u16() == 409 && text.contains("\"ZONE_BUSY\"");
+ // Two of this app's own writes to one zone close together (notes deleted one after
+ // another in Recently Deleted) answer 409 TRY_AGAIN_LATER, "Sync zone CAS Op-Lock
+ // failed. There was a concurrent write" — the same: nothing applied, ask again.
+ // Each is a wait like 503's, not a conflict over the record.
+ let zone_busy = status.as_u16() == 409
+ && (text.contains("\"ZONE_BUSY\"") || text.contains("\"TRY_AGAIN_LATER\""));
if !matches!(status.as_u16(), 429 | 503) && !zone_busy {
return Ok((status, text));
}
if tries >= BUSY_TRIES {
- eprintln!("cloudkit: still busy after {tries} tries ({status}): {text}");
+ quiet!("cloudkit: still busy after {tries} tries ({status})");
return Err(Error::Refused(
"iCloud is busy right now. Nothing was changed — try again in a minute.".into(),
));
@@ -503,6 +518,63 @@ mod tests {
.unwrap();
}
+ /// Two of this app's own writes close together: Apple's answer, word for word as he met it
+ /// deleting notes in Recently Deleted, is waited out the same way.
+ #[tokio::test]
+ async fn a_concurrent_write_is_tried_again() {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path_regex(r".*/records/modify$"))
+ .respond_with(ResponseTemplate::new(409).set_body_json(json!({
+ "uuid": "d1fdc23f-b3c5-4537-8ab2-75e2ec1606f9", "serverErrorCode": "TRY_AGAIN_LATER",
+ "reason": "Sync zone CAS Op-Lock failed. There was a concurrent write and this operation was rejected."
+ })))
+ .up_to_n_times(1)
+ .mount(&server)
+ .await;
+ Mock::given(method("POST"))
+ .and(path_regex(r".*/records/modify$"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({
+ "records": [{ "recordName": "N", "recordChangeTag": "t2" }]
+ })))
+ .mount(&server)
+ .await;
+ let http = reqwest::Client::new();
+ let client = ZoneClient::new(&http, &server.uri(), "com.apple.notes", vec![]);
+ client
+ .update_record("Notes", "N", "Note", Some("t1"), json!({}))
+ .await
+ .unwrap();
+ }
+
+ /// The same refusal carried per record in a 200, as Apple also sends it: tried again too.
+ #[tokio::test]
+ async fn a_record_refused_for_a_busy_zone_is_tried_again() {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path_regex(r".*/records/modify$"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({
+ "records": [{ "recordName": "N", "serverErrorCode": "TRY_AGAIN_LATER",
+ "reason": "Sync zone CAS Op-Lock failed. There was a concurrent write and this operation was rejected. Retry request..." }]
+ })))
+ .up_to_n_times(1)
+ .mount(&server)
+ .await;
+ Mock::given(method("POST"))
+ .and(path_regex(r".*/records/modify$"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({
+ "records": [{ "recordName": "N", "recordChangeTag": "t2" }]
+ })))
+ .mount(&server)
+ .await;
+ let http = reqwest::Client::new();
+ let client = ZoneClient::new(&http, &server.uri(), "com.apple.notes", vec![]);
+ client
+ .update_record("Notes", "N", "Note", Some("t1"), json!({}))
+ .await
+ .unwrap();
+ }
+
/// And one still busy after that is said in a sentence, not Apple's JSON.
#[tokio::test]
async fn a_cloudkit_that_stays_busy_says_so_plainly() {
@@ -749,6 +821,30 @@ impl ZoneClient<'_> {
}
async fn modify(&self, zone: &str, operation: Value) -> Result<Value> {
+ // A record refused because the zone was busy with another write was not applied: the
+ // same request goes again after a moment, as a busy server's is.
+ let mut tries = 0;
+ loop {
+ tries += 1;
+ match self.modify_once(zone, &operation).await {
+ Err(Error::Busy) if tries < BUSY_TRIES => {
+ tokio::time::sleep(std::time::Duration::from_millis(
+ 400 * u64::from(tries) * u64::from(tries),
+ ))
+ .await;
+ }
+ Err(Error::Busy) => {
+ return Err(Error::Refused(
+ "iCloud is busy right now. Nothing was changed — try again in a minute."
+ .into(),
+ ))
+ }
+ other => return other,
+ }
+ }
+ }
+
+ async fn modify_once(&self, zone: &str, operation: &Value) -> Result<Value> {
let body = json!({
"operations": [operation],
"zoneID": { "zoneName": zone, "zoneType": "REGULAR_CUSTOM_ZONE" },
@@ -779,6 +875,9 @@ impl ZoneClient<'_> {
.pointer("/records/0/serverErrorCode")
.and_then(Value::as_str)
.unwrap_or("");
+ if zone_was_busy(code, reason) {
+ return Err(Error::Busy);
+ }
// Apple signals a stale change tag as CONFLICT, and sometimes as an "oplock"
// message with a different code; both mean the same thing.
let stale = code == "CONFLICT" || reason.to_ascii_lowercase().contains("oplock");
@@ -1067,8 +1166,11 @@ impl ZoneClient<'_> {
.get("serverErrorCode")
.and_then(Value::as_str)
.unwrap_or("");
+ // A busy zone is retried as a moved tag is, once more on a fresh read.
Err(
- if code == "CONFLICT" || reason.to_ascii_lowercase().contains("oplock")
+ if code == "CONFLICT"
+ || reason.to_ascii_lowercase().contains("oplock")
+ || zone_was_busy(code, reason)
{
Error::Conflict
} else {
diff --git a/crates/quince-icloud/src/contacts.rs b/crates/quince-icloud/src/contacts.rs
index 5b6bcf7..dcc6163 100644
--- a/crates/quince-icloud/src/contacts.rs
+++ b/crates/quince-icloud/src/contacts.rs
@@ -892,6 +892,79 @@ pub fn split_vcards(text: &str) -> Vec<String> {
out
}
+/// Whether a vCard is someone already in the book — the same names and nothing the book's
+/// card lacks (each phone and email on it already there). Importing an export of the same
+/// book once added a copy of every person (2026-10-20, 123 of them); Apple's own Contacts
+/// leaves such a card out, and so does this.
+#[must_use]
+pub fn already_in(card: &str, book: &[Contact]) -> bool {
+ let unfold = card.replace("\r\n ", "").replace("\n ", "");
+ let mut name = (String::new(), String::new(), String::new());
+ let mut org = String::new();
+ let mut reach: Vec<String> = Vec::new();
+ for line in unfold.lines() {
+ let Some((key, value)) = line.split_once(':') else {
+ continue;
+ };
+ let field = key.split(';').next().unwrap_or("").to_ascii_uppercase();
+ let field = field.rsplit('.').next().unwrap_or("").to_string();
+ let value = value.trim().replace("\\,", ",").replace("\\;", ";");
+ match field.as_str() {
+ "N" => {
+ let mut parts = line[line.find(':').unwrap_or(0) + 1..].split(';');
+ let last = parts.next().unwrap_or("").trim().to_string();
+ let first = parts.next().unwrap_or("").trim().to_string();
+ let middle = parts.next().unwrap_or("").trim().to_string();
+ name = (first, middle, last);
+ }
+ "ORG" => org = value.split(';').next().unwrap_or("").trim().to_string(),
+ "TEL" => reach.push(phone_key(&value)),
+ "EMAIL" => reach.push(value.to_lowercase()),
+ _ => {}
+ }
+ }
+ reach.retain(|r| !r.is_empty());
+ let same = |a: &Option<String>, b: &str| {
+ a.as_deref()
+ .unwrap_or("")
+ .trim()
+ .eq_ignore_ascii_case(b.trim())
+ };
+ book.iter().any(|c| {
+ let named = same(&c.first_name, &name.0)
+ && same(&c.middle_name, &name.1)
+ && same(&c.last_name, &name.2)
+ && same(&c.company, &org);
+ if !named {
+ return false;
+ }
+ let theirs: Vec<String> = c
+ .methods
+ .iter()
+ .filter(|m| m.kind == "phone" || m.kind == "email")
+ .map(|m| {
+ if m.kind == "phone" {
+ phone_key(&m.value)
+ } else {
+ m.value.to_lowercase()
+ }
+ })
+ .collect();
+ // A card with nothing to tell it apart is the same only if the book's has nothing too.
+ if reach.is_empty() {
+ return theirs.is_empty()
+ && !(name.0.is_empty() && name.2.is_empty() && org.is_empty());
+ }
+ reach.iter().all(|r| theirs.contains(r))
+ })
+}
+
+/// A phone number as digits only, its last ten: "+91 90000 00002" and "090000 00002" are one.
+fn phone_key(v: &str) -> String {
+ let digits: String = v.chars().filter(char::is_ascii_digit).collect();
+ digits[digits.len().saturating_sub(10)..].to_string()
+}
+
/// Cards gathered into batches Apple takes in one import: under `max_bytes` and `max_cards`.
#[must_use]
pub fn batch_vcards(cards: &[String], max_bytes: usize, max_cards: usize) -> Vec<String> {
@@ -1353,6 +1426,49 @@ mod list_tests {
#[cfg(test)]
mod tests {
+ #[test]
+ fn a_card_already_in_the_book_is_known() {
+ use quince_core::contacts::{Contact, ContactMethod};
+ let person = |first: &str, last: &str, phones: &[&str]| Contact {
+ guid: "G".into(),
+ first_name: Some(first.into()),
+ middle_name: None,
+ photo_url: None,
+ photo_signature: None,
+ photo_crop: None,
+ last_name: Some(last.into()),
+ company: None,
+ is_company: false,
+ birthday: None,
+ notes: None,
+ etag: None,
+ methods: phones
+ .iter()
+ .map(|p| ContactMethod {
+ kind: "phone".into(),
+ label: Some("mobile".into()),
+ value: (*p).into(),
+ })
+ .collect(),
+ };
+ let book = vec![person("Asha", "Rao", &["+91 90000 00002"])];
+ let card = |n: &str, tel: &str| {
+ format!("BEGIN:VCARD\r\nVERSION:3.0\r\nN:{n}\r\nFN:x\r\nTEL;type=CELL:{tel}\r\nEND:VCARD\r\n")
+ };
+ assert!(
+ super::already_in(&card("Rao;Asha;;;", "090000 00002"), &book),
+ "the same person, the number written another way"
+ );
+ assert!(
+ !super::already_in(&card("Rao;Asha;;;", "+91 90000 00004"), &book),
+ "a number the book lacks is news"
+ );
+ assert!(
+ !super::already_in(&card("Rao;Ashwin;;;", "+91 90000 00002"), &book),
+ "another name is someone else"
+ );
+ }
+
use super::*;
/// A Google Contacts export: names, a company with a comma, two numbers in one cell, an
diff --git a/crates/quince-icloud/src/drive.rs b/crates/quince-icloud/src/drive.rs
index 5535a06..9c032bf 100644
--- a/crates/quince-icloud/src/drive.rs
+++ b/crates/quince-icloud/src/drive.rs
@@ -2485,10 +2485,7 @@ async fn post_json(
return Err(Error::ReauthRequired);
}
if !status.is_success() {
- eprintln!(
- "drive: {url} answered {status}: {}",
- text.chars().take(300).collect::<String>()
- );
+ quiet!("drive: a request was refused ({status})");
if status.as_u16() == 409 && text.contains("ZONE_BUSY") {
return Err(Error::Refused(BUSY.into()));
}
diff --git a/crates/quince-icloud/src/lib.rs b/crates/quince-icloud/src/lib.rs
index 62ff3fb..dc820aa 100644
--- a/crates/quince-icloud/src/lib.rs
+++ b/crates/quince-icloud/src/lib.rs
@@ -3,6 +3,17 @@
//! These are reverse-engineered endpoints, not a published API. Every response is treated as
//! untrusted: a missing field or a malformed date returns an error, never a panic.
+/// What went wrong, said on the terminal in a development build only, and never with anything
+/// of the person's in it — no names, record ids, addresses or Apple's answers. A release build
+/// says nothing at all: Quince keeps no diagnostics and sends none anywhere.
+macro_rules! quiet {
+ ($($t:tt)*) => {
+ if cfg!(debug_assertions) {
+ eprintln!($($t)*);
+ }
+ };
+}
+
pub mod calendar;
pub mod ckdocument;
pub mod cloudkit;
@@ -33,6 +44,10 @@ pub enum Error {
ReauthRequired,
#[error("this changed on another device first — refresh and try again")]
Conflict,
+ /// The zone was mid-write for someone else and the change was not applied; it is sent
+ /// again (cloudkit's modify), and only reaches a person as Refused if it stays busy.
+ #[error("iCloud is busy right now. Nothing was changed — try again in a minute.")]
+ Busy,
/// Apple turned a request down, said in words a person can act on. What Apple actually
/// sent goes to the log, not the screen: a path and a JSON body told nobody anything.
#[error("{0}")]
diff --git a/crates/quince-media/src/lib.rs b/crates/quince-media/src/lib.rs
index d6fbaf9..19bb0a2 100644
--- a/crates/quince-media/src/lib.rs
+++ b/crates/quince-media/src/lib.rs
@@ -125,6 +125,61 @@ pub fn heic_to_jpeg(bytes: &[u8]) -> Result<Vec<u8>, String> {
Ok(out.into_inner())
}
+/// RGB rows (`stride` bytes apart) made a JPEG, as heic_to_jpeg makes one.
+///
+/// # Errors
+/// When the rows are shorter than the size says.
+pub fn rgb_to_jpeg(data: &[u8], w: u32, h: u32, stride: usize) -> Result<Vec<u8>, String> {
+ let row = w as usize * 3;
+ let mut rgb = Vec::with_capacity(row * h as usize);
+ for y in 0..h as usize {
+ rgb.extend_from_slice(
+ data.get(y * stride..y * stride + row)
+ .ok_or("the frame was cut short")?,
+ );
+ }
+ let picture = image::RgbImage::from_raw(w, h, rgb).ok_or("the picture had the wrong size")?;
+ let mut out = std::io::Cursor::new(Vec::new());
+ image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 90)
+ .encode_image(&picture)
+ .map_err(|e| e.to_string())?;
+ Ok(out.into_inner())
+}
+
+/// How light RGB rows are, 0–255 on average: a frame of nothing (a recording's black first
+/// frame) is near 0.
+#[must_use]
+pub fn rgb_lightness(data: &[u8], w: u32, h: u32, stride: usize) -> f64 {
+ let (mut sum, mut n) = (0u64, 0u64);
+ // Every fourth pixel of every fourth row is plenty to tell a picture from black.
+ for y in (0..h as usize).step_by(4) {
+ let Some(line) = data.get(y * stride..y * stride + w as usize * 3) else {
+ break;
+ };
+ for px in line.as_chunks::<3>().0.iter().step_by(4) {
+ sum += u64::from(px[0]) * 3 + u64::from(px[1]) * 6 + u64::from(px[2]);
+ n += 10;
+ }
+ }
+ if n == 0 {
+ 0.0
+ } else {
+ sum as f64 / n as f64
+ }
+}
+
+/// Whether a picture shows nothing: every part of it black, as Apple's poster for a video
+/// whose first frame is black (a screen recording's) is — 0.0 on average, to the last pixel.
+#[must_use]
+pub fn is_blank(bytes: &[u8]) -> bool {
+ let Ok(picture) = image::load_from_memory(bytes) else {
+ return false;
+ };
+ let gray = picture.to_luma8();
+ let brightest = gray.pixels().map(|p| p.0[0]).max().unwrap_or(0);
+ brightest < 24
+}
+
/// 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 {
diff --git a/probe/examples/contacts_dedupe_import.rs b/probe/examples/contacts_dedupe_import.rs
new file mode 100644
index 0000000..6036d7f
--- /dev/null
+++ b/probe/examples/contacts_dedupe_import.rs
@@ -0,0 +1,112 @@
+//! One-off repair of his own address book, done with his say-so (2026-10-20): a vCard export
+//! of it was imported back at 07:07 UTC that day, adding a copy of every contact. A contact is
+//! deleted here only when all three hold — Apple's import gave it its id (base64, 48 long),
+//! Apple made it inside that twelve-second burst, and an original (a UUID id) with exactly the
+//! same names, birthday, notes and methods is still in the book. One is deleted first and the
+//! book read again to see the original kept; then the rest. Pass `--go` to delete; without it,
+//! it only counts.
+use anyhow::{anyhow, Result};
+use quince_core::contacts::Contact;
+
+fn made_at(c: &Contact) -> Option<i64> {
+ i64::from_str_radix(c.etag.as_deref()?, 36).ok()
+}
+
+fn same(a: &Contact, b: &Contact) -> bool {
+ let methods = |c: &Contact| {
+ let mut m: Vec<_> = c
+ .methods
+ .iter()
+ .map(|m| {
+ (
+ m.kind.clone(),
+ m.label.clone().unwrap_or_default().to_lowercase(),
+ m.value.clone(),
+ )
+ })
+ .collect();
+ m.sort();
+ m
+ };
+ let t = |s: &Option<String>| s.clone().unwrap_or_default();
+ t(&a.first_name) == t(&b.first_name)
+ && t(&a.middle_name) == t(&b.middle_name)
+ && t(&a.last_name) == t(&b.last_name)
+ && t(&a.company) == t(&b.company)
+ && t(&a.birthday) == t(&b.birthday)
+ && t(&a.notes) == t(&b.notes)
+ && methods(a) == methods(b)
+}
+
+#[tokio::main]
+async fn main() -> Result<()> {
+ let go = std::env::args().any(|a| a == "--go");
+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");
+ let mut client = quince_auth::Client::new(&dir)?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let root = client
+ .session()
+ .service_url("contacts")
+ .ok_or_else(|| anyhow!("no contacts"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ use quince_icloud::contacts as c;
+ // 2026-10-20 07:07:00 – 07:07:30 UTC, in ms.
+ let (from, to) = (1_792_480_020_000_i64, 1_792_480_050_000_i64);
+ let pick = |book: &[Contact]| -> Vec<(Contact, String)> {
+ book.iter()
+ .filter(|x| x.guid.len() == 48 && made_at(x).is_some_and(|t| (from..=to).contains(&t)))
+ .filter_map(|x| {
+ book.iter()
+ .find(|o| o.guid.len() == 36 && same(o, x))
+ .map(|o| (x.clone(), o.guid.clone()))
+ })
+ .collect()
+ };
+ let (book, tokens) = c::fetch_with_tokens(&http, &root, p.clone()).await?;
+ let copies = pick(&book);
+ println!(
+ "book {}; copies with an exact original: {}",
+ book.len(),
+ copies.len()
+ );
+ if !go || copies.is_empty() {
+ return Ok(());
+ }
+ let (first, original) = &copies[0];
+ c::delete(&http, &root, p.clone(), &tokens, first).await?;
+ let (book2, mut tokens) = c::fetch_with_tokens(&http, &root, p.clone()).await?;
+ let kept = book2.iter().any(|x| &x.guid == original);
+ let gone = !book2.iter().any(|x| x.guid == first.guid);
+ println!("first: copy gone {gone}, original kept {kept}");
+ if !(kept && gone) {
+ return Err(anyhow!(
+ "stopped: the first delete did not do what it should"
+ ));
+ }
+ let mut done = 1;
+ for (copy, original) in pick(&book2) {
+ if !book2.iter().any(|x| x.guid == original) {
+ continue;
+ }
+ match c::delete(&http, &root, p.clone(), &tokens, &copy).await {
+ // Each delete moves the book's sync token on: read it before the next.
+ Ok(()) => {
+ done += 1;
+ tokens = c::fetch_with_tokens(&http, &root, p.clone()).await?.1;
+ }
+ Err(e) => {
+ eprintln!("{}: {e}; reading the book again", copy.guid);
+ tokens = c::fetch_with_tokens(&http, &root, p.clone()).await?.1;
+ }
+ }
+ }
+ let (book3, _) = c::fetch_with_tokens(&http, &root, p.clone()).await?;
+ println!(
+ "deleted {done}; book now {}; copies left {}",
+ book3.len(),
+ pick(&book3).len()
+ );
+ Ok(())
+}
diff --git a/probe/examples/contacts_import_known_live.rs b/probe/examples/contacts_import_known_live.rs
new file mode 100644
index 0000000..2a64a3b
--- /dev/null
+++ b/probe/examples/contacts_import_known_live.rs
@@ -0,0 +1,45 @@
+//! Live, throwaway contact only: "Quince dup test" imported once; the same card offered again
+//! is known as already in the book (contacts::already_in, as the app's import now checks) and
+//! so never sent; a card with a new number is not. Then the throwaway is deleted.
+use anyhow::{anyhow, Result};
+#[tokio::main]
+async fn main() -> Result<()> {
+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");
+ let mut client = quince_auth::Client::new(&dir)?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let root = client
+ .session()
+ .service_url("contacts")
+ .ok_or_else(|| anyhow!("no contacts"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ use quince_icloud::contacts as c;
+ let card = "BEGIN:VCARD\r\nVERSION:3.0\r\nN:test;Quince dup;;;\r\nFN:Quince dup test\r\nTEL;type=CELL:+1 555 0199\r\nEND:VCARD\r\n";
+ let (book, tokens) = c::fetch_with_tokens(&http, &root, p.clone()).await?;
+ println!("before: known {}", c::already_in(card, &book));
+ let (ids, _) = c::import_vcards(&http, &root, p.clone(), &tokens, card).await?;
+ let id = ids
+ .first()
+ .ok_or_else(|| anyhow!("nothing imported"))?
+ .clone();
+ let (book, tokens) = c::fetch_with_tokens(&http, &root, p.clone()).await?;
+ println!("after import: known {}", c::already_in(card, &book));
+ let other = card.replace("0199", "0123");
+ println!(
+ "same name, new number: known {}",
+ c::already_in(&other, &book)
+ );
+ let mine = book
+ .iter()
+ .find(|x| x.guid == id)
+ .ok_or_else(|| anyhow!("not in the book"))?;
+ c::delete(&http, &root, p.clone(), &tokens, mine).await?;
+ let (book, _) = c::fetch_with_tokens(&http, &root, p.clone()).await?;
+ println!(
+ "throwaway deleted: {}; book {}",
+ !book.iter().any(|x| x.guid == id),
+ book.len()
+ );
+ Ok(())
+}
diff --git a/probe/examples/notes_delete_many_live.rs b/probe/examples/notes_delete_many_live.rs
new file mode 100644
index 0000000..6faa462
--- /dev/null
+++ b/probe/examples/notes_delete_many_live.rs
@@ -0,0 +1,86 @@
+//! Live, throwaways only: three notes made, all three deleted at once (into Recently Deleted),
+//! then all three deleted at once from there — as he did when Apple answered 409
+//! TRY_AGAIN_LATER. Every delete should go through, the busy answers waited out.
+use anyhow::{anyhow, Result};
+use quince_icloud::notes as n;
+
+#[tokio::main]
+async fn main() -> Result<()> {
+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");
+ let mut client = quince_auth::Client::new(&dir)?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let root = client
+ .session()
+ .service_url("ckdatabasews")
+ .ok_or_else(|| anyhow!("no ck"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ let mut made = Vec::new();
+ for i in 1..=3 {
+ made.push(
+ n::create_cloudkit(
+ &http,
+ &root,
+ p.clone(),
+ None,
+ &format!("Quince delete test {i}\nthrowaway"),
+ None,
+ )
+ .await?,
+ );
+ }
+ println!("made {}", made.len());
+ let read = || async {
+ let mut lib = quince_core::Library::in_memory()?;
+ n::apply_cloudkit(
+ &mut lib,
+ n::fetch_cloudkit(&http, &root, p.clone(), None).await?,
+ )?;
+ anyhow::Ok(lib)
+ };
+ for round in ["to Recently Deleted", "for good"] {
+ let lib = read().await?;
+ let notes: Vec<_> = made
+ .iter()
+ .map(|g| lib.note(g))
+ .collect::<Result<Vec<_>, _>>()?
+ .into_iter()
+ .flatten()
+ .collect();
+ let all = futures_util::future::join_all(
+ notes
+ .iter()
+ .map(|note| n::delete_cloudkit(&http, &root, p.clone(), note)),
+ )
+ .await;
+ let failed: Vec<_> = all
+ .iter()
+ .filter_map(|r| r.as_ref().err())
+ .map(ToString::to_string)
+ .collect();
+ println!(
+ "{round}: {} of {} went through; {:?}",
+ all.len() - failed.len(),
+ all.len(),
+ failed
+ );
+ }
+ let lib = read().await?;
+ let left = made
+ .iter()
+ .filter(|g| lib.note(g).ok().flatten().is_some())
+ .count();
+ println!("still listed afterwards: {left}");
+ // Earlier runs' throwaways still in Recently Deleted, found by their own title only.
+ let stray: Vec<_> = lib
+ .notes_in(Some("TrashFolder-CloudKit"))?
+ .into_iter()
+ .filter(|x| x.title.starts_with("Quince delete test"))
+ .collect();
+ for note in &stray {
+ n::delete_cloudkit(&http, &root, p.clone(), note).await?;
+ }
+ println!("earlier throwaways cleared: {}", stray.len());
+ Ok(())
+}
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 4a7063f..c846b26 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -10,6 +10,11 @@ tauri-build = { version = "2", features = [] }
[dependencies]
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"
+gstreamer-app = "0.25"
+gstreamer-video = "0.25"
tauri = { version = "2", features = ["tray-icon", "image-png"] }
quince-auth = { path = "../crates/quince-auth" }
quince-core = { path = "../crates/quince-core" }
@@ -31,4 +36,5 @@ tauri-plugin-single-instance = "2"
libc = "0.2"
[dev-dependencies]
+image = { version = "0.25", default-features = false, features = ["jpeg"] }
tempfile = "3"
diff --git a/src-tauri/src/alerts.rs b/src-tauri/src/alerts.rs
index 7a22b78..578066c 100644
--- a/src-tauri/src/alerts.rs
+++ b/src-tauri/src/alerts.rs
@@ -206,7 +206,7 @@ fn show(app: AppHandle, due: DueAlarm) {
crate::set_done(&auth, &data, &due.reminder_guid, &due.list_guid, true)
.await
{
- eprintln!("could not complete {}: {e}", due.reminder_guid);
+ quiet!("an alert's reminder could not be completed: {e}");
}
// Every open screen looks again, as after any pass.
let report = crate::refresh::status(&data.0).await;
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 85fe60c..7842aa5 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -1,10 +1,22 @@
// Quince — desktop shell.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
+/// What went wrong, said on the terminal in a development build only, and never with anything
+/// of the person's in it — no names, record ids, addresses or Apple's answers. A release build
+/// says nothing at all: Quince keeps no diagnostics and sends none anywhere.
+macro_rules! quiet {
+ ($($t:tt)*) => {
+ if cfg!(debug_assertions) {
+ eprintln!($($t)*);
+ }
+ };
+}
+
mod alerts;
mod cpu;
mod outbox;
mod photos;
+mod poster;
mod push;
mod refresh;
mod video;
@@ -1364,7 +1376,7 @@ async fn reminder_edit(
)
.await
{
- eprintln!("a subtask did not follow its reminder: {e}");
+ quiet!("a subtask did not follow its reminder: {e}");
}
}
}
@@ -1516,7 +1528,7 @@ async fn reminder_list_delete(
/// upload. It is noted, and the next refresh brings the screen up to date.
fn settle(refreshed: Result<(), String>) -> Result<(), String> {
if let Err(e) = refreshed {
- eprintln!("refresh after a write: {e}");
+ quiet!("refresh after a write: {e}");
}
Ok(())
}
@@ -1768,7 +1780,7 @@ async fn note_save(
.map_err(|e| e.to_string())?;
// Apple has it; a refresh failing now must not read as the save failing.
if let Err(e) = resync_notes(&http, &root, params, &data).await {
- eprintln!("notes refresh after a save: {e}");
+ quiet!("notes refresh after a save: {e}");
}
// Apple accepted the body, but its change feed does not always carry our own write back
@@ -1830,7 +1842,7 @@ async fn note_create(
// Apple has made it. A refresh failing now must not read as the create failing — the
// editor would try again, and the person would have the note twice.
if let Err(e) = resync_notes(&http, &root, params, &data).await {
- eprintln!("notes refresh after a create: {e}");
+ quiet!("notes refresh after a create: {e}");
}
// Apple's change feed does not always carry a new record back on the very next pass.
@@ -2261,13 +2273,14 @@ async fn contacts_export(
Ok(path.to_string_lossy().into_owned())
}
-/// Add everyone in a vCard file to Contacts. Answers how many came in and how many could not.
+/// Add everyone in a vCard file to Contacts. Answers how many came in, how many could not be
+/// read, and how many were left out because they are in Contacts already.
#[tauri::command]
async fn contacts_import(
paths: Vec<String>,
auth: State<'_, Auth>,
data: State<'_, Data>,
-) -> UiResult<(usize, usize)> {
+) -> UiResult<(usize, usize, usize)> {
let _one = CONTACTS_PASS.lock().await;
// Every file chosen, vCard or CSV (Google Contacts, Outlook), read into cards first, so a
// file that cannot be read stops the import before anything is sent.
@@ -2294,9 +2307,17 @@ async fn contacts_import(
return Err("Those files hold no contacts.".into());
}
let (http, root, params) = contacts_context(&auth).await?;
- let (_, tokens) = quince_icloud::contacts::fetch_with_tokens(&http, &root, params.clone())
+ let (book, tokens) = quince_icloud::contacts::fetch_with_tokens(&http, &root, params.clone())
.await
.map_err(|e| e.to_string())?;
+ // Someone already in Contacts is left out, as Apple's Contacts leaves them: an export of
+ // this same book imported back once doubled every person in it.
+ let before = cards.len();
+ cards.retain(|card| !quince_icloud::contacts::already_in(card, &book));
+ let known = before - cards.len();
+ if cards.is_empty() {
+ return Ok((0, unreadable, known));
+ }
// In batches Apple takes in one import: well under its 10 MB, a few hundred cards each.
let mut imported = 0;
for batch in quince_icloud::contacts::batch_vcards(&cards, 8 * 1024 * 1024, 400) {
@@ -2308,7 +2329,7 @@ async fn contacts_import(
unreadable += failed;
}
settle(resync_contacts(&http, &root, params, &data).await)?;
- Ok((imported, unreadable))
+ Ok((imported, unreadable, known))
}
/// The card that is this person's own, as the last pass stored it.
@@ -3650,7 +3671,7 @@ fn main() {
.opener()
.open_url(url.as_str(), None::<&str>)
{
- eprintln!("could not open {url}: {e}");
+ quiet!("a link could not be opened: {e}");
}
}
inside
@@ -3810,7 +3831,7 @@ fn main() {
}
}
if let Err(e) = build_tray(app) {
- eprintln!("no tray on this desktop, so closing the window quits: {e}");
+ quiet!("no tray on this desktop, so closing the window quits: {e}");
}
show_when_ready(app.handle());
// Photos uploads a quit left half done carry on.
diff --git a/src-tauri/src/photos.rs b/src-tauri/src/photos.rs
index 7e3d00a..b61e82f 100644
--- a/src-tauri/src/photos.rs
+++ b/src-tauri/src/photos.rs
@@ -342,9 +342,76 @@ async fn from_apple(
if !done && !fetch(new_link(&http, &root, params, &photo, size).await?).await? {
return Err("Apple did not send that picture.".into());
}
+ // A video's poster that is black (Apple makes it from the first frame) is made again from
+ // the first frame that shows something, before anyone sees it.
+ if photo.kind == quince_core::photos::Kind::Video && matches!(size, Size::Thumb | Size::Medium)
+ {
+ repair_poster(app, id).await;
+ }
Ok(path)
}
+/// When a video's thumbnail is black, its first frame that is not (see `crate::poster`) made
+/// its thumbnail and screen-sized picture instead, at the sizes Apple's were, and every size
+/// made from the black one let go. Answers whether it was remade.
+pub async fn repair_poster(app: &AppHandle, id: &str) -> bool {
+ let thumb = cache_path(app, id, Size::Thumb);
+ let Ok(bytes) = tokio::fs::read(&thumb).await else {
+ return false;
+ };
+ if !crate::cpu::run(move || quince_media::is_blank(&bytes))
+ .await
+ .unwrap_or(false)
+ {
+ return false;
+ }
+ // The original when it is on disk already; otherwise the small rendition, a few megabytes.
+ let original = cache_path(app, id, Size::Original);
+ let film = if original.exists() {
+ original
+ } else {
+ match Box::pin(cached(app, id, Size::Video)).await {
+ Ok(path) => path,
+ Err(_) => return false,
+ }
+ };
+ let Ok(Ok(Some(frame))) = crate::cpu::run(move || crate::poster::first_seen_frame(&film)).await
+ else {
+ return false;
+ };
+ for size in [Size::Thumb, Size::Medium] {
+ let path = cache_path(app, id, size);
+ let old = tokio::fs::read(&path).await.unwrap_or_default();
+ let src = frame.clone();
+ // Apple's own sizes: the thumbnail's long side, and the screen-sized one's.
+ let long =
+ quince_media::long_side(&old).unwrap_or(if size == Size::Thumb { 512 } else { 2048 });
+ let Ok(Ok(made)) =
+ crate::cpu::run(move || quince_media::fit(&src, long).map(|m| m.unwrap_or(src))).await
+ else {
+ continue;
+ };
+ if let Some(dir) = path.parent() {
+ let _ = tokio::fs::create_dir_all(dir).await;
+ }
+ let part = path.with_extension("part");
+ if tokio::fs::write(&part, &made).await.is_ok() {
+ let _ = tokio::fs::rename(&part, &path).await;
+ }
+ }
+ for step in FITS {
+ let _ = tokio::fs::remove_file(
+ crate::state_dir(app)
+ .join("photos")
+ .join("fit")
+ .join(step.to_string())
+ .join(id),
+ )
+ .await;
+ }
+ true
+}
+
/// 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
@@ -363,6 +430,15 @@ pub fn keep_ahead(app: AppHandle) {
let library = data.0.lock().await;
library.photos(View::Library).unwrap_or_default()
};
+ // Videos whose black poster was kept before posters were remade: remade now, once.
+ for p in newest
+ .iter()
+ .filter(|p| p.kind == quince_core::photos::Kind::Video)
+ {
+ if cache_path(&app, &p.id, Size::Thumb).exists() {
+ crate::cpu::ahead(repair_poster(&app, &p.id)).await;
+ }
+ }
let wanted: Vec<(String, Size)> = newest
.into_iter()
.take(600)
@@ -1854,7 +1930,7 @@ async fn one(app: &AppHandle, u: quince_core::photos::Upload) -> bool {
return false;
}
Err(e) if attempt < 3 && !cancelled(&u) => {
- eprintln!("photos upload of {}: try {attempt} failed: {e}", u.name);
+ quiet!("photos upload: try {attempt} failed: {e}");
tokio::time::sleep(Duration::from_secs(2 * attempt)).await;
}
Err(e) => {
@@ -1916,7 +1992,7 @@ async fn into_album(
)
.ok();
}
- Err(e) => eprintln!("photos upload: {} not put in its album: {e}", u.name),
+ Err(e) => quiet!("photos upload: not put in its album: {e}"),
}
}
diff --git a/src-tauri/src/poster.rs b/src-tauri/src/poster.rs
new file mode 100644
index 0000000..34cf139
--- /dev/null
+++ b/src-tauri/src/poster.rs
@@ -0,0 +1,120 @@
+//! A video's picture when Apple's is blank.
+//!
+//! Apple makes a video's poster from its first frame, and a screen recording's first frame is
+//! black: in his library a 1:02 recording showed as a black square in the grid (its thumbnail
+//! 0.0 light to the last pixel) though its picture starts half a second in. Here the first
+//! frame that shows something is read from the video itself — upright, as the phone recorded
+//! it — and made the video's thumbnail and screen-sized picture in their place.
+
+use gstreamer as gst;
+use gstreamer::prelude::*;
+use gstreamer_app as gst_app;
+
+/// Where the poster is looked for: the start, then a little way in, then further.
+const LOOKS: [u64; 7] = [0, 250, 500, 1000, 2000, 4000, 8000];
+
+/// Average lightness (0–255) above which a frame shows something.
+const SEEN: f64 = 8.0;
+
+/// The first frame of the video at `path` that is not black, as a JPEG. `None` when every
+/// look finds black (a video of the dark is shown as it is).
+///
+/// # Errors
+/// When GStreamer cannot read the file.
+pub fn first_seen_frame(path: &std::path::Path) -> Result<Option<Vec<u8>>, String> {
+ gst::init().map_err(|e| e.to_string())?;
+ // videoflip's automatic direction turns the frame upright, as the phone's orientation tag
+ // says; the player does the same.
+ let pipeline = gst::parse::launch(
+ "filesrc name=src ! decodebin ! videoconvert ! videoflip video-direction=auto ! \
+ videoconvert ! video/x-raw,format=RGB ! appsink name=sink sync=false",
+ )
+ .map_err(|e| e.to_string())?
+ .downcast::<gst::Pipeline>()
+ .map_err(|_| "not a pipeline")?;
+ let src = pipeline.by_name("src").ok_or("no source")?;
+ src.set_property("location", path.to_string_lossy().as_ref());
+ let sink = pipeline
+ .by_name("sink")
+ .ok_or("no sink")?
+ .downcast::<gst_app::AppSink>()
+ .map_err(|_| "not an appsink")?;
+ let found = (|| {
+ pipeline
+ .set_state(gst::State::Paused)
+ .map_err(|e| e.to_string())?;
+ let (done, ..) = pipeline.state(gst::ClockTime::from_seconds(10));
+ done.map_err(|e| e.to_string())?;
+ for at in LOOKS {
+ if at > 0
+ && pipeline
+ .seek_simple(
+ gst::SeekFlags::FLUSH | gst::SeekFlags::ACCURATE,
+ gst::ClockTime::from_mseconds(at),
+ )
+ .is_err()
+ {
+ break;
+ }
+ let Some(sample) = sink.try_pull_preroll(gst::ClockTime::from_seconds(5)) else {
+ continue;
+ };
+ let (Some(buffer), Some(caps)) = (sample.buffer(), sample.caps()) else {
+ continue;
+ };
+ let info = gstreamer_video::VideoInfo::from_caps(caps).map_err(|e| e.to_string())?;
+ let map = buffer.map_readable().map_err(|e| e.to_string())?;
+ let (w, h) = (info.width(), info.height());
+ let stride = usize::try_from(info.stride()[0]).unwrap_or(0);
+ if quince_media::rgb_lightness(&map, w, h, stride) > SEEN {
+ return quince_media::rgb_to_jpeg(&map, w, h, stride).map(Some);
+ }
+ }
+ Ok(None)
+ })();
+ let _ = pipeline.set_state(gst::State::Null);
+ found
+}
+
+#[cfg(test)]
+mod tests {
+ /// A real video, given by path (QUINCE_POSTER_VIDEO): its poster's size and lightness.
+ #[test]
+ #[ignore = "needs a video on disk"]
+ fn a_real_video() {
+ let Ok(path) = std::env::var("QUINCE_POSTER_VIDEO") else {
+ return;
+ };
+ let jpeg = super::first_seen_frame(std::path::Path::new(&path))
+ .unwrap()
+ .expect("a frame");
+ let picture = image::load_from_memory(&jpeg).unwrap();
+ let gray = picture.to_luma8();
+ let mean = gray.pixels().map(|p| f64::from(p.0[0])).sum::<f64>()
+ / f64::from(gray.width() * gray.height());
+ println!(
+ "poster {}x{}, lightness {mean:.1}, blank {}",
+ picture.width(),
+ picture.height(),
+ quince_media::is_blank(&jpeg)
+ );
+ }
+
+ /// Half a second of black, then a picture, recorded turned a quarter (as a phone held
+ /// upright records): the poster is the picture, not the black, and stands upright.
+ #[test]
+ fn the_first_frame_that_shows_something_upright() {
+ let film =
+ std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/black-start.mp4");
+ let jpeg = super::first_seen_frame(&film)
+ .unwrap()
+ .expect("a frame that shows something");
+ assert!(!quince_media::is_blank(&jpeg), "not the black first frame");
+ let picture = image::load_from_memory(&jpeg).unwrap();
+ assert_eq!(
+ (picture.width(), picture.height()),
+ (48, 64),
+ "turned upright, as the phone recorded it"
+ );
+ }
+}
diff --git a/src-tauri/src/push.rs b/src-tauri/src/push.rs
index f830516..eba4971 100644
--- a/src-tauri/src/push.rs
+++ b/src-tauri/src/push.rs
@@ -96,7 +96,7 @@ async fn watch_contacts(
}
}
Err(e) => {
- eprintln!("contacts watch: {e}");
+ quiet!("contacts watch: {e}");
tokens = None;
tokio::time::sleep(backoff).await;
backoff = (backoff * 2).min(Duration::from_secs(5 * 60));
@@ -164,7 +164,7 @@ async fn watch_calendar(
seeded = true;
}
Err(e) => {
- eprintln!("calendar watch: {e}");
+ quiet!("calendar watch: {e}");
tokio::time::sleep(backoff).await;
backoff = (backoff * 2).min(Duration::from_secs(5 * 60));
}
@@ -222,7 +222,7 @@ async fn listen(client: Arc<Mutex<Client>>, tx: mpsc::UnboundedSender<&'static s
match quince_icloud::push::open(&http, &root, &params, &client_id, &containers).await {
Ok(channel) => channel,
Err(e) => {
- eprintln!("push: could not open the channel: {e}");
+ quiet!("push: could not open the channel: {e}");
tokio::time::sleep(backoff).await;
backoff = (backoff * 2).min(Duration::from_secs(5 * 60));
continue;
@@ -250,7 +250,7 @@ async fn listen(client: Arc<Mutex<Client>>, tx: mpsc::UnboundedSender<&'static s
Ok(None) => failures = 0,
Err(e) => {
failures += 1;
- eprintln!("push: the wait failed ({failures}): {e}");
+ quiet!("push: the wait failed ({failures}): {e}");
if failures >= 3 {
// Three in a row is a channel gone bad, not a blip: make a new one.
break;
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index cae1876..f506222 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -22,7 +22,8 @@
}
],
"security": {
- "csp": null
+ "csp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' quince: http://quince.localhost data: blob:; media-src 'self' quince: http://quince.localhost http://127.0.0.1:*; connect-src ipc: http://ipc.localhost; font-src 'self' data:; object-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'",
+ "devCsp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' quince: http://quince.localhost data: blob:; media-src 'self' quince: http://quince.localhost http://127.0.0.1:*; connect-src ipc: http://ipc.localhost ws://localhost:* http://localhost:*; font-src 'self' data:; object-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'"
}
},
"bundle": {
diff --git a/src-tauri/tests/fixtures/black-start.mp4 b/src-tauri/tests/fixtures/black-start.mp4
new file mode 100644
index 0000000..25c6ed2
Binary files /dev/null and b/src-tauri/tests/fixtures/black-start.mp4 differ
diff --git a/src/components/Portal.tsx b/src/components/Portal.tsx
index 9e2228a..21a54a8 100644
--- a/src/components/Portal.tsx
+++ b/src/components/Portal.tsx
@@ -1,13 +1,18 @@
import { createPortal } from "react-dom";
+import { useScreenActive } from "../lib/screen";
/**
* Menus, popovers and sheets are drawn at the top of the page, over everything, as a
* window server draws them. Inside a screen, any ancestor with a transform, filter or
* backdrop blur becomes what `position: fixed` is fixed to: a menu opened from Drive's grid
* came out the width of the screen, and File Info sat in a corner instead of the middle.
+ *
+ * Not drawn while its screen is out of sight (screens are kept once opened): a menu or sheet
+ * left open there comes back with it.
*/
export function Portal({ children }: { children: React.ReactNode }) {
- return createPortal(children, document.body);
+ const active = useScreenActive();
+ return active ? createPortal(children, document.body) : null;
}
/**
diff --git a/src/components/RowMenu.tsx b/src/components/RowMenu.tsx
index 954f7bf..24511fb 100644
--- a/src/components/RowMenu.tsx
+++ b/src/components/RowMenu.tsx
@@ -1,4 +1,5 @@
import { Portal } from "./Portal";
+import { useActiveRef } from "../lib/screen";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
/**
@@ -27,6 +28,7 @@ type Anchor = { x: number; y: number; alignRight: boolean };
* Choosing anything, at any depth, closes every level.
*/
export function RowMenu({ at, entries, onClose }: { at: Anchor; entries: MenuEntry[]; onClose: () => void }) {
+ const live = useActiveRef();
useEffect(() => {
// Any press outside every level of this menu dismisses it.
const down = (e: MouseEvent) => {
@@ -52,6 +54,7 @@ export function RowMenu({ at, entries, onClose }: { at: Anchor; entries: MenuEnt
// Escape closes the menu wherever the keys are: focus is not always in it — a submenu
// that closed under the pointer took the focus it held with it.
const key = (e: KeyboardEvent) => {
+ if (!live.current) return;
if (e.key !== "Escape" || (e.target as HTMLElement | null)?.closest?.(".row-menu")) return;
e.preventDefault();
e.stopPropagation();
diff --git a/src/lib/fade.ts b/src/lib/fade.ts
index bd6bd49..ee94a04 100644
--- a/src/lib/fade.ts
+++ b/src/lib/fade.ts
@@ -50,3 +50,31 @@ export function fadeSheetsIn() {
}
}).observe(document.body, { childList: true, subtree: true });
}
+
+/**
+ * A row folding away, drawn by the page the same way: each frame its height, padding and
+ * opacity set from here, so the rows below glide up. Then `done`.
+ */
+export function foldAway(el: HTMLElement, done: () => void, duration = 240) {
+ if (typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
+ done();
+ return;
+ }
+ const cs = getComputedStyle(el);
+ const h = el.getBoundingClientRect().height;
+ const [pt, pb] = [parseFloat(cs.paddingTop), parseFloat(cs.paddingBottom)];
+ el.style.overflow = "hidden";
+ const start = performance.now();
+ const step = (now: number) => {
+ const t = Math.min(1, (now - start) / duration);
+ // Quick at first, settling: Apple's own curve for things leaving.
+ const k = 1 - (1 - t) ** 3;
+ el.style.height = `${h * (1 - k)}px`;
+ el.style.paddingTop = `${pt * (1 - k)}px`;
+ el.style.paddingBottom = `${pb * (1 - k)}px`;
+ el.style.opacity = String(1 - k);
+ if (t < 1) requestAnimationFrame(step);
+ else done();
+ };
+ requestAnimationFrame(step);
+}
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index b2c0fa7..ffa945d 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -245,7 +245,8 @@ export const api = {
contactsExport: (guids: string[], fileName: string) => invoke<string>("contacts_export", { guids, fileName }),
/** Everyone in a vCard file, added to Contacts. Returns [added, could not be read]. */
/** vCard and CSV files, any number: [imported, could not be read]. */
- contactsImport: (paths: string[]) => invoke<[number, number]>("contacts_import", { paths }),
+ /** How many came in, could not be read, and were in Contacts already. */
+ contactsImport: (paths: string[]) => invoke<[number, number, number]>("contacts_import", { paths }),
/** The card that is this person's own, if they have said. */
contactMe: () => invoke<string | null>("contact_me"),
contactSetMe: (guid: string) => invoke<void>("contact_set_me", { guid }),
diff --git a/src/lib/screen.ts b/src/lib/screen.ts
new file mode 100644
index 0000000..2058800
--- /dev/null
+++ b/src/lib/screen.ts
@@ -0,0 +1,22 @@
+/**
+ * Whether the screen a component belongs to is the one showing. Screens are kept once opened
+ * (coming back to one is instant, and finds it as it was left — its place, its selection), so
+ * a screen out of sight is still mounted: its menus and sheets must not be drawn, and its keys
+ * must not answer, while another screen is in front.
+ */
+import { createContext, useContext, useEffect, useRef } from "react";
+
+export const ScreenActive = createContext(true);
+
+export const useScreenActive = () => useContext(ScreenActive);
+
+/** The same, as a ref, for listeners set up once and read when a key comes. */
+export function useActiveRef() {
+ const active = useScreenActive();
+ const ref = useRef(active);
+ ref.current = active;
+ useEffect(() => {
+ ref.current = active;
+ }, [active]);
+ return ref;
+}
diff --git a/src/screens/ContactsView.tsx b/src/screens/ContactsView.tsx
index 2c6b90c..043749c 100644
--- a/src/screens/ContactsView.tsx
+++ b/src/screens/ContactsView.tsx
@@ -208,9 +208,18 @@ export function ContactsView() {
const paths = !chosen ? [] : Array.isArray(chosen) ? chosen : [chosen];
if (paths.length === 0) return;
setBusy(true);
- const [added, failed] = await api.contactsImport(paths);
+ const [added, failed, known] = await api.contactsImport(paths);
await Promise.all([read(search), readLists()]);
- setDone(`${added} ${added === 1 ? "contact" : "contacts"} imported${failed ? `, ${failed} could not be read` : ""}.`);
+ const people = (n: number) => `${n} ${n === 1 ? "contact" : "contacts"}`;
+ setDone(
+ [
+ `${people(added)} imported`,
+ known ? `${people(known)} already in Contacts ${known === 1 ? "was" : "were"} left out` : "",
+ failed ? `${failed} could not be read` : "",
+ ]
+ .filter(Boolean)
+ .join(", ") + ".",
+ );
} catch (e) {
setError(messageOf(e));
} finally {
diff --git a/src/screens/DriveView.tsx b/src/screens/DriveView.tsx
index 3ae0b6b..83b09b0 100644
--- a/src/screens/DriveView.tsx
+++ b/src/screens/DriveView.tsx
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useRef, useState } from "react";
+import { useActiveRef } from "../lib/screen";
import { useSync } from "../lib/sync";
import { Notice } from "../components/Notice";
import { Portal } from "../components/Portal";
@@ -335,9 +336,10 @@ function kindName(item: DriveItem) {
/** File Info, as icloud.com shows it: the mark, the name, then what it is and where. */
function InfoSheet({ item, where, thumb, onClose }: { item: DriveItem; where: string; thumb?: string; onClose: () => void }) {
const done = useRef<HTMLButtonElement | null>(null);
+ const live = useActiveRef();
useEffect(() => {
const id = window.setTimeout(() => done.current?.focus(), 0);
- const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
+ const onKey = (e: KeyboardEvent) => live.current && e.key === "Escape" && onClose();
window.addEventListener("keydown", onKey);
return () => { window.clearTimeout(id); window.removeEventListener("keydown", onKey); };
}, [onClose]);
@@ -939,6 +941,9 @@ export function DriveView() {
return (
<div className={`drive${dropping ? " is-dropping" : ""}`}>
<header className="cal-bar">
+ {/* The folder's name with what is in it under it, as icloud.com writes them: one block
+ whose size never depends on when the count arrives, so the bar is laid out once. */}
+ <div className="drive-title">
<nav className="crumbs" aria-label="Folder path">
{trail.map((crumb, i) => (
<span key={crumb.id}>
@@ -972,15 +977,16 @@ export function DriveView() {
</span>
))}
</nav>
- {loaded && (
- // As icloud.com writes it under a folder's name: how much is in it.
- <p className="drive-count" aria-live="polite">
- {(() => {
- const n = items.filter((x) => !gone.has(x.drivewsid)).length;
- return `${n} item${n === 1 ? "" : "s"}${available ? `, ${available} available` : ""}`;
- })()}
- </p>
- )}
+ {/* How much is in it; its line is kept while it loads, so nothing moves when it comes. */}
+ <p className="drive-count" aria-live="polite">
+ {loaded
+ ? (() => {
+ const n = items.filter((x) => !gone.has(x.drivewsid)).length;
+ return `${n} item${n === 1 ? "" : "s"}${available ? `, ${available} available` : ""}`;
+ })()
+ : "\u00a0"}
+ </p>
+ </div>
<div className="cal-actions">
<button className="quiet with-glyph" title="Recents" onClick={() => setInRecents(true)}>
<Clock size={15} strokeWidth={1.6} aria-hidden="true" />
@@ -1350,8 +1356,10 @@ function MoveDialog({
// A sheet is modal: Escape leaves it exactly as Cancel would, and it must not be possible
// to tab out into the page still open underneath.
+ const live = useActiveRef();
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
+ if (!live.current) return;
if (e.key === "Escape") onCancel();
};
document.addEventListener("keydown", onKey);
diff --git a/src/screens/Library.tsx b/src/screens/Library.tsx
index b2e7df4..d0636d6 100644
--- a/src/screens/Library.tsx
+++ b/src/screens/Library.tsx
@@ -27,6 +27,7 @@ const DriveView = lazy(loaders.drivews);
const PhotosView = lazy(loaders.photos);
const SettingsView = lazy(loaders.settings);
import { ScreenBoundary } from "../components/ScreenBoundary";
+import { ScreenActive } from "../lib/screen";
import { AppIcon } from "../components/AppIcon";
/**
@@ -147,6 +148,27 @@ export function Library({ onSignOut }: { onSignOut: () => void }) {
return () => window.clearTimeout(t);
}, [ready]);
+ // The screens opened so far, in the order they were first opened.
+ const keptRef = useRef<string[]>([]);
+ if (webAccess !== false && selected && SCREENS.some((s) => s.key === selected) && !keptRef.current.includes(selected)) {
+ keptRef.current = [...keptRef.current, selected];
+ }
+ const kept = keptRef.current;
+ const screenFor = (key: string) =>
+ key === "calendar" ? (
+ <CalendarView />
+ ) : key === "reminders" ? (
+ <RemindersView />
+ ) : key === "notes" ? (
+ <NotesView />
+ ) : key === "contacts" ? (
+ <ContactsView />
+ ) : key === "photos" ? (
+ <PhotosView />
+ ) : (
+ <DriveView />
+ );
+
const choose = (key: string) => {
setSelected(key);
setSidebarOpen(false);
@@ -271,39 +293,38 @@ export function Library({ onSignOut }: { onSignOut: () => void }) {
again.
</p>
</div>
- ) : selected === "settings" ? (
- <ScreenBoundary key="settings" name="Settings">
- <Suspense fallback={null}>
- <SettingsView onSignOut={onSignOut} />
- </Suspense>
- </ScreenBoundary>
- ) : selected && SCREENS.some((s) => s.key === selected) ? (
- // Keyed by screen, so moving to another screen also clears a failed one.
- <ScreenBoundary key={selected} name={SCREENS.find((s) => s.key === selected)?.name ?? "This screen"}>
- <Suspense fallback={null}>
- {selected === "calendar" ? (
- <CalendarView />
- ) : selected === "reminders" ? (
- <RemindersView />
- ) : selected === "notes" ? (
- <NotesView />
- ) : selected === "contacts" ? (
- <ContactsView />
- ) : selected === "photos" ? (
- <PhotosView />
- ) : (
- <DriveView />
- )}
- </Suspense>
- </ScreenBoundary>
) : (
- ready &&
- services.length === 0 && (
- <p className="cal-empty">
- Apple hasn’t offered Reminders, Notes, iCloud Drive, Calendar or Contacts to
- this account yet.
- </p>
- )
+ <>
+ {selected === "settings" && (
+ <ScreenBoundary key="settings" name="Settings">
+ <Suspense fallback={null}>
+ <SettingsView onSignOut={onSignOut} />
+ </Suspense>
+ </ScreenBoundary>
+ )}
+ {/* Each screen is kept once opened, out of sight while another is in front:
+ coming back is instant, and finds it as it was left — its place, its
+ selection, its scroll — as a Mac app's windows are. Out of sight it is inert,
+ draws no menus and answers no keys (lib/screen). */}
+ {kept.map((key) => {
+ const on = key === selected;
+ return (
+ <div key={key} className="screen-slot" hidden={!on} {...(on ? {} : { inert: "" })}>
+ <ScreenActive.Provider value={on}>
+ <ScreenBoundary name={SCREENS.find((s) => s.key === key)?.name ?? "This screen"}>
+ <Suspense fallback={null}>{screenFor(key)}</Suspense>
+ </ScreenBoundary>
+ </ScreenActive.Provider>
+ </div>
+ );
+ })}
+ </>
+ )}
+ {ready && services.length === 0 && (
+ <p className="cal-empty">
+ Apple hasn’t offered Reminders, Notes, iCloud Drive, Calendar or Contacts to
+ this account yet.
+ </p>
)}
</main>
</div>
diff --git a/src/screens/PhotosView.tsx b/src/screens/PhotosView.tsx
index 9d52afa..da29a61 100644
--- a/src/screens/PhotosView.tsx
+++ b/src/screens/PhotosView.tsx
@@ -3,6 +3,7 @@
* for how many across; a photo opens on a dark stage with the arrows to go through them. Everything draws from the local library at once; thumbnails come
* from the disk cache and are fetched once.
*/
+import { useActiveRef } from "../lib/screen";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { listen } from "@tauri-apps/api/event";
import { getCurrentWebview } from "@tauri-apps/api/webview";
@@ -961,6 +962,8 @@ export function PhotosView() {
const el = stage.current;
if (!el) return undefined;
const measure = () => {
+ // Out of sight (another screen in front) it has no box: nothing to measure.
+ if (!el.clientWidth) return;
const cs = getComputedStyle(el);
stageBox = {
w: el.clientWidth - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight),
@@ -1011,10 +1014,12 @@ export function PhotosView() {
}, [open, photos]);
// The viewer's keys: arrows to go through, Escape to close, I for the details.
+ const live = useActiveRef();
useEffect(() => {
if (open === null) return undefined;
const current = photos?.[open] ?? null;
const onKey = (e: KeyboardEvent) => {
+ if (!live.current) return;
// Keys typed into a field — the caption — are words, not commands.
if ((e.target as HTMLElement | null)?.closest?.("input:not([type=range]), textarea, [contenteditable]")) return;
// The zoom slider's own arrows move it; every other key still works with it focused.
@@ -1334,6 +1339,7 @@ export function PhotosView() {
useEffect(() => {
if (open !== null) return undefined;
const onKey = (e: KeyboardEvent) => {
+ if (!live.current) return;
const t = e.target as HTMLElement | null;
if (t?.closest?.("input, textarea, [contenteditable], .row-menu, [role=dialog]") || naming) return;
const list = photos ?? [];
@@ -1852,6 +1858,7 @@ export function PhotosView() {
// Zoom from the keys as in Photos: Ctrl and + or −.
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
+ if (!live.current) return;
if (!(e.ctrlKey || e.metaKey) || e.altKey || viewer.current) return;
if (e.key === "=" || e.key === "+") setZoom((z) => Math.min(ACROSS.length - 1, z + 1));
else if (e.key === "-") setZoom((z) => Math.max(0, z - 1));
@@ -1911,6 +1918,7 @@ export function PhotosView() {
const measure = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
+ if (!el.clientWidth) return;
const h = `${Math.ceil(el.getBoundingClientRect().height)}px`;
if (main.style.getPropertyValue("--bar") !== h) main.style.setProperty("--bar", h);
});
@@ -1926,7 +1934,9 @@ export function PhotosView() {
useLayoutEffect(() => {
const el = scroller.current;
if (!el) return undefined;
- const measure = () => setGridWidth(Math.ceil(el.clientWidth / 32) * 32);
+ // Never measured while out of sight: with no width, the grid laid itself out empty and lost
+ // its place.
+ const measure = () => el.clientWidth && setGridWidth(Math.ceil(el.clientWidth / 32) * 32);
measure();
const watch = new ResizeObserver(measure);
watch.observe(el);
diff --git a/src/screens/RemindersView.tsx b/src/screens/RemindersView.tsx
index e79cd46..bf869ce 100644
--- a/src/screens/RemindersView.tsx
+++ b/src/screens/RemindersView.tsx
@@ -1,4 +1,6 @@
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { foldAway } from "../lib/fade";
+import { useActiveRef } from "../lib/screen";
import { listen } from "@tauri-apps/api/event";
import { usePending } from "../lib/pending";
import { Notice } from "../components/Notice";
@@ -408,21 +410,11 @@ export function RemindersView() {
window.setTimeout(() => {
setLeaving((was) => new Set(was).add(guid));
const row = document.querySelector<HTMLElement>(`.rx-row[data-guid="${CSS.escape(guid)}"]`);
- const still = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
- if (!row || still || typeof row.animate !== "function") {
- setDeparted((was) => new Set(was).add(guid));
- return;
- }
- const h = row.getBoundingClientRect().height;
- const cs = getComputedStyle(row);
- const fold = row.animate(
- [
- { height: `${h}px`, paddingTop: cs.paddingTop, paddingBottom: cs.paddingBottom, opacity: 1 },
- { height: "0px", paddingTop: "0px", paddingBottom: "0px", opacity: 0 },
- ],
- { duration: 240, easing: "cubic-bezier(0.32, 0.72, 0, 1)", fill: "forwards" },
- );
- fold.onfinish = () => setDeparted((was) => new Set(was).add(guid));
+ const gone = () => setDeparted((was) => new Set(was).add(guid));
+ // Folded by the page, frame by frame (lib/fade): handed to the compositor, as the Web
+ // Animations API hands it, an animation flickered on his screen.
+ if (!row) gone();
+ else foldAway(row, gone);
}, 600),
]);
};
@@ -435,10 +427,10 @@ export function RemindersView() {
const ticks = useRef(new Map<string, Promise<unknown>>());
const toggle = (r: Reminder) => {
const wasOpen = !r.completedAt;
- // Shown at once, every time, even while an earlier tick of this one is on its way.
- if (repeatLabel(r) === null) {
- setItems(patch(r.guid, { completedAt: wasOpen ? Math.floor(Date.now() / 1000) : null }));
- }
+ // Shown at once, every time, even while an earlier tick of this one is on its way — a
+ // repeating one too: its circle fills now, and it rolls on to its next date when Apple
+ // has made it (waiting for that, a tick on one showed nothing at all for a second or two).
+ setItems(patch(r.guid, { completedAt: wasOpen ? Math.floor(Date.now() / 1000) : null }));
// Only where completed reminders are hidden, and never for a repeating one, which rolls on.
if (wasOpen && !showDone && repeatLabel(r) === null) depart(r.guid);
else stay(r.guid);
@@ -453,10 +445,9 @@ export function RemindersView() {
const fresh = await write(
r,
() => api.reminderSetDone(r.guid, r.listGuid, wasOpen),
- // A repeating one rolls on rather than closing, so only Apple's answer can show it.
- repeatLabel(r) === null
- ? patch(r.guid, { completedAt: wasOpen ? Math.floor(Date.now() / 1000) : null })
- : undefined,
+ // Held over any refresh until Apple has it. A repeating one then comes back from Apple
+ // rolled on, open again with its next date.
+ patch(r.guid, { completedAt: wasOpen ? Math.floor(Date.now() / 1000) : null }),
);
if (!fresh) stay(r.guid);
if (!fresh || !wasOpen || repeatLabel(r) === null) return;
@@ -1584,8 +1575,9 @@ function ListInfo({ list, onClose, onDone }: {
const current = LIST_COLOURS.find((c) => c.hex.toLowerCase() === (list.colour ?? "").toLowerCase())?.key ?? null;
const [colour, setColour] = useState<string | null>(current);
const shown = LIST_COLOURS.find((c) => c.key === colour)?.hex ?? list.colour ?? "#007AFF";
+ const live = useActiveRef();
useEffect(() => {
- const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
+ const onKey = (e: KeyboardEvent) => live.current && e.key === "Escape" && onClose();
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [onClose]);
diff --git a/src/screens/calendar/CalendarView.tsx b/src/screens/calendar/CalendarView.tsx
index aa43ba2..01c4a1b 100644
--- a/src/screens/calendar/CalendarView.tsx
+++ b/src/screens/calendar/CalendarView.tsx
@@ -1,4 +1,5 @@
import { Notice } from "../../components/Notice";
+import { useActiveRef } from "../../lib/screen";
import { usePending } from "../../lib/pending";
import { inMenu, Portal } from "../../components/Portal";
import { TimeField } from "../../components/TimeField";
@@ -451,9 +452,11 @@ export function CalendarView() {
* as the whole series.
*/
const [asking, setAsking] = useState<{ verb: "change" | "delete"; answer: (scope: EventScope | null) => void } | null>(null);
+ const live = useActiveRef();
useEffect(() => {
if (!asking) return undefined;
const onKey = (e: KeyboardEvent) => {
+ if (!live.current) return;
if (e.key === "Escape") {
e.stopPropagation();
asking.answer(null);
@@ -629,6 +632,7 @@ export function CalendarView() {
// Keyboard, as in Calendar on a Mac (Ctrl here): arrows page, T today, 1–4 the views, N an event.
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
+ if (!live.current) return;
const typing = (e.target as HTMLElement | null)?.closest("input, textarea, select, [contenteditable]");
// Find, as everywhere on a Mac: ⌘F (Ctrl+F here) goes to the search field.
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "f") {
@@ -1180,6 +1184,9 @@ function MonthView({
const el = grid.current;
if (!el) return undefined;
const measure = () => {
+ // Out of sight (another screen in front) it has no box: kept as it was, so it comes
+ // back as it was rather than with one row a day for a frame.
+ if (!el.clientWidth) return;
const week = el.firstElementChild as HTMLElement | null;
const height = week?.getBoundingClientRect().height ?? 0;
const width = (week?.firstElementChild as HTMLElement | null)?.getBoundingClientRect().width ?? 0;
@@ -1450,6 +1457,7 @@ function TimeGrid({
const handlers = useRef({ follow, finish });
handlers.current = { follow, finish };
const dragging = drag !== null;
+ const live = useActiveRef();
useEffect(() => {
if (!dragging) return undefined;
const move = (e: PointerEvent) => {
@@ -1458,7 +1466,7 @@ function TimeGrid({
};
const up = (e: PointerEvent | MouseEvent) => handlers.current.finish(e.clientX, e.clientY);
const drop = () => setDragNow(null);
- const key = (e: KeyboardEvent) => e.key === "Escape" && drop();
+ const key = (e: KeyboardEvent) => live.current && e.key === "Escape" && drop();
window.addEventListener("pointermove", move);
window.addEventListener("pointerup", up);
window.addEventListener("mouseup", up);
@@ -1877,8 +1885,10 @@ function EventPopover({
setPos({ left, top });
}, [at]);
+ const live = useActiveRef();
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
+ if (!live.current) return;
if (e.key === "Escape") return onClose();
// Up/Down: fifteen minutes in Day and Week, a week in Month. Left/Right: a day.
if (e.ctrlKey && e.altKey && onNudge && editable && e.key.startsWith("Arrow")) {
diff --git a/src/screens/notes/FormatPanel.tsx b/src/screens/notes/FormatPanel.tsx
index b754d71..630d099 100644
--- a/src/screens/notes/FormatPanel.tsx
+++ b/src/screens/notes/FormatPanel.tsx
@@ -1,4 +1,5 @@
import { useEffect, useLayoutEffect, useRef, useState } from "react";
+import { useActiveRef } from "../../lib/screen";
import { Check } from "lucide-react";
import { inMenu, Portal } from "../../components/Portal";
import type { EditorStatus } from "./NoteEditor";
@@ -51,12 +52,13 @@ export function FormatPanel({
const top = at.y + height > window.innerHeight - 8 ? Math.max(8, window.innerHeight - height - 8) : at.y;
setPos({ left, top });
}, [at]);
+ const live = useActiveRef();
useEffect(() => {
const down = (e: MouseEvent) => {
const t = e.target as HTMLElement;
if (!box.current?.contains(t) && !t.closest(".notes-aa") && !inMenu(t)) onClose();
};
- const key = (e: KeyboardEvent) => e.key === "Escape" && onClose();
+ const key = (e: KeyboardEvent) => live.current && e.key === "Escape" && onClose();
document.addEventListener("mousedown", down);
window.addEventListener("keydown", key);
window.addEventListener("resize", onClose);
diff --git a/src/screens/photos/AdjustDate.tsx b/src/screens/photos/AdjustDate.tsx
index 5be0999..43eee64 100644
--- a/src/screens/photos/AdjustDate.tsx
+++ b/src/screens/photos/AdjustDate.tsx
@@ -2,6 +2,7 @@
* Adjust Date and Time, as icloud.com's: the photo, the timezone the times are in, the original
* date, and the one to give it — to the second. Save only once it is a different, real date.
*/
+import { useActiveRef } from "../../lib/screen";
import { useEffect, useState } from "react";
import { X } from "lucide-react";
import { pictureSrc, type Photo } from "../../lib/ipc";
@@ -20,8 +21,10 @@ const zone = () => {
export function AdjustDate({ photo, onSave, onClose }: { photo: Photo; onSave: (takenAt: number) => void; onClose: () => void }) {
const [value, setValue] = useState(() => local(photo.takenAt));
+ const live = useActiveRef();
useEffect(() => {
const key = (e: KeyboardEvent) => {
+ if (!live.current) return;
if (e.key !== "Escape") return;
e.preventDefault();
e.stopPropagation();
diff --git a/src/screens/photos/DownloadOptions.tsx b/src/screens/photos/DownloadOptions.tsx
index 3a53934..59905a0 100644
--- a/src/screens/photos/DownloadOptions.tsx
+++ b/src/screens/photos/DownloadOptions.tsx
@@ -3,6 +3,7 @@
* as captured or imported — and, including edits, Highest Resolution or Most Compatible. Each
* row downloads at once; Escape or × closes.
*/
+import { useActiveRef } from "../../lib/screen";
import { useEffect } from "react";
import { Download, X } from "lucide-react";
import { pictureSrc, type Photo } from "../../lib/ipc";
@@ -10,8 +11,10 @@ import { pictureSrc, type Photo } from "../../lib/ipc";
export type Want = "originals" | "highestQuality" | "mostCompatible";
export function DownloadOptions({ photos, onPick, onClose }: { photos: Photo[]; onPick: (want: Want) => void; onClose: () => void }) {
+ const live = useActiveRef();
useEffect(() => {
const key = (e: KeyboardEvent) => {
+ if (!live.current) return;
if (e.key !== "Escape") return;
e.preventDefault();
e.stopPropagation();
diff --git a/src/screens/photos/JumpTo.tsx b/src/screens/photos/JumpTo.tsx
index a047373..c1537fe 100644
--- a/src/screens/photos/JumpTo.tsx
+++ b/src/screens/photos/JumpTo.tsx
@@ -3,6 +3,7 @@
* year's months as tiles with a photo from each, in the calendar's order. A tile takes the grid
* to that month. Only months the library has photos in are offered.
*/
+import { useActiveRef } from "../../lib/screen";
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { fitSrc, type Photo } from "../../lib/ipc";
import { Portal } from "../../components/Portal";
@@ -36,12 +37,14 @@ export function JumpTo({
// Once, before its first frame is painted: run after it, the picker showed whole for a frame
// and then began its fade from nothing — a flash.
useLayoutEffect(() => fadeIn(box.current, { duration: 140 }), []);
+ const live = useActiveRef();
useEffect(() => {
box.current?.focus({ preventScroll: true });
const down = (e: MouseEvent) => {
if (!box.current?.contains(e.target as Node)) onClose();
};
const key = (e: KeyboardEvent) => {
+ if (!live.current) return;
if (e.key !== "Escape") return;
e.preventDefault();
e.stopPropagation();
diff --git a/src/screens/photos/Slideshow.tsx b/src/screens/photos/Slideshow.tsx
index 8b6d699..30da232 100644
--- a/src/screens/photos/Slideshow.tsx
+++ b/src/screens/photos/Slideshow.tsx
@@ -9,6 +9,7 @@
* one leaving fades out as the next fades in — before, it stood whole behind the next for the
* length of the fade, its edges showing round a narrower photo, and then vanished at once.
*/
+import { useActiveRef } from "../../lib/screen";
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { ChevronLeft, ChevronRight, Pause, Play, X } from "lucide-react";
import { fitSrc, type Photo } from "../../lib/ipc";
@@ -83,8 +84,10 @@ export function Slideshow({ photos, start, onClose }: { photos: Photo[]; start:
if (next) void decode(screenSrc(next));
}, [at, list]);
+ const live = useActiveRef();
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
+ if (!live.current) return;
if (e.key === "Escape") onClose();
else if (e.key === " ") setPlaying((p) => !p);
else if (e.key === "ArrowRight") go(1);
diff --git a/src/screens/photos/VideoPlayer.tsx b/src/screens/photos/VideoPlayer.tsx
index 6bf305c..be38d86 100644
--- a/src/screens/photos/VideoPlayer.tsx
+++ b/src/screens/photos/VideoPlayer.tsx
@@ -7,6 +7,7 @@
* The scrubber follows the film every frame (the engine's own timeupdate comes four times a
* second, and a progress bar that jumps reads as a stutter), and dragging it seeks as it goes.
*/
+import { useActiveRef, useScreenActive } from "../../lib/screen";
import { useCallback, useEffect, useRef, useState } from "react";
import { Pause, Play, Volume2, VolumeX } from "lucide-react";
@@ -41,6 +42,11 @@ export function VideoPlayer({
const [awake, setAwake] = useState(true);
const [hover, setHover] = useState<{ x: number; t: number } | null>(null);
const dragging = useRef(false);
+ // Another screen brought to the front pauses it, as leaving a film does on a Mac.
+ const active = useScreenActive();
+ useEffect(() => {
+ if (!active) film.current?.pause();
+ }, [active]);
// Where it is, drawn straight to the scrubber and the clocks once a frame — never through
// React, so a playing film redraws nothing else.
@@ -81,8 +87,10 @@ export function VideoPlayer({
else v.pause();
}, []);
// Space plays and pauses, before the viewer's own keys.
+ const live = useActiveRef();
useEffect(() => {
const key = (e: KeyboardEvent) => {
+ if (!live.current) return;
if (e.key !== " " || (e.target as HTMLElement | null)?.closest?.("input, textarea, [contenteditable]")) return;
e.preventDefault();
e.stopPropagation();
diff --git a/src/styles/app.css b/src/styles/app.css
index 864bab7..2ddbb24 100644
--- a/src/styles/app.css
+++ b/src/styles/app.css
@@ -407,7 +407,7 @@
gap: 10px;
min-height: 34px;
white-space: nowrap;
- transition: background 120ms ease, transform 120ms ease;
+ transition: background 120ms ease;
width: 100%;
border: 0;
background: none;
@@ -1227,7 +1227,7 @@
* date beneath it, and the row's actions float over its far end when it is pointed at rather
* than holding a strip of the width empty when it is not.
*/
-@media (max-width: 720px) {
+@container (max-width: 560px) {
.drive-row { position: relative; }
.drive-row-hit {
grid-template-columns: 28px auto minmax(0, 1fr);
@@ -1239,12 +1239,12 @@
padding: 7px 8px;
}
.drive-row-hit > .drive-badge { margin-right: 10px; }
- .drive-row-hit > .drive-meta:nth-of-type(3):not(:empty) { margin-right: 4px; }
+ .drive-row-hit > .drive-meta:not(.drive-kind):not(:last-child):not(:empty) { margin-right: 4px; }
.drive-row-hit > .drive-badge { grid-area: badge; }
.drive-row-hit > .drive-name { grid-area: name; }
- .drive-row-hit > .drive-meta:nth-of-type(3) { grid-area: size; }
+ .drive-row-hit > .drive-meta:not(.drive-kind):not(:last-child) { grid-area: size; }
.drive-row-hit > .drive-meta:last-child { grid-area: date; }
- .drive-row-hit > .drive-meta:nth-of-type(3):not(:empty)::after { content: " ·"; }
+ .drive-row-hit > .drive-meta:not(.drive-kind):not(:last-child):not(:empty)::after { content: " ·"; }
.drive-row-actions {
width: auto;
position: absolute;
@@ -1893,20 +1893,37 @@
.drive-col.is-on { color: var(--text-2); font-weight: 600; }
.drive-col:hover { color: var(--text); }
.drive-kind { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
-@media (max-width: 900px) { .drive-kind, .drive-col:nth-of-type(2) { display: none; } .drive-row-hit { grid-template-columns: 40px minmax(0, 1fr) 80px 110px; } }
/* Drive's bar: the path and its count stay one line and give way first; the controls wrap
beneath only when the window is too narrow for both. At 760px the title broke in two and
ran into its own count. */
.drive > .cal-bar { flex-wrap: wrap; row-gap: 10px; }
.drive > .cal-bar .crumbs { flex-wrap: nowrap; overflow: hidden; }
.drive > .cal-bar .crumb { white-space: nowrap; }
-.drive > .cal-bar .drive-count { flex: 1 1 auto; margin-left: 10px; }
-.drive > .cal-bar .cal-actions { flex-wrap: wrap; justify-content: flex-end; }
-@media (max-width: 900px) {
- /* Icons alone, their names kept for anyone who cannot see them. */
- .drive > .cal-bar .with-glyph:not(.primary) { font-size: 0; gap: 0; padding-inline: 8px; }
+.drive > .cal-bar .drive-title { display: flex; flex-direction: column; gap: 2px; flex: 1 1 auto; min-width: 0; }
+/* The name's first letter in line with its count's. */
+.drive > .cal-bar .drive-title .crumbs { margin-left: -5px; }
+.drive > .cal-bar .drive-count { margin: 0; overflow: hidden; text-overflow: ellipsis; }
+.drive > .cal-bar .cal-actions { flex-wrap: wrap; justify-content: flex-end; gap: 8px; }
+/* Sized by Drive's own width, not the window's: half a screen, a folded sidebar, a wide
+ one — each lays out the same for the same room. */
+.drive { container-type: inline-size; }
+@container (max-width: 880px) {
+ /* Too narrow for the named controls beside the name: icons alone, their names kept for
+ anyone who cannot see them (title, aria). */
+ .drive > .cal-bar .with-glyph:not(.primary) { font-size: 0; gap: 0; padding-inline: 9px; }
.drive > .cal-bar .with-glyph:not(.primary) svg { font-size: initial; }
}
+/* Narrower, the kind column goes (above the narrowest, which sets rows as Files on iPhone). */
+@container (min-width: 561px) and (max-width: 640px) {
+ .drive-kind, .drive-col:nth-of-type(2) { display: none; }
+ .drive-row-hit { grid-template-columns: 40px minmax(0, 1fr) 80px 110px; }
+}
+@container (max-width: 560px) {
+ /* Too narrow for both: the controls go under the name, starting at its edge. */
+ .drive > .cal-bar .cal-actions { width: 100%; justify-content: flex-start; }
+ /* Rows set as Files on iPhone sets them have no columns to head; the sort menu stays. */
+ .drive-head { display: none; }
+}
.drive-meta.is-soon { color: var(--sys-red, #ff453a); }
@@ -2069,3 +2086,8 @@
@keyframes upload-finding { from { transform: translateX(-10%); } to { transform: translateX(240%); } }
.upload-bar.is-waiting > span { transform: none; }
@media (prefers-reduced-motion: reduce) { .upload-bar.is-waiting > span { animation: none; width: 100%; opacity: 0.4; } }
+
+/* A kept screen's box is the screen's own (it lays out as before, straight in the content);
+ one out of sight is not drawn at all. */
+.screen-slot { display: contents; }
+.screen-slot[hidden] { display: none !important; }
diff --git a/src/styles/calendar.css b/src/styles/calendar.css
index 44944d9..0e7f8c3 100644
--- a/src/styles/calendar.css
+++ b/src/styles/calendar.css
@@ -327,7 +327,7 @@
position: relative; flex: none; width: 10px; height: 10px; padding: 0; margin: 0;
border: 1.3px solid var(--cal, var(--text-3)); border-radius: 50%; box-sizing: border-box;
background: none; box-shadow: none; cursor: pointer;
- transition: background 140ms ease, border-color 140ms ease, transform 140ms ease;
+ transition: background 140ms ease, border-color 140ms ease;
}
/* A target a finger or a trackpad can find, larger than the ring it draws. */
.cx-ring::before { content: ""; position: absolute; inset: -6px; }
diff --git a/src/styles/notes.css b/src/styles/notes.css
index 915a3e7..1807503 100644
--- a/src/styles/notes.css
+++ b/src/styles/notes.css
@@ -262,7 +262,9 @@ textarea.note-title::placeholder { color: var(--text-3); }
position: absolute; right: 6px; display: grid; place-items: center; width: 22px; height: 22px;
padding: 0; border: 0; border-radius: 50%; background: color-mix(in srgb, var(--text) 12%, transparent);
box-shadow: none; color: var(--text); font-size: 8px; letter-spacing: 1px; opacity: 0; cursor: pointer;
- transition: opacity 120ms ease;
+ /* Shown and hidden at once, never faded: a fade here is the compositor's, and flickered on
+ his screen as the pointer crossed the rows. (Opacity, not visibility: hidden, it could
+ not be reached with Tab.) */
}
.notes-folder-row:hover .notes-folder-more, .notes-folder-row.is-menu .notes-folder-more,
.notes-folder-more:focus-visible { opacity: 1; }
diff --git a/src/styles/photos.css b/src/styles/photos.css
index 4cf2155..60be06b 100644
--- a/src/styles/photos.css
+++ b/src/styles/photos.css
@@ -68,7 +68,7 @@
background: transparent;
color: var(--text-3);
opacity: 0;
- transition: opacity 120ms ease;
+ transition: none;
}
/* As in Finder and Photos: the + shows when the sidebar is pointed at or the keys reach it. */
.px-side:hover .px-side-add,
@@ -143,7 +143,7 @@
background: transparent;
color: var(--text);
cursor: default;
- transition: background-color 120ms ease, transform 160ms var(--spring-quick);
+ transition: background-color 120ms ease;
}
.px-cap:hover:not(:disabled) { background: color-mix(in srgb, var(--text) 8%, transparent); }
.px-cap:active:not(:disabled) { transform: scale(0.9); }
@@ -163,7 +163,7 @@
font-size: var(--t-13);
font-weight: 600;
cursor: default;
- transition: background-color 120ms ease, transform 160ms var(--spring-quick);
+ transition: background-color 120ms ease;
}
.px-word.is-danger { color: var(--danger); }
.px-word:hover { background: color-mix(in srgb, currentColor 10%, transparent); }
@@ -254,7 +254,7 @@
/* The thumbnail (the frame's background) shows until the picture made for the tile is in. */
.px-pic { background-size: cover; background-position: center; }
.px-pic img[data-in] { opacity: 1; }
-.px-pic img[data-in="fade"] { transition: opacity 160ms ease-out; }
+.px-pic img[data-in="fade"] { transition: none; }
/* Whole photos, as icloud.com shows them: each in its own shape, with room around it. */
.px-scroll[data-fit] .px-grid { gap: 14px; padding: 0 14px; }
.px-scroll[data-fit] .px-tile { background: transparent; overflow: visible; }
@@ -370,7 +370,7 @@
background: color-mix(in srgb, var(--sheet) 90%, transparent);
box-shadow: var(--glass-float);
color: var(--text);
- transition: transform 160ms var(--spring-quick);
+ transition: none;
}
.px-nav:hover { background: var(--glass-thick); }
.px-nav:active { transform: scale(0.92); }
@@ -476,7 +476,7 @@
box-shadow: inset 0 0.5px 0 rgba(255, 255, 255, 0.18), 0 10px 30px rgba(0, 0, 0, 0.5);
color: #fff;
opacity: 0;
- transition: opacity 260ms ease;
+ transition: none;
}
.px-show.is-awake .px-show-bar { opacity: 1; }
.px-show-bar .px-cap { color: #fff; }
@@ -532,7 +532,7 @@
background: transparent;
color: var(--text-3);
cursor: default;
- transition: color 120ms ease, transform 140ms var(--spring-quick);
+ transition: color 120ms ease;
}
.px-star.is-on { color: #ff9f0a; }
.px-star:hover:not(:disabled) { background: color-mix(in srgb, var(--text) 7%, transparent); }
@@ -640,11 +640,11 @@
overflow: hidden;
background: color-mix(in srgb, var(--text) 7%, transparent);
color: var(--text-3);
- transition: transform 180ms var(--spring-quick), box-shadow 180ms ease;
+ transition: box-shadow 180ms ease;
}
.px-card-pic img { width: 100%; height: 100%; object-fit: cover; display: block; }
.px-card-pic .px-glyph { width: 36px; height: 36px; }
-.px-card:hover .px-card-pic { transform: scale(1.015); box-shadow: 0 6px 18px rgba(0, 0, 0, 0.18); }
+.px-card:hover .px-card-pic { box-shadow: 0 6px 18px rgba(0, 0, 0, 0.18); }
.px-card:active .px-card-pic { transform: scale(0.985); }
.px-card:focus-visible { outline: none; }
.px-card:focus-visible .px-card-pic, .px-card[data-drop] .px-card-pic { box-shadow: 0 0 0 3px var(--accent); }
@@ -810,7 +810,7 @@
background: color-mix(in srgb, var(--text) 9%, transparent);
color: var(--accent);
cursor: default;
- transition: transform 140ms var(--spring-quick);
+ transition: none;
}
.px-dl-go:hover { background: color-mix(in srgb, var(--text) 14%, transparent); }
.px-dl-go:active { transform: scale(0.92); }
@@ -844,7 +844,7 @@
font-size: var(--t-13);
font-weight: 600;
cursor: default;
- transition: transform 140ms var(--spring-quick);
+ transition: none;
}
.px-sheet-button:hover:not(:disabled) { background: color-mix(in srgb, var(--text) 15%, transparent); }
.px-sheet-button:active:not(:disabled) { transform: scale(0.97); }
@@ -928,7 +928,7 @@
padding: 0 6px;
border-radius: 20px;
opacity: 0;
- transition: opacity 260ms ease;
+ transition: none;
pointer-events: none;
}
.px-player.is-awake .px-player-bar { opacity: 1; pointer-events: auto; }
diff --git a/src/styles/reminders.css b/src/styles/reminders.css
index d5b4286..637589f 100644
--- a/src/styles/reminders.css
+++ b/src/styles/reminders.css
@@ -563,7 +563,6 @@
.rx-info-name:focus { border-color: currentColor; }
.rx-info-colours { display: grid; grid-template-columns: repeat(6, 1fr); gap: 12px; }
.rx-info-swatch { width: 30px; height: 30px; padding: 0; border: 0; border-radius: 50%; box-shadow: none; cursor: pointer; transition: transform 120ms ease; }
-.rx-info-swatch:hover { transform: scale(1.08); }
.rx-info-swatch.is-on { box-shadow: 0 0 0 2px var(--sheet, var(--bg)), 0 0 0 4px var(--text-3); }
.rx-info-actions { display: flex; justify-content: space-between; width: 100%; margin-top: 4px; }