Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
Uploads you can follow and stop, deletes that stick, notes that show what they hold
Yashwanth Kamireddi242d4e0466a7
diff --git a/.uiverify/drive-upload-cancel.mjs b/.uiverify/drive-upload-cancel.mjsnew file mode 100644index 0000000..1f79d69--- /dev/null+++ b/.uiverify/drive-upload-cancel.mjs@@ -0,0 +1,98 @@+// A folder upload shows what it is doing from the first moment — the folder being made, then+// each file as it is found — and every file still waiting or going up can be cancelled, one+// at a time or all at once, ending as "cancelled" rather than vanishing or failing.+import { engine as chromium } from "./engine.mjs";++const b = await chromium.launch();+const ctx = await b.newContext({ viewport: { width: 1280, height: 820 } });+await ctx.addInitScript(() => {+ const handlers = {};+ const wait = (ms) => new Promise((r) => setTimeout(r, ms));+ window.__cancels = [];+ window.__TAURI_INTERNALS__ = {+ transformCallback: (cb) => cb,+ convertFileSrc: (p, proto = "asset") => `${proto}://localhost/${encodeURIComponent(p)}`,+ invoke: async (cmd, args) => {+ if (cmd === "auth_status") return { hasStoredSession: true, signedIn: true };+ if (cmd === "auth_resume") return "library";+ if (cmd === "account_services") return ["drivews", "docws"];+ if (cmd === "plugin:event|listen") {+ (handlers[args.event] ??= []).push(args.handler);+ return handlers[args.event].length;+ }+ if (cmd === "plugin:dialog|open") return ["/home/me/Holiday"];+ if (cmd === "drive_children") return [];+ if (cmd === "drive_item") return null;+ if (cmd === "drive_sync_folder") return 0;+ const say = (e) => (handlers["quince://upload"] ?? []).forEach((h) =>+ h({ event: "quince://upload", id: 1, payload: { within: "", error: null, sent: 0, folder: false, ...e } }));+ if (cmd === "drive_upload_cancel") {+ window.__cancels.push(args);+ for (const id of window.__live ?? []) {+ if (args.ids.includes(id.id) || (args.batch && id.id.startsWith(`${args.batch}:`))) say({ ...id, state: "cancelled" });+ }+ return null;+ }+ if (cmd === "drive_upload") {+ const batch = args.batch;+ say({ id: `${batch}:dir:0`, batch, name: "Holiday", total: 0, state: "preparing", folder: true });+ await wait(300);+ window.__early = document.querySelector(".upload-tray")?.innerText ?? "";+ say({ id: `${batch}:dir:0`, batch, name: "Holiday", total: 0, state: "done", folder: true });+ window.__live = [0, 1, 2].map((n) => ({ id: `${batch}:${n}`, batch, name: `photo ${n}.jpg`, within: "Holiday", total: 1000 }));+ for (const f of window.__live) say({ ...f, state: "waiting" });+ await wait(200);+ window.__found = document.querySelector(".upload-row")?.innerText ?? "";+ // Everything found: from here there is a total.+ say({ id: `${batch}:planned`, batch, name: "", total: 3000, state: "planned", folder: true });+ say({ ...window.__live[0], sent: 300, state: "sending" });+ await wait(150);+ say({ ...window.__live[0], sent: 900, state: "sending" });+ await wait(100);+ window.__ahead = document.querySelector(".upload-tray-percent")?.textContent ?? "";+ // A report for the same file that was overtaken on its way here.+ say({ ...window.__live[0], sent: 300, state: "sending" });+ await wait(100);+ window.__after = document.querySelector(".upload-tray-percent")?.textContent ?? "";+ // Waits for the person: the backend's uploads run until they finish or are stopped.+ await new Promise((r) => (window.__finish = r));+ return [];+ }+ if (cmd === "sync_all" || cmd === "sync_status") return { services: [], asOf: 1, tookMs: 0 };+ return [];+ },+ };+});++const page = await ctx.newPage();+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });+await page.locator(".nav-item", { hasText: "iCloud Drive" }).click();+await page.waitForSelector(".drive-rows", { state: "attached" });+await page.waitForTimeout(300);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };++await page.getByRole("button", { name: "Upload", exact: true }).click();+await page.getByRole("menuitem", { name: "Folder…" }).click();+await page.waitForTimeout(700);+const early = await page.evaluate(() => window.__early);+ok(/Holiday/.test(early) && /Preparing/.test(early), `a folder upload says what it is doing from the start [${early.replace(/\s+/g, " ")}]`);+const found = await page.evaluate(() => window.__found);+ok(/Preparing… 3 found/.test(found), `while a folder is still being walked it counts what it has found, not a total [${found.replace(/\s+/g, " ")}]`);+// One line for the folder, everything in it counted together — not a row per file.+const lines = await page.locator(".upload-row").allInnerTexts();+ok(lines.length === 1 && /Holiday/.test(lines[0]) && /0 of 3/.test(lines[0]), `a folder is one line, its files counted together ${JSON.stringify(lines)}`);+await page.waitForFunction(() => window.__after !== undefined);+const [ahead, after] = await page.evaluate(() => [window.__ahead, window.__after]);+ok(ahead === "30%" && after === "30%", `progress never slides back when a late report arrives [${ahead} → ${after}]`);+ok(/Uploading Holiday/.test(await page.locator(".upload-tray-title").innerText()), "the head names the folder going up");++ok((await page.getByRole("button", { name: "Cancel Holiday" }).count()) === 0, "one upload has one Cancel, not two");+await page.locator(".upload-tray").getByRole("button", { name: "Cancel", exact: true }).click();+await page.waitForTimeout(200);+const sent = await page.evaluate(() => window.__cancels);+ok(sent.length === 1 && Boolean(sent[0].batch), `Cancel stops the whole upload ${JSON.stringify(sent)}`);+ok(/Cancelled/.test(await page.locator(".upload-row").first().innerText()), `the folder then says it was cancelled [${await page.locator(".upload-row").first().innerText()}]`);+await page.evaluate(() => window.__finish?.());+await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/drive-upload.mjs b/.uiverify/drive-upload.mjsindex 84eaa09..25188c3 100644--- a/.uiverify/drive-upload.mjs+++ b/.uiverify/drive-upload.mjs@@ -84,7 +84,7 @@ ok(rows.length === 2 && /is-done/.test(rows[0].cls) && /is-failed/.test(rows[1]."each file ends with its own verdict, and a failure says why",`rows ended as ${JSON.stringify(rows)}`);const head = await page.locator(".upload-tray-title").innerText();-ok(head === "1 of 2 didn’t upload", "the tray sums it up honestly", `the tray said "${head}"`);+ok(head === "Some uploads didn’t finish", "the tray sums it up honestly", `the tray said "${head}"`);const usable = await page.getByRole("button", { name: "Upload", exact: true }).isEnabled();ok(usable, "the window stays usable, and another upload can start", "Upload was left disabled");diff --git a/.uiverify/menus.mjs b/.uiverify/menus.mjsindex 002b45f..697ab75 100644--- a/.uiverify/menus.mjs+++ b/.uiverify/menus.mjs@@ -139,6 +139,24 @@ for (const size of [{ width: 1280, height: 800 }, { width: 760, height: 520 }])ok((await page.locator(".row-menu").count()) === 1, `${label} resting on another line closes the submenu`);await page.keyboard.press("Escape");+ // A pop-up stays open through a scroll that leaves its button where it was — a page+ // settling as it opened used to shut it at once — and goes when its button moves.+ await openScreen(page, "Reminders");+ await page.waitForTimeout(300);+ await page.locator(".rx-rows li").first().hover();+ await page.locator(".rx-trailing .rx-icon-button[aria-expanded]").first().click({ force: true });+ await page.waitForTimeout(300);+ const pop = page.locator(".rx-detail .picker-button").first();+ if (await pop.count()) {+ await pop.click();+ await page.waitForTimeout(100);+ await page.evaluate(() => document.dispatchEvent(new Event("scroll")));+ await page.waitForTimeout(80);+ ok((await page.locator(".picker-menu").count()) === 1, `${label} a scroll that leaves the button in place does not close its menu`);+ await page.keyboard.press("Escape");+ }+ await page.keyboard.press("Escape");+// The ⋯ that opened a menu closes it again, in one press, and it does not blink back.const listRow = page.locator(".contacts-lists .notes-folder-row").nth(1);if (await listRow.isVisible()) {diff --git a/.uiverify/notes-media.mjs b/.uiverify/notes-media.mjsnew file mode 100644index 0000000..88c9626--- /dev/null+++ b/.uiverify/notes-media.mjs@@ -0,0 +1,30 @@+// What a note holds besides text, drawn where it sits: a picture at its own proportions from+// the backend's picture route, a file as a chip naming it and its kind — and either opens in+// the app this computer uses for it. A picture that cannot be had becomes the chip.+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(() => { window.__mediaNote = true; });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, notesFixture: true });+const page = await ctx.newPage();+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });+await openScreen(page, "Notes");+await page.waitForTimeout(400);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };+await page.locator(".note-row", { hasText: "Trip" }).first().click();+await page.waitForTimeout(800);+// In a plain browser quince:// cannot load, so the picture falls back to its chip — what is+// checked is that the picture was asked for by its route, and the fallback is a named chip.+const asked = await page.evaluate(() => [...document.querySelectorAll("img")].map((i) => i.getAttribute("src")).concat(window.__asked ?? []));+const chips = await page.locator(".nf-file").allInnerTexts();+ok(chips.some((c) => /Budget\.xlsx/.test(c) && /XLSX/.test(c)), `a file shows as a chip with its name and kind ${JSON.stringify(chips)}`);+ok(chips.some((c) => /beach\.jpeg/.test(c)) || asked.some((s) => s?.includes("note%2FM1%2Ffile")), `a picture is drawn from its own route, or its chip when it cannot be had ${JSON.stringify(asked)}`);+await page.locator(".nf-file", { hasText: "Budget.xlsx" }).click();+await page.waitForTimeout(150);+ok(JSON.stringify(await page.evaluate(() => window.__opened)) === JSON.stringify(["M2"]), "clicking a file opens it");+const saves = await page.evaluate(() => window.__noteSaves?.length ?? 0);+ok(saves === 0, "and the note's text is left alone");+await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/notes-table.mjs b/.uiverify/notes-table.mjsnew file mode 100644index 0000000..58c2657--- /dev/null+++ b/.uiverify/notes-table.mjs@@ -0,0 +1,44 @@+// A table in a note, drawn as its grid and edited in place: a typed cell takes typing as its+// own (the note's text is untouched), saves when left, and goes back with the reason if Apple+// refuses; a cell never typed in says it cannot be changed here yet.+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(() => { window.__tableNote = true; });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, notesFixture: true });+const page = await ctx.newPage();+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });+await openScreen(page, "Notes");+await page.waitForTimeout(400);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };+await page.locator(".note-row", { hasText: "Groceries" }).first().click();+await page.waitForSelector(".nf-table");+const grid = await page.locator(".nf-table tr").evaluateAll((rows) => rows.map((r) => [...r.cells].map((c) => c.textContent)));+ok(JSON.stringify(grid) === JSON.stringify([["Item", "Qty"], ["Milk", "2"], ["", ""]]), `the table is drawn as its grid ${JSON.stringify(grid)}`);++const milk = page.locator(".nf-cell-edit", { hasText: "Milk" });+await milk.click();+await page.keyboard.press("End");+await page.keyboard.type(" (oat)");+await page.keyboard.press("Enter");+await page.waitForTimeout(100);+ok((await milk.textContent()) === "Milk (oat)", "a cell takes typing and shows it at once");+await page.waitForTimeout(400);+const writes = await page.evaluate(() => window.__cellWrites);+ok(writes?.length === 1 && writes[0].row === 1 && writes[0].column === 0 && writes[0].text === "Milk (oat)", `the cell, and only it, goes to Apple ${JSON.stringify(writes)}`);+const saves = await page.evaluate(() => window.__noteSaves?.length ?? 0);+ok(saves === 0, "typing in a cell leaves the note's own text alone");++await page.evaluate(() => { window.__cellFail = true; });+const qty = page.locator(".nf-cell-edit", { hasText: "2" });+await qty.click();+await page.keyboard.press("End");+await page.keyboard.type("0");+await page.keyboard.press("Enter");+await page.waitForTimeout(500);+ok((await qty.textContent()) === "2" && /refused/.test((await qty.getAttribute("title")) ?? ""), "a change Apple refuses goes back, and says why");+ok((await page.locator(".nf-cell-empty").count()) === 2, "a cell never typed in is shown but not offered for editing");+await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/reminders-context.mjs b/.uiverify/reminders-context.mjsnew file mode 100644index 0000000..91cda79--- /dev/null+++ b/.uiverify/reminders-context.mjs@@ -0,0 +1,28 @@+// Right-clicking a reminder opens what can be done to it, as on the Mac: info, flag,+// complete, indent, move to another list, delete — each doing what it says.+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, remindersFixture: true });+const page = await ctx.newPage();+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });+await openScreen(page, "Reminders");+await page.waitForTimeout(400);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };+const row = page.locator(".rx-row").first();+await row.click({ button: "right", position: { x: 300, y: 10 } });+await page.waitForTimeout(150);+const items = await page.locator(".row-menu").first().getByRole("menuitem").allInnerTexts();+ok(["Show Info", "Flag", "Mark as Completed", "Indent", "Move to List", "Delete"].every((x) => items.some((i) => i.startsWith(x))), `a reminder's menu holds what can be done to it ${JSON.stringify(items)}`);+await page.getByRole("menuitem", { name: "Show Info" }).click();+await page.waitForTimeout(200);+ok((await page.locator(".rx-detail").count()) === 1, "Show Info opens its details");+await row.click({ button: "right", position: { x: 300, y: 10 } });+await page.getByRole("menuitem", { name: "Move to List" }).hover();+await page.waitForTimeout(200);+ok((await page.locator(".row-menu").count()) === 2, "Move to List offers the other lists beside it");+await page.keyboard.press("Escape");+await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/reminders-switch.mjs b/.uiverify/reminders-switch.mjsnew file mode 100644index 0000000..f804654--- /dev/null+++ b/.uiverify/reminders-switch.mjs@@ -0,0 +1,45 @@+// Switching between lists: the pane changes heading and reminders together, in one draw —+// never the new list's name over the old list's reminders — and a quick run of switches+// ends on the last one picked.+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(() => { window.__slowItems = 150; window.__filterLists = true; });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, remindersFixture: true });+const page = await ctx.newPage();+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });+await openScreen(page, "Reminders");+await page.waitForTimeout(500);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };+const lists = await page.locator(".rx-list .rx-list-name").allInnerTexts();+await page.locator(".rx-list", { hasText: "Daily" }).click();+await page.waitForTimeout(400);+await page.evaluate(() => {+ window.__frames = [];+ window.__watch = true;+ const tick = () => {+ const h = document.querySelector(".rx h1")?.textContent?.trim();+ // Daily holds three reminders and GYM one: the count says whose rows are drawn.+ const n = document.querySelectorAll(".rx-row").length;+ window.__frames.push(`${h}::${n === 1 ? "GYM" : n === 3 ? "DAILY" : n}`);+ if (window.__watch) requestAnimationFrame(tick);+ };+ requestAnimationFrame(tick);+});+await page.locator(".rx-list", { hasText: "GYM" }).click();+await page.waitForTimeout(500);+const frames = await page.evaluate(() => { window.__watch = false; return window.__frames; });+const wrong = frames.filter((f) => (f.startsWith("GYM") && f.endsWith("DAILY")) || (f.startsWith("Daily") && f.endsWith("GYM")));+ok(wrong.length === 0, `heading and reminders change together [${[...new Set(frames)].join(" → ")}]`);+// The sidebar answers the click at once.+ok((await page.locator('.rx-list[aria-current="true"]').innerText()).includes("GYM"), "the sidebar shows the pick at once");+// Three quick picks: the pane ends on the last.+for (const name of ["Daily", "Life Goals", "GYM"]) await page.locator(".rx-list", { hasText: name }).click();+await page.waitForTimeout(700);+const last = (await page.evaluate(() => window.__frames.at(-1))) ?? "";+const h = await page.locator(".rx h1").first().innerText();+ok(h.includes("GYM"), `a quick run of switches ends on the last one picked [${h}]`);+await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/settings.mjs b/.uiverify/settings.mjsindex d78b674..01d4a46 100644--- a/.uiverify/settings.mjs+++ b/.uiverify/settings.mjs@@ -64,6 +64,13 @@ await page.evaluate(() => {await page.getByRole("button", { name: "Fold Sidebar to Icons" }).click();await page.waitForTimeout(400);ok(await page.evaluate(() => window.__slid), "folding slides the content on the compositor");+// A diagnostic report is written for the person to read and send, and says where.+await page.locator(".sidebar-account").click();+await page.waitForSelector(".settings");+await page.getByRole("button", { name: "Save Diagnostic Report" }).click();+await page.waitForTimeout(150);+ok((await page.evaluate(() => window.__diagnostics)) === 1 && /Saved to Downloads\/Quince diagnostics/.test(await page.locator(".settings").innerText()), "a diagnostic report is saved, and the screen says where");+// The account's picture is the photo on the person's own card, where it has one.// (A plain browser cannot load quince:// — the picture falls back to initials, as it should —// so what is checked is the picture asked for.)diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjsindex 5e70e77..1569b66 100644--- a/.uiverify/stub.mjs+++ b/.uiverify/stub.mjs@@ -167,7 +167,12 @@ export function installStub({ screen, services, twoFactor, calendarFixture, notecase "calendar_sync": return { calendars: calendars.length, events: events.length };case "reminder_counts": return { today: 4, scheduled: 7, flagged: 2, all: 12, lists: [["L1", 5], ["L2", 3], ["lists", 4]] };case "reminder_lists": return !remindersFixture ? [] : reminderLists;- case "reminders_in": return !remindersFixture || remindersFixture === "lists" ? [] : reminderItems;+ case "reminders_in": {+ 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;+ }case "reminders_due_between": return calendarFixture ? dueReminders : [];case "reminder_create":// Kept, as Apple keeps it, with what the view implied.@@ -206,6 +211,15 @@ export function installStub({ screen, services, twoFactor, calendarFixture, notecase "note_paragraph": (window.__paragraphs ??= []).push(args); return null;case "note_runs": {if (window.__savedRuns?.[args.guid]) return window.__savedRuns[args.guid];+ if (args.guid === "nM") {+ const plain = (length) => ({ length, style: null, indent: 0, checked: null, bold: false, italic: false, underline: false, strike: false, link: null });+ return [plain(5), { ...plain(1), attachment: "M1" }, plain(1), { ...plain(1), attachment: "M2" }, plain(4)];+ }+ if (args.guid === "nT") {+ // "Groceries", a table on its own line, then a last line: the table's run names it.+ const plain = (length) => ({ length, style: null, indent: 0, checked: null, bold: false, italic: false, underline: false, strike: false, link: null });+ return [plain(10), { ...plain(1), attachment: "T1" }, plain(4)];+ }// Curtains, set as a phone sets one: a title, then a dashed list and a ticked item.if (args.guid !== "n1") return [];const body = (noteList.find((n) => n.guid === "n1") ?? {}).body ?? "";@@ -251,7 +265,28 @@ export function installStub({ screen, services, twoFactor, calendarFixture, notereturn null;}case "note_create": return "Note/new";- case "notes_in": return !notesFixture ? [] : noteList.map((n) => ({ ...n }));+ case "notes_in":+ // Opt-in: a note holding a table, as a phone makes one.+ if (window.__mediaNote && !noteList.some((n) => n.guid === "nM"))+ noteList.unshift({ guid: "nM", folderGuid: "f1", title: "Trip", snippet: "", body: "Trip\n\uFFFC\n\uFFFC\nend",+ locked: false, editable: true, pinned: false, createdAt: null, modifiedAt: 1789100000, etag: null });+ if (window.__tableNote && !noteList.some((n) => n.guid === "nT"))+ noteList.unshift({ guid: "nT", folderGuid: "f1", title: "Groceries", snippet: "", body: "Groceries\n\uFFFC\nend",+ locked: false, editable: true, pinned: false, createdAt: null, modifiedAt: 1789000000, etag: null });+ return !notesFixture ? [] : noteList.map((n) => ({ ...n }));+ case "note_attachment_info":+ return args.id === "M1"+ ? { id: "M1", uti: "public.jpeg", kind: "image", filename: "beach.jpeg", title: null, width: 1200, height: 800, size: 271872, hasPreview: true }+ : { id: "M2", uti: "org.openxmlformats.spreadsheetml.sheet", kind: "file", filename: "Budget.xlsx", title: null, width: null, height: null, size: 9100, hasPreview: false };+ case "note_attachment_open": (window.__opened ??= []).push(args.id); return null;+ case "note_table": if (String(args.id).startsWith("M")) return null; return (window.__table ??= [["Item", "Qty"], ["Milk", "2"], ["", ""]]).map((r) => r.slice());+ case "note_table_set_cell": {+ (window.__cellWrites ??= []).push(args);+ await new Promise((r) => setTimeout(r, 300));+ if (window.__cellFail) throw "Apple refused that change.";+ window.__table[args.row][args.column] = args.text;+ return window.__table.map((r) => r.slice());+ }case "note_body": return (noteList.find((n) => n.guid === args?.guid) ?? {}).body ?? null;case "note_counts": {const per = new Map();@@ -290,6 +325,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, notecase "drive_thumbnails": return driveFixture ? { "FILE::d": "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='80' height='60'><rect width='80' height='60' fill='%23eee'/></svg>" } : {};case "drive_duplicate": (window.__dups ??= []).push(args.drivewsid); return null;case "storage_info": return { usedBytes: 182196857, totalBytes: 5368709120 };+ case "diagnostics_save": (window.__diagnostics = (window.__diagnostics ?? 0) + 1); return "/home/user/Downloads/Quince diagnostics 2026-10-18 20.00.txt";case "account_info": return { name: "Asha Rao", email: "[email protected]", photoContact: window.__mePhoto ?? null, webAccessAllowed: window.__webAccess ?? true, dataProtection: false };case "settings_get": return { reminderAlerts: true, eventAlerts: true, ...(window.__settings ?? {}) };case "settings_set":diff --git a/Cargo.lock b/Cargo.lockindex 2d6f9aa..daf8e91 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -650,6 +650,16 @@ dependencies = ["url",]+[[package]]+name = "core-foundation"+version = "0.9.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"+dependencies = [+ "core-foundation-sys",+ "libc",+]+[[package]]name = "core-foundation"version = "0.10.1"@@ -673,7 +683,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97"dependencies = ["bitflags 2.13.2",- "core-foundation",+ "core-foundation 0.10.1","core-graphics-types","foreign-types","libc",@@ -686,7 +696,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"dependencies = ["bitflags 2.13.2",- "core-foundation",+ "core-foundation 0.10.1","libc",]@@ -2279,9 +2289,13 @@ version = "3.6.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c"dependencies = [+ "byteorder","dbus-secret-service","log","secret-service",+ "security-framework 2.11.1",+ "security-framework 3.7.0",+ "windows-sys 0.60.2","zeroize",]@@ -3346,6 +3360,7 @@ dependencies = ["anyhow","base64 0.22.1","flate2",+ "futures-util","image","jiff","quince-auth",@@ -3921,6 +3936,42 @@ dependencies = ["zbus 4.4.0",]+[[package]]+name = "security-framework"+version = "2.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"+dependencies = [+ "bitflags 2.13.2",+ "core-foundation 0.9.4",+ "core-foundation-sys",+ "libc",+ "security-framework-sys",+]++[[package]]+name = "security-framework"+version = "3.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"+dependencies = [+ "bitflags 2.13.2",+ "core-foundation 0.10.1",+ "core-foundation-sys",+ "libc",+ "security-framework-sys",+]++[[package]]+name = "security-framework-sys"+version = "2.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"+dependencies = [+ "core-foundation-sys",+ "libc",+]+[[package]]name = "selectors"version = "0.36.1"@@ -4373,7 +4424,7 @@ checksum = "d1c93047acf68669466a34690ac58cca7010bd1b201e1ec86f1fd0a75d3dd4a9"dependencies = ["bitflags 2.13.2","block2",- "core-foundation",+ "core-foundation 0.10.1","core-graphics","crossbeam-channel","dbus",diff --git a/README.md b/README.mdindex 4d81ac7..e1cd473 100644--- a/README.md+++ b/README.md@@ -15,7 +15,8 @@ It is a native Linux application — Rust underneath, a real window, no browserEverything here is read from and written to your real iCloud account, shows the moment youmake it — before Apple has answered — and is put back with the reason if Apple refuses.-**Notes** — edited formatted, as on a Mac: titles, headings, monospaced text, bulleted,+**Notes** — pictures, scans, PDFs, recordings, films and files shown where they sit and opened+in your own apps; tables shown as the grids they are, their cells edited in place; edited formatted, as on a Mac: titles, headings, monospaced text, bulleted,dashed and numbered lists, checklists you tick, bold, italic, underline and strikethrough,from the Aa panel, the checklist button or the Mac's keys. Folders: new, rename, nest,delete. Pin, move, Recently Deleted and Recover. An edit made on your phone at the same time@@ -35,15 +36,34 @@ schedule in their list's colour; birthdays and holidays; the Mac's keyboard throwith people added by menu or by dragging; select several to add, remove, export or deletetogether; vCard import and export; My Card.-**iCloud Drive** — browse in a list or grid with Apple's own thumbnails; sort; upload by-button or by dropping files on the window; download, rename, duplicate, Get Info; move by+**iCloud Drive** — browse in a list or grid with Apple's own thumbnails; sort; upload files+or whole folders by button or by dropping them on the window, each file's progress shown and+any of them cancellable while it is still on its way up; download, rename, duplicate, Get Info; move bydialog or by dragging onto a folder; Recents; Recently Deleted with the time each item hasleft, Recover and Delete Now; your storage.-Each app takes its own Mac colours — Notes yellow, Calendar red, the rest blue — from-Apple's macOS 27 design kit, in light and dark.+**Instant, both ways.** A change made on your phone reaches Quince in about a second: Notes+and Reminders through Apple's own push channel, Calendar and Contacts through the same quick+"has anything changed" checks icloud.com makes, every few seconds while the window is open.+What you change shows the moment you make it and is put back, with the reason, only if Apple+refuses it — and a refresh landing mid-change never undoes what is still on its way.-Not yet: Photos, Mail, Find My, and tables in Notes (a note with one opens and edits; the table itself shows as a placeholder until it can be edited here).+**Settings** — your account and its picture from your own card, iCloud storage, when each app+last synced with Sync Now, Automatic / Light / Dark, and switches for reminder and calendar+alerts that the alerts really obey.++**Designed as macOS 27 is.** Liquid Glass on the chrome — the sidebar, toolbars, menus,+popovers and sheets — and never on your content; capsule controls; motion on Apple's own+springs; each app in its own Mac colour, Notes yellow, Calendar red, the rest blue; light and+dark, Reduce Transparency and Increase Contrast honoured.++**Advanced Data Protection.** With it on and "Access iCloud Data on the Web" off, no app+outside your devices can read your iCloud. Quince says exactly that, once, and names Apple's+switch — on your iPhone, Settings, your name, iCloud, Access iCloud Data on the Web — rather+than failing screen by screen.++Not yet: Photos, Mail, Find My; typing into a table cell that has never been typed in (cells+with text are edited in place); calendar invitations.## Installing@@ -83,7 +103,8 @@ guessed at.```Formatting, lints, the Rust tests, TypeScript, the bundle, and then the built application-driven in a real browser: every screen screenshotted and measured, the keyboard path walked,+driven in a real browser: every screen screenshotted and measured, the keyboard path walked, motion sampled frame by+frame (a fold that jumps, a list that flickers, a menu that blinks fails the build),accessibility audited, and every screen opened again as a German speaker in New York, aJapanese speaker in Tokyo and a New Zealander on the Chathams — because this was written inone place with a clock that never moves, and most people are somewhere else.@@ -115,9 +136,9 @@ and will not be built.and Screen Time are encrypted end to end — Apple's own servers hold no key to them. Quinceshows them as unavailable rather than quietly leaving them out.-**Advanced Data Protection.** With it switched on, the services above are encrypted the same-way and Quince cannot read them either. It says so rather than nudging anybody to turn a-security feature off.+**Advanced Data Protection.** With it switched on and web access off, iCloud's data is+encrypted the same way and Quince cannot read it either. It says so, and how web access is+turned on, rather than nudging anybody to turn the security feature itself off.## Licencediff --git a/check.sh b/check.shindex f44f3ba..7766245 100755--- a/check.sh+++ b/check.sh@@ -72,6 +72,12 @@ step "calendar day steps" node .uiverify/calendar-daystep.mjsstep "sidebar fold" node .uiverify/sidebar-fold.mjsstep "pending writes" node .uiverify/pending-writes.mjsstep "row hover" node .uiverify/row-hover.mjs+step "reminders switch" node .uiverify/reminders-switch.mjs+step "upload cancel" node .uiverify/drive-upload-cancel.mjs+step "notes tables" node .uiverify/notes-table.mjs+step "reminder menu" node .uiverify/reminders-context.mjs+step "notes media" node .uiverify/notes-media.mjs+step "webkit: tables" env ENGINE=webkit node .uiverify/notes-table.mjsstep "webkit: row hover" env ENGINE=webkit node .uiverify/row-hover.mjsstep "webkit: fold" env ENGINE=webkit node .uiverify/sidebar-fold.mjsstep "reminder colours" node .uiverify/calendar-reminder-colour.mjsdiff --git a/crates/quince-auth/Cargo.toml b/crates/quince-auth/Cargo.tomlindex 4c11b15..aba78f4 100644--- a/crates/quince-auth/Cargo.toml+++ b/crates/quince-auth/Cargo.toml@@ -19,14 +19,26 @@ hmac = "0.12"rand = "0.9"reqwest_cookie_store = "0.8"cookie_store = { version = "0.21", features = ["serde_json"] }-# `linux-native` selects the KERNEL keyutils backend, which is session-scoped and does not-# survive a reboot — the trust token would quietly evaporate and the app would ask for a code-# again, the exact failure this project exists to fix. The Secret Service backend is the-# persistent one (gnome-keyring / kwallet).-keyring = { version = "3", default-features = false, features = ["sync-secret-service", "crypto-rust"] }thiserror = "2"[dev-dependencies]tokio = { workspace = true }wiremock = "0.6"tempfile = "3"++# Each system's own keyring, behind the same `keyring` API: the Secret Service on Linux, the+# Credential Manager on Windows, the Keychain on macOS. One set of features for all three+# pulled D-Bus into a Windows build, which cannot link it.+#+# `linux-native` selects the KERNEL keyutils backend, which is session-scoped and does not+# survive a reboot — the trust token would quietly evaporate and the app would ask for a code+# again, the exact failure this project exists to fix. The Secret Service backend is the+# persistent one (gnome-keyring / kwallet).+[target.'cfg(target_os = "linux")'.dependencies]+keyring = { version = "3", default-features = false, features = ["sync-secret-service", "crypto-rust"] }++[target.'cfg(target_os = "windows")'.dependencies]+keyring = { version = "3", default-features = false, features = ["windows-native"] }++[target.'cfg(target_os = "macos")'.dependencies]+keyring = { version = "3", default-features = false, features = ["apple-native"] }diff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rsindex 173964c..897c35d 100644--- a/crates/quince-auth/src/lib.rs+++ b/crates/quince-auth/src/lib.rs@@ -98,7 +98,8 @@ pub enum Error {NoTrustToken,#[error("this account signs in a way Quince can't handle yet ({0})")]UnsupportedAccount(String),- #[error("couldn't reach Apple: {0}")]+ /// Said without the address, which carries account and client ids.+ #[error("couldn't reach Apple: {}", if .0.is_timeout() { "it took too long to answer" } else if .0.is_connect() { "check your connection" } else { "the connection dropped" })]Network(#[from] reqwest::Error),#[error("Apple sent back something unexpected: {0}")]Protocol(String),diff --git a/crates/quince-icloud/src/ckdocument.rs b/crates/quince-icloud/src/ckdocument.rsindex baafb92..957ebf7 100644--- a/crates/quince-icloud/src/ckdocument.rs+++ b/crates/quince-icloud/src/ckdocument.rs@@ -712,6 +712,18 @@ fn rebuild_note(note: &[u8], old_text: &str, new_text: &str) -> Option<Vec<u8>>Some(out)}+/// A text object rewritten to say `new_text`, as a device would edit it: the merge records+/// edited in step and every other field copied through. The same message shape serves a+/// note's body and each cell of a Notes table, so a table's cells are edited by this too.+/// `None` when the object is not one this can rewrite truthfully.+pub(crate) fn rewrite_text_object(+ object: &[u8],+ old_text: &str,+ new_text: &str,+) -> Option<Vec<u8>> {+ rebuild_note(object, old_text, new_text)+}+/// What to change about one paragraph's setting.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum ParagraphChange {diff --git a/crates/quince-icloud/src/contacts.rs b/crates/quince-icloud/src/contacts.rsindex d6cddd3..28eb671 100644--- a/crates/quince-icloud/src/contacts.rs+++ b/crates/quince-icloud/src/contacts.rs@@ -1000,8 +1000,62 @@ async fn startup()));}- serde_json::from_str(&text)- .map_err(|e| Error::Protocol(format!("/co/startup returned invalid JSON: {e}")))+ let mut body: Value = serde_json::from_str(&text)+ .map_err(|e| Error::Protocol(format!("/co/startup returned invalid JSON: {e}")))?;++ // `contactsOrder` names every card in the book; `contacts` may hold only the first of+ // them, as icloud.com reads a large book a page at a time (`co/contacts/card/?offset&+ // limit`). The rest is read the same way, so a large address book is never cut short —+ // and stored short, the cards it missed would read as deleted.+ let wanted = body+ .get("contactsOrder")+ .and_then(Value::as_array)+ .map_or(0, Vec::len);+ let mut have = body+ .get("contacts")+ .and_then(Value::as_array)+ .map_or(0, Vec::len);+ let mut pages = 0;+ while have < wanted && pages < 200 {+ pages += 1;+ // As icloud.com sends every Contacts request: with the book's tokens beside the rest.+ let mut page_query = query.clone();+ for key in ["syncToken", "prefToken"] {+ if let Some(token) = body.get(key).and_then(Value::as_str) {+ page_query.push((key.into(), token.to_string()));+ }+ }+ page_query.push(("offset".into(), have.to_string()));+ page_query.push(("limit".into(), "500".into()));+ let url = format!("{}/co/contacts/card/", root.trim_end_matches('/'));+ let response = http.get(url).query(&page_query).send().await?;+ if response.status().as_u16() == 450 {+ return Err(Error::ReauthRequired);+ }+ if !response.status().is_success() {+ return Err(Error::Protocol(format!(+ "Apple stopped part-way through the address book ({}), so it was not stored short.",+ response.status()+ )));+ }+ let page: Value = response.json().await?;+ let more = page+ .get("contacts")+ .and_then(Value::as_array)+ .cloned()+ .unwrap_or_default();+ if more.is_empty() {+ return Err(Error::Protocol(+ "Apple listed more contacts than it would send, so the address book was not stored short."+ .into(),+ ));+ }+ have += more.len();+ if let Some(Value::Array(all)) = body.get_mut("contacts") {+ all.extend(more);+ }+ }+ Ok(body)}/// Store a fetched address book. Touches no network.@@ -1103,6 +1157,66 @@ mod list_tests {mod tests {use super::*;+ /// A book whose startup names more cards than it holds is read to the end, a page at a+ /// time with its tokens, as icloud.com reads one — never stored short.+ #[tokio::test]+ async fn a_large_book_is_read_to_the_end() {+ use wiremock::matchers::{method, path, query_param};+ use wiremock::{Mock, MockServer, ResponseTemplate};+ let server = MockServer::start().await;+ let card = |id: &str| serde_json::json!({ "contactId": id, "firstName": id });+ Mock::given(method("GET"))+ .and(path("/co/startup"))+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({+ "syncToken": "S", "prefToken": "P",+ "contactsOrder": ["a", "b", "c"], "contacts": [card("a")], "groups": []+ })))+ .mount(&server)+ .await;+ Mock::given(method("GET"))+ .and(path("/co/contacts/card/"))+ .and(query_param("offset", "1"))+ .and(query_param("syncToken", "S"))+ .and(query_param("prefToken", "P"))+ .respond_with(+ ResponseTemplate::new(200)+ .set_body_json(serde_json::json!({ "contacts": [card("b"), card("c")] })),+ )+ .mount(&server)+ .await;+ let book = fetch(&reqwest::Client::new(), &server.uri(), vec![])+ .await+ .unwrap();+ let ids: Vec<_> = book.contacts.iter().map(|c| c.guid.as_str()).collect();+ assert_eq!(ids, ["a", "b", "c"]);+ }++ /// Apple naming cards it then will not send is a failure, not a smaller address book.+ #[tokio::test]+ async fn a_book_apple_will_not_finish_is_refused_not_stored_short() {+ use wiremock::matchers::{method, path};+ use wiremock::{Mock, MockServer, ResponseTemplate};+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/co/startup"))+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({+ "syncToken": "S", "prefToken": "P", "contactsOrder": ["a", "b"],+ "contacts": [{ "contactId": "a" }], "groups": []+ })))+ .mount(&server)+ .await;+ Mock::given(method("GET"))+ .and(path("/co/contacts/card/"))+ .respond_with(+ ResponseTemplate::new(200).set_body_json(serde_json::json!({ "contacts": [] })),+ )+ .mount(&server)+ .await;+ assert!(fetch(&reqwest::Client::new(), &server.uri(), vec![])+ .await+ .is_err());+ }+#[test]fn a_changeset_says_whether_anything_moved() {let mut t = Tokens {diff --git a/crates/quince-icloud/src/drive.rs b/crates/quince-icloud/src/drive.rsindex 5c06ecd..61c5bac 100644--- a/crates/quince-icloud/src/drive.rs+++ b/crates/quince-icloud/src/drive.rs@@ -286,6 +286,66 @@ fn created_folder(body: &Value, name: &str) -> Result<DriveItem> {.ok_or_else(|| Error::Protocol("Drive's answer described the folder without an id".into()))}+/// Create many folders inside `parent_id` in one request, as `createFolders` takes them — a+/// folder of 256 folders (a git repository's `objects`) is one round trip, not 256. Each name+/// answers with its new folder's id, or why it was not made; the answer is matched by the+/// `clientId` each was sent with.+pub async fn create_folders(+ http: &reqwest::Client,+ root: &str,+ params: Vec<(String, String)>,+ parent_id: &str,+ names: &[String],+) -> Result<Vec<(String, std::result::Result<String, String>)>> {+ let mut out = Vec::with_capacity(names.len());+ for chunk in names.chunks(100) {+ let asked: Vec<(String, String)> = chunk+ .iter()+ .map(|n| (n.trim().to_string(), uuid::Uuid::new_v4().to_string()))+ .collect();+ let body = json!({+ "destinationDrivewsId": parent_id,+ "folders": asked.iter().map(|(name, id)| json!({ "name": name, "clientId": id })).collect::<Vec<_>>(),+ });+ let url = format!("{}/createFolders", root.trim_end_matches('/'));+ let reply = post_json(http, &url, ¶ms, &body).await?;+ let made: Vec<Value> = reply+ .get("folders")+ .and_then(Value::as_array)+ .cloned()+ .unwrap_or_default();+ for (name, client_id) in asked {+ let folder = made+ .iter()+ .find(|f| f.get("clientId").and_then(Value::as_str) == Some(client_id.as_str()))+ .or_else(|| {+ made.iter()+ .find(|f| f.get("name").and_then(Value::as_str) == Some(name.as_str()))+ });+ let result = match folder {+ Some(f)+ if f.get("status")+ .and_then(Value::as_str)+ .is_none_or(|s| s == "OK") =>+ {+ item_from(f).map(|i| i.drivewsid).ok_or_else(|| {+ "Drive's answer described the folder without an id".to_string()+ })+ }+ Some(f) => Err(format!(+ "iCloud Drive didn't create \u{201c}{name}\u{201d} ({}).",+ f.get("status").and_then(Value::as_str).unwrap_or("?")+ )),+ None => Err(format!(+ "iCloud Drive said nothing about \u{201c}{name}\u{201d}."+ )),+ };+ out.push((name, result));+ }+ }+ Ok(out)+}+/// Create a folder inside `parent_id`. Returns the item Apple stored.pub async fn create_folder(http: &reqwest::Client,@@ -446,31 +506,71 @@ pub async fn delete(.and_then(|i| i.etag.clone()).or_else(|| item.etag.clone());+ // As icloud.com sends it (main.js, module 2231): the id, the etag, and the item's own id+ // as `clientId`; and the answer read per item — only "OK" is done. A folder still taking+ // uploads changes its etag with every file that lands, so the etag read a moment ago is+ // already old: Apple answered 200 and refused it inside, and the folder stayed where it+ // was. A stale etag is tried again with the one Apple sent back.let url = format!("{}/moveItemsToTrash", root.trim_end_matches('/'));- let body = json!({- "items": [{ "drivewsid": item.drivewsid, "etag": etag }],- });-- let response = http.post(url).query(¶ms).json(&body).send().await?;- let status = response.status();- if status.as_u16() == 450 {- return Err(Error::ReauthRequired);- }- if !status.is_success() {- let text = response.text().await.unwrap_or_default();- return Err(Error::Protocol(format!(- "Drive refused the delete ({status}): {}",- text.chars().take(200).collect::<String>()- )));+ let mut etag = etag;+ // Measured: deleting a folder while files went on landing in it met ETAG_CONFLICT on+ // three tries in a row — each file landing moved the etag again within the second. The+ // uploads into it are stopped first; the ones already being filed finish within seconds,+ // so the delete keeps trying, spaced out, with the etag Apple says it has now.+ let waits = [0u64, 400, 800, 1500, 2500, 3500];+ for (attempt, wait) in waits.iter().enumerate() {+ if *wait > 0 {+ tokio::time::sleep(std::time::Duration::from_millis(*wait)).await;+ }+ let body = json!({+ "items": [{ "drivewsid": item.drivewsid, "etag": etag, "clientId": item.drivewsid }],+ });+ let reply = post_json(http, &url, ¶ms, &body).await?;+ let answer = reply+ .get("items")+ .and_then(Value::as_array)+ .and_then(|items| {+ items.iter().find(|i| {+ i.get("drivewsid").and_then(Value::as_str) == Some(item.drivewsid.as_str())+ })+ })+ .cloned();+ match answer+ .as_ref()+ .and_then(|a| a.get("status"))+ .and_then(Value::as_str)+ {+ Some("OK") | None => break,+ Some("ETAG_CONFLICT") if attempt + 1 < waits.len() => {+ etag = answer+ .as_ref()+ .and_then(|a| a.get("etag"))+ .and_then(Value::as_str)+ .map(str::to_string)+ .or(etag);+ }+ Some(other) => {+ return Err(Error::Refused(format!(+ "iCloud Drive did not let that be deleted ({other})."+ )));+ }+ }}- let after = folder_listing(http, root, ¶ms, parent).await?;- if after.iter().any(|i| i.drivewsid == item.drivewsid) {- return Err(Error::Protocol(- "Apple answered success but the item is still in the folder".into(),- ));+ // A large folder takes Apple a moment to move: looked for a few times before it is said+ // to have stayed.+ for wait in [0u64, 800, 1500, 2500] {+ if wait > 0 {+ tokio::time::sleep(std::time::Duration::from_millis(wait)).await;+ }+ let after = folder_listing(http, root, ¶ms, parent).await?;+ if !after.iter().any(|i| i.drivewsid == item.drivewsid) {+ return Ok(());+ }}- Ok(())+ Err(Error::Refused(+ "iCloud answered, but the item is still in the folder — try again in a moment.".into(),+ ))}/// Duplicate a file as icloud.com does: `POST {docws}/v1/item/copy/{item_id}` with@@ -764,7 +864,55 @@ pub async fn out_of_trash_many(endpoint: &str,what: &str,) -> Result<Vec<(String, String)>> {+ // Fifty at a time: hundreds in one request — a Recently Deleted filled by a folder upload+ // — was too large for the connection, and nothing was deleted at all. A dropped connection+ // is tried once more before the rest is reported.+ // Recently Deleted is read once before every batch and once after them all — not twice a+ // batch: a large one takes seconds to read, and sixty items took most of a minute and a+ // half that way.let current = folder_listing(http, root, ¶ms, TRASH).await?;+ let mut failed = Vec::new();+ for chunk in items.chunks(50) {+ let mut outcome =+ out_of_trash_batch(http, root, params.clone(), chunk, endpoint, what, ¤t).await;+ if matches!(outcome, Err(Error::Network(_))) {+ tokio::time::sleep(std::time::Duration::from_millis(800)).await;+ outcome =+ out_of_trash_batch(http, root, params.clone(), chunk, endpoint, what, ¤t)+ .await;+ }+ match outcome {+ Ok(f) => failed.extend(f),+ Err(e) => failed.extend(+ chunk+ .iter()+ .map(|item| (item.drivewsid.clone(), e.to_string())),+ ),+ }+ }+ let after = folder_listing(http, root, ¶ms, TRASH).await?;+ for item in items {+ if after.iter().any(|i| i.drivewsid == item.drivewsid)+ && !failed.iter().any(|(id, _)| id == &item.drivewsid)+ {+ failed.push((+ item.drivewsid.clone(),+ format!("iCloud answered, but the item is still in Recently Deleted, so it was not {what}."),+ ));+ }+ }+ Ok(failed)+}++async fn out_of_trash_batch(+ http: &reqwest::Client,+ root: &str,+ params: Vec<(String, String)>,+ items: &[DriveItem],+ endpoint: &str,+ what: &str,+ current: &[DriveItem],+) -> Result<Vec<(String, String)>> {let mut failed: Vec<(String, String)> = Vec::new();// Each with the etag Apple has for it now.let mut todo: Vec<(DriveItem, Option<String>)> = Vec::new();@@ -830,17 +978,6 @@ pub async fn out_of_trash_many(format!("That item changed in iCloud Drive, so it was not {what}."),));}- let after = folder_listing(http, root, ¶ms, TRASH).await?;- for item in items {- if after.iter().any(|i| i.drivewsid == item.drivewsid)- && !failed.iter().any(|(id, _)| id == &item.drivewsid)- {- failed.push((- item.drivewsid.clone(),- format!("iCloud answered, but the item is still in Recently Deleted, so it was not {what}."),- ));- }- }Ok(failed)}@@ -2156,32 +2293,92 @@ async fn upload_once(// No answer is not "not filed": Apple may have filed it and the reply been lost. Asked// again from the start, the file would go up a second time beside the first — "photo// 2.jpg". The slot's document id is this file's alone, so the folder says which.+ // So is "something with that name is already there": measured on a busy zone, the+ // first try was filed, the answer to it lost, and the retry met the file itself. It is+ // asked for by its own id, which is current the moment it is filed, where the folder's+ // listing can lag behind it.Err(e @ (Error::Network(_) | Error::Refused(_))) => {let id = format!("FILE::{DOCUMENTS_ZONE}::{document_id}");- match folder_listing(http, drivews_root, ¶ms, folder_id).await {- Ok(items)- if items- .iter()- .any(|i| i.drivewsid == id && i.size == Some(size as i64)) =>- {- id- }- _ => return Err(e),+ match item_details(http, drivews_root, ¶ms, &id).await {+ Ok(Some(item)) if item.size == Some(size as i64) => id,+ _ => match folder_listing(http, drivews_root, ¶ms, folder_id).await {+ Ok(items)+ if items+ .iter()+ .any(|i| i.drivewsid == id && i.size == Some(size as i64)) =>+ {+ id+ }+ _ => return Err(e),+ },}}Err(e) => return Err(e),};- // Apple answers 200 to writes it did not make. The folder is the only witness that counts.- let after = folder_listing(http, drivews_root, ¶ms, folder_id).await?;- after- .into_iter()- .find(|i| i.drivewsid == stored)- .ok_or_else(|| {- Error::Protocol(format!(- "Apple accepted {name} but the folder does not hold it"- ))+ // Apple answers 200 to writes it did not make, so the document is read back from Apple:+ // itself, by id, as icloud.com reads an item (`retrieveItemDetails`) — it must be there,+ // in this folder, at this size. Reading the whole folder back instead took six of the+ // nine seconds "Checking" lasted for a 40 MB file in a full folder, for every file sent.+ let found = item_details(http, drivews_root, ¶ms, &stored).await?;+ match found {+ Some(item)+ if item.parent_id.as_deref() == Some(folder_id) && item.size == Some(size as i64) =>+ {+ Ok(item)+ }+ Some(item) if item.parent_id.as_deref() != Some(folder_id) => {+ // A parent named another way (the root by its own id) is checked against the+ // folder itself, rather than trusted or refused on the spelling.+ let listed = folder_listing(http, drivews_root, ¶ms, folder_id).await?;+ listed+ .into_iter()+ .find(|i| i.drivewsid == stored)+ .ok_or_else(|| {+ Error::Protocol(format!(+ "Apple accepted {name} but the folder does not hold it"+ ))+ })+ }+ Some(_) => Err(Error::Protocol(format!(+ "Apple holds {name} at a different size from the file sent"+ ))),+ None => Err(Error::Protocol(format!(+ "Apple accepted {name} but the folder does not hold it"+ ))),+ }+}++/// One item as Apple holds it now, by id (`retrieveItemDetails`, as icloud.com reads one).+/// `None` when Apple has no such item.+async fn item_details(+ http: &reqwest::Client,+ root: &str,+ params: &[(String, String)],+ drivewsid: &str,+) -> Result<Option<DriveItem>> {+ let url = format!("{}/retrieveItemDetails", root.trim_end_matches('/'));+ let reply = post_json(+ http,+ &url,+ params,+ &json!({ "items": [{ "drivewsid": drivewsid, "includeHierarchy": false }] }),+ )+ .await?;+ Ok(reply+ .get("items")+ .and_then(Value::as_array)+ .and_then(|items| {+ items+ .iter()+ .find(|i| i.get("drivewsid").and_then(Value::as_str) == Some(drivewsid))+ })+ .filter(|i| {+ i.get("status")+ .and_then(Value::as_str)+ .is_none_or(|s| s == "OK")})+ .and_then(item_from))}/// The id of the document an `add_file` reply describes, once it is shown to be the file sent.@@ -2234,6 +2431,18 @@ async fn post_json(.and_then(|v| v.to_str().ok()).and_then(|v| v.trim().parse::<u64>().ok());let text = response.text().await.unwrap_or_default();+ // A 409 is not always a name taken. Measured with three files going into one folder:+ // `ZONE_BUSY` — "Sync zone CAS Op-Lock failed. There was a concurrent write and this+ // operation was rejected. Retry request" — two writes to the zone at once, the second+ // turned away and asked to come again. Read as "something with that name is already+ // there", five of twenty-four files were reported as not uploaded. It is retried, after a+ // short pause that differs per request so the writers stop colliding.+ let zone_busy = status.as_u16() == 409 && text.contains("ZONE_BUSY");+ if zone_busy && tries < 6 {+ let jitter = u64::from(uuid::Uuid::new_v4().as_bytes()[0]) * 2;+ tokio::time::sleep(std::time::Duration::from_millis(250 * tries + jitter)).await;+ continue;+ }if !matches!(status.as_u16(), 429 | 500 | 502 | 503 | 504) || tries >= 3 {break (status, text);}@@ -2252,6 +2461,9 @@ async fn post_json("drive: {url} answered {status}: {}",text.chars().take(300).collect::<String>());+ if status.as_u16() == 409 && text.contains("ZONE_BUSY") {+ return Err(Error::Refused(BUSY.into()));+ }return Err(Error::Refused(match status.as_u16() {429 | 500..=599 => {"iCloud Drive is busy right now — try this one again in a minute.".into()@@ -2485,6 +2697,15 @@ mod app_library_tests {}]))).mount(&server).await;+ // And the document itself, read back by id as uploads now confirm it.+ Mock::given(method("POST"))+ .and(path_regex(r".*/retrieveItemDetails$"))+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "items": [{+ "drivewsid": "FILE::com.apple.CloudDocs::D1", "parentId": "FOLDER::com.apple.CloudDocs::root",+ "name": "quince-lost-reply", "extension": "txt", "type": "FILE", "size": 5, "status": "OK"+ }]})))+ .mount(&server)+ .await;let file = std::env::temp_dir().join("quince-lost-reply.txt");std::fs::write(&file, b"hello").unwrap();let item = upload(diff --git a/crates/quince-icloud/src/lib.rs b/crates/quince-icloud/src/lib.rsindex 39a74e5..2a707e8 100644--- a/crates/quince-icloud/src/lib.rs+++ b/crates/quince-icloud/src/lib.rs@@ -9,6 +9,7 @@ pub mod cloudkit;pub mod contacts;pub mod drive;pub mod mergeable;+pub mod note_media;pub mod notes;pub mod occasions;pub mod push;@@ -19,7 +20,9 @@ pub mod topotext;#[derive(Debug, thiserror::Error)]pub enum Error {- #[error("couldn't reach iCloud: {0}")]+ /// Said in words, never with the address: an address carries the account's id and this+ /// install's client id, and was shown on screen whole.+ #[error("{}", network_words(.0))]Network(#[from] reqwest::Error),#[error("iCloud sent back something unexpected: {0}")]Protocol(String),@@ -45,3 +48,16 @@ pub enum Error {}pub type Result<T> = std::result::Result<T, Error>;++/// What went wrong reaching Apple, in words a person can act on — the address left out.+fn network_words(e: &reqwest::Error) -> String {+ if e.is_timeout() {+ "iCloud took too long to answer. Check your connection and try again.".into()+ } else if e.is_connect() {+ "Couldn't reach iCloud. Check your connection and try again.".into()+ } else if e.is_body() || e.is_decode() {+ "iCloud's answer was cut off. Try again.".into()+ } else {+ "The connection to iCloud dropped. Try again.".into()+ }+}diff --git a/crates/quince-icloud/src/note_media.rs b/crates/quince-icloud/src/note_media.rsnew file mode 100644index 0000000..c4bceca--- /dev/null+++ b/crates/quince-icloud/src/note_media.rs@@ -0,0 +1,261 @@+//! What a note holds besides text and tables: pictures, scans, PDFs, recordings, films and+//! other files — read so a note can show them where they sit and open them.+//!+//! Measured on a real account: an `Attachment` record names its kind (`UTIEncrypted`, e.g.+//! `public.jpeg`, `com.apple.paper.doc.pdf`, `com.apple.m4a-audio`) and points by its `Media`+//! reference at a `Media` record, whose `Asset` is the file itself (`downloadURL`) and whose+//! `FilenameEncrypted` is its name. Pictures, scans, PDFs and films also carry+//! `PreviewImages` — small renderings, a few at different sizes — with `PreviewWidths` /+//! `PreviewHeights`, and pictures their `Width` / `Height`. Every asset is served as+//! `application/octet-stream`, so what a file is gets read from its own bytes.+//!+//! Asset addresses expire, so the records are looked up fresh each time a file is fetched.++use crate::cloudkit::ZoneClient;+use crate::{Error, Result};+use serde::Serialize;+use serde_json::Value;++const CONTAINER: &str = "com.apple.notes";+const ZONE: &str = "Notes";++/// What an attachment is, to draw it in its note.+#[derive(Debug, Clone, Serialize, PartialEq)]+#[serde(rename_all = "camelCase")]+pub struct AttachmentInfo {+ pub id: String,+ pub uti: String,+ /// `image`, `document` (PDF, scan), `audio`, `video`, or `file`.+ pub kind: &'static str,+ pub filename: Option<String>,+ pub title: Option<String>,+ pub width: Option<f64>,+ pub height: Option<f64>,+ pub size: Option<i64>,+ /// Whether Apple keeps a rendering of it to show in place of the file.+ pub has_preview: bool,+}++/// The kind of thing a type identifier names, as Notes draws it.+#[must_use]+pub fn kind_of(uti: &str) -> &'static str {+ let u = uti.to_ascii_lowercase();+ if matches!(+ u.as_str(),+ "public.jpeg"+ | "public.png"+ | "public.heic"+ | "public.heif"+ | "com.compuserve.gif"+ | "public.tiff"+ | "org.webmproject.webp"+ | "public.image"+ ) {+ "image"+ } else if u.contains("pdf") || u.contains("scan") {+ "document"+ } else if u.contains("audio") || u.ends_with(".mp3") || u.contains("m4a") {+ "audio"+ } else if u.contains("movie")+ || u.contains("video")+ || u.contains("mpeg-4") && !u.contains("audio")+ {+ "video"+ } else {+ "file"+ }+}++fn decoded(record: &Value, field: &str) -> Option<String> {+ use base64::Engine;+ let v = record+ .pointer(&format!("/fields/{field}/value"))?+ .as_str()?;+ let bytes = base64::engine::general_purpose::STANDARD.decode(v).ok()?;+ let text = String::from_utf8(bytes).ok()?;+ let t = text.trim().to_string();+ (!t.is_empty()).then_some(t)+}++fn number(record: &Value, field: &str) -> Option<f64> {+ record.pointer(&format!("/fields/{field}/value"))?.as_f64()+}++/// What the attachment is, read from Apple now.+pub async fn info(+ http: &reqwest::Client,+ ckdatabasews_root: &str,+ params: Vec<(String, String)>,+ id: &str,+) -> Result<AttachmentInfo> {+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);+ let record = client+ .lookup_record(ZONE, id)+ .await?+ .ok_or(Error::NotFound)?;+ let uti = decoded(&record, "UTIEncrypted")+ .or_else(|| {+ record+ .pointer("/fields/UTI/value")+ .and_then(Value::as_str)+ .map(str::to_string)+ })+ .unwrap_or_default();+ let media = match record+ .pointer("/fields/Media/value/recordName")+ .and_then(Value::as_str)+ {+ Some(m) => client.lookup_record(ZONE, m).await?,+ None => None,+ };+ // A paper document's file is its PDF, named from its title.+ let paper = media.is_none() && record.pointer("/fields/FallbackPDF/value").is_some();+ let filename = media+ .as_ref()+ .and_then(|m| decoded(m, "FilenameEncrypted"))+ .or_else(|| {+ paper.then(|| {+ format!(+ "{}.pdf",+ decoded(&record, "TitleEncrypted").unwrap_or_else(|| "Document".into())+ )+ })+ });+ Ok(AttachmentInfo {+ id: id.to_string(),+ kind: kind_of(&uti),+ filename,+ title: decoded(&record, "TitleEncrypted"),+ width: number(&record, "Width"),+ height: number(&record, "Height"),+ size: record+ .pointer("/fields/FileSize/value")+ .and_then(Value::as_i64)+ .or_else(|| {+ media+ .as_ref()+ .and_then(|m| m.pointer("/fields/Asset/value/size"))+ .and_then(Value::as_i64)+ })+ .or_else(|| {+ record+ .pointer("/fields/FallbackPDF/value/size")+ .and_then(Value::as_i64)+ }),+ has_preview: record+ .pointer("/fields/PreviewImages/value")+ .and_then(Value::as_array)+ .is_some_and(|a| !a.is_empty()),+ uti,+ })+}++/// Which bytes of an attachment to fetch.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Part {+ /// The file itself.+ File,+ /// Apple's largest rendering of it.+ Preview,+}++async fn download(http: &reqwest::Client, url: &str) -> Result<Vec<u8>> {+ // CloudKit's asset addresses carry a `${f}` for a filename of the caller's choosing.+ let response = http.get(url.replace("${f}", "file")).send().await?;+ if !response.status().is_success() {+ return Err(Error::Protocol(format!(+ "Apple would not hand over that attachment ({})",+ response.status()+ )));+ }+ Ok(response.bytes().await?.to_vec())+}++/// An attachment's bytes, fetched from Apple now.+pub async fn bytes(+ http: &reqwest::Client,+ ckdatabasews_root: &str,+ params: Vec<(String, String)>,+ id: &str,+ part: Part,+) -> Result<Vec<u8>> {+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);+ let record = client+ .lookup_record(ZONE, id)+ .await?+ .ok_or(Error::NotFound)?;+ match part {+ Part::Preview => {+ let previews = record+ .pointer("/fields/PreviewImages/value")+ .and_then(Value::as_array)+ .cloned()+ .unwrap_or_default();+ let widths: Vec<f64> = record+ .pointer("/fields/PreviewWidths/value")+ .and_then(Value::as_array)+ .map(|a| a.iter().filter_map(Value::as_f64).collect())+ .unwrap_or_default();+ // The largest Apple keeps.+ let best = (0..previews.len()).max_by(|&a, &b| {+ widths+ .get(a)+ .unwrap_or(&0.0)+ .partial_cmp(widths.get(b).unwrap_or(&0.0))+ .unwrap_or(std::cmp::Ordering::Equal)+ });+ let url = best+ .and_then(|i| previews.get(i))+ .and_then(|p| p.get("downloadURL"))+ .and_then(Value::as_str)+ .ok_or(Error::NotFound)?;+ download(http, url).await+ }+ Part::File => {+ // A PDF or scan made in Notes ("paper") keeps no Media record: its own format is in+ // `PaperDatabase`, and a ready PDF of it in `FallbackPDF` — what any other app opens.+ if let Some(url) = record+ .pointer("/fields/FallbackPDF/value/downloadURL")+ .and_then(Value::as_str)+ {+ if record.pointer("/fields/Media/value/recordName").is_none() {+ return download(http, url).await;+ }+ }+ let media = record+ .pointer("/fields/Media/value/recordName")+ .and_then(Value::as_str)+ .ok_or(Error::NotFound)?;+ let media = client+ .lookup_record(ZONE, media)+ .await?+ .ok_or(Error::NotFound)?;+ let url = media+ .pointer("/fields/Asset/value/downloadURL")+ .and_then(Value::as_str)+ .ok_or(Error::NotFound)?;+ download(http, url).await+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// The kinds measured on a real account, each drawn the way Notes draws it.+ #[test]+ fn each_kind_measured_is_drawn_as_notes_draws_it() {+ assert_eq!(kind_of("public.jpeg"), "image");+ assert_eq!(kind_of("com.apple.paper.doc.pdf"), "document");+ assert_eq!(kind_of("com.apple.paper.doc.scan"), "document");+ assert_eq!(kind_of("com.apple.m4a-audio"), "audio");+ assert_eq!(kind_of("public.mpeg-4-audio"), "audio");+ assert_eq!(kind_of("com.apple.quicktime-movie"), "video");+ assert_eq!(kind_of("org.openxmlformats.spreadsheetml.sheet"), "file");+ assert_eq!(+ kind_of("dyn.ah62d4rv4ge80455crf0gn3dfs3y0g3puqfy1e4psq6"),+ "file"+ );+ }+}diff --git a/crates/quince-icloud/src/notes.rs b/crates/quince-icloud/src/notes.rsindex f970040..6a3c7c9 100644--- a/crates/quince-icloud/src/notes.rs+++ b/crates/quince-icloud/src/notes.rs@@ -988,8 +988,8 @@ pub async fn delete_folder_cloudkit(http: &reqwest::Client,ckdatabasews_root: &str,params: Vec<(String, String)>,- all: &[NoteFolder],- notes: &[Note],+ all_known: &[NoteFolder],+ notes_known: &[Note],guid: &str,) -> Result<()> {if guid == DEFAULT_FOLDER || guid == quince_core::notes::TRASH_FOLDER {@@ -997,6 +997,18 @@ pub async fn delete_folder_cloudkit("Apple's own folders can't be deleted.".into(),));}+ // The folders and notes as Apple holds them now, not as this computer last read them: a+ // note filed in the folder on a phone since the last sync was not in the list this was+ // handed, was not moved to Recently Deleted, and was left filed in a folder that no longer+ // existed. Without a fresh answer nothing is deleted.+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params.clone());+ let walk = client.all_records(ZONE, None).await?;+ let fresh_folders: Vec<NoteFolder> = walk.records.iter().filter(|r| r["recordType"] == "Folder").filter_map(folder_from_record).collect();+ let fresh_notes: Vec<Note> = walk.records.iter().filter(|r| r["recordType"] == "Note").filter_map(note_from_record).collect();+ let (all, notes) = if walk.complete { (&fresh_folders[..], &fresh_notes[..]) } else {+ return Err(Error::Refused("Couldn't read all of this folder from iCloud just now, so nothing was deleted — try again.".into()));+ };+ let _ = (all_known, notes_known);// This folder, then every folder under it, deepest last.let mut doomed = vec![guid.to_string()];let mut i = 0;@@ -1023,7 +1035,6 @@ pub async fn delete_folder_cloudkit().await?;}- let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);for folder in doomed.iter().rev() {if client.lookup_record(ZONE, folder).await?.is_some() {client.delete_record(ZONE, folder).await?;@@ -2395,3 +2406,48 @@ mod derived_title_tests {assert_eq!(note_from_record(&record(None)).unwrap().title, "New Note");}}++/// Change one cell of a Notes table, as a device edits it.+///+/// Recomputed from Apple's own current copy of the table and written against its exact+/// version (see [`ZoneClient::edit_record`]), so an edit made on a phone meanwhile is never+/// written over. Only a cell already typed in can be changed — see+/// [`crate::table::with_cell`] — and a table this cannot rewrite exactly is refused, not+/// written. Answers the cells as Apple now holds them.+pub async fn set_table_cell_cloudkit(+ http: &reqwest::Client,+ ckdatabasews_root: &str,+ params: Vec<(String, String)>,+ attachment: &str,+ row: usize,+ column: usize,+ text: &str,+) -> Result<Vec<Vec<String>>> {+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);+ client+ .edit_record(ZONE, attachment, "Attachment", |record| {+ let current = record+ .pointer("/fields/MergeableDataEncrypted/value")?+ .as_str()?;+ let edited = crate::table::with_cell_in_base64(current, row, column, text)?;+ Some(serde_json::json!({+ "MergeableDataEncrypted": { "type": "ENCRYPTED_BYTES", "value": edited }+ }))+ })+ .await?+ .ok_or_else(|| {+ Error::Refused(+ "That cell can’t be changed here yet — only cells already typed in can.".into(),+ )+ })?;+ // Apple's answer to the write does not carry the table back (measured), so what it now+ // holds is read from it.+ client+ .lookup_record(ZONE, attachment)+ .await?+ .ok_or(Error::NotFound)?+ .pointer("/fields/MergeableDataEncrypted/value")+ .and_then(Value::as_str)+ .and_then(crate::table::cells_from_base64)+ .ok_or_else(|| Error::Protocol("Apple kept a table this cannot read back".into()))+}diff --git a/crates/quince-icloud/src/table.rs b/crates/quince-icloud/src/table.rsindex 7d6fa75..1af1ec0 100644--- a/crates/quince-icloud/src/table.rs+++ b/crates/quince-icloud/src/table.rs@@ -225,6 +225,151 @@ impl<'a> Doc<'a> {}}+fn put_varint(mut v: u64, out: &mut Vec<u8>) {+ loop {+ let byte = (v & 0x7f) as u8;+ v >>= 7;+ if v == 0 {+ out.push(byte);+ return;+ }+ out.push(byte | 0x80);+ }+}++/// `message` with the `nth` length-delimited field `tag` replaced by `payload`, every other+/// byte copied through. `None` when there is no such field.+fn splice(message: &[u8], tag: u64, nth: usize, payload: &[u8]) -> Option<Vec<u8>> {+ let mut out = Vec::with_capacity(message.len() + payload.len());+ let (mut at, mut seen, mut done) = (0usize, 0usize, false);+ while at < message.len() {+ let start = at;+ let (key, next) = varint(message, at)?;+ at = next;+ match key & 7 {+ 0 => at = varint(message, at)?.1,+ 2 => {+ let (n, next) = varint(message, at)?;+ let end = next.checked_add(usize::try_from(n).ok()?)?;+ message.get(next..end)?;+ if key >> 3 == tag && !done {+ if seen == nth {+ put_varint(key, &mut out);+ put_varint(payload.len() as u64, &mut out);+ out.extend_from_slice(payload);+ done = true;+ at = end;+ continue;+ }+ seen += 1;+ }+ at = end;+ }+ 1 => at = at.checked_add(8).filter(|&e| e <= message.len())?,+ 5 => at = at.checked_add(4).filter(|&e| e <= message.len())?,+ _ => return None,+ }+ out.extend_from_slice(message.get(start..at)?);+ }+ done.then_some(out)+}++/// Where a cell's text lives: the index of its text object among the document's objects.+fn cell_object(document: &[u8], row: usize, column: usize) -> Option<usize> {+ let top = fields(document)?;+ let version = fields(bytes(&top, 2).next()?)?;+ let data = fields(bytes(&version, 3).next()?)?;+ let doc = Doc {+ objects: bytes(&data, 3).collect(),+ keys: bytes(&data, 4)+ .map(|k| String::from_utf8_lossy(k).into_owned())+ .collect(),+ uuids: bytes(&data, 6).collect(),+ };+ let root = doc.custom(0)?;+ let at = |name: &str| root.get(name).and_then(|id| object_index(id));+ let by_uuid = doc.uuid_objects();+ let rows = doc.ordered(at("crRows")?, &by_uuid)?;+ let columns = doc.ordered(at("crColumns")?, &by_uuid)?;+ let (_, cells_body) = doc.object(at("cellColumns")?)?;+ let by_column = Doc::dictionary(cells_body)?;+ let inner = *by_column.get(columns.get(column)?)?;+ let cells = Doc::dictionary(doc.object(inner)?.1)?;+ let cell = *cells.get(rows.get(row)?)?;+ // A text object, as a cell's is.+ (doc.object(cell)?.0 == 10).then_some(cell)+}++/// The table's document with one cell's text changed, edited as a device edits it.+///+/// Only a cell already typed in is written: its text object exists, and is rewritten in+/// place with its merge records moved in step (the same rewrite a note's body takes). A cell+/// never typed in has no object yet, and making one is not attempted. Before anything is+/// returned it is proven that the rewrite is exact: written back with the text it already+/// had, the document must come out byte for byte as it was — anything this does not model+/// would break that, and the cell is then left alone.+#[must_use]+pub fn with_cell(document: &[u8], row: usize, column: usize, text: &str) -> Option<Vec<u8>> {+ let cell = cell_object(document, row, column)?;+ let top = fields(document)?;+ let version_bytes = bytes(&top, 2).next()?;+ let version = fields(version_bytes)?;+ let data_bytes = bytes(&version, 3).next()?;+ let data = fields(data_bytes)?;+ let object = bytes(&data, 3).nth(cell)?;+ let string = bytes(&fields(object)?, 10).next()?;+ let old = bytes(&fields(string)?, 2)+ .next()+ .map(|b| String::from_utf8_lossy(b).into_owned())+ .unwrap_or_default();++ let rebuild = |new_text: &str| -> Option<Vec<u8>> {+ let new_string = crate::ckdocument::rewrite_text_object(string, &old, new_text)?;+ let new_object = splice(object, 10, 0, &new_string)?;+ let new_data = splice(data_bytes, 3, cell, &new_object)?;+ let new_version = splice(version_bytes, 3, 0, &new_data)?;+ splice(document, 2, 0, &new_version)+ };+ // The proof: the splice itself, with the string as it was, changes nothing.+ let same = splice(object, 10, 0, string)+ .and_then(|o| splice(data_bytes, 3, cell, &o))+ .and_then(|d| splice(version_bytes, 3, 0, &d))+ .and_then(|v| splice(document, 2, 0, &v))?;+ if same != document {+ return None;+ }+ let out = rebuild(text)?;+ // And what was written reads back as meant.+ let read = cells(&out)?;+ (read.get(row)?.get(column)? == text).then_some(out)+}++/// [`with_cell`] over the attachment's `MergeableDataEncrypted` as Apple sends it (base64,+/// compressed), answered in the same compression it came in.+#[must_use]+pub fn with_cell_in_base64(value: &str, row: usize, column: usize, text: &str) -> Option<String> {+ use base64::Engine;+ use std::io::Write;+ let raw = base64::engine::general_purpose::STANDARD+ .decode(value.trim())+ .ok()?;+ let gz = raw.starts_with(&[0x1f, 0x8b]);+ let plain = inflate(&raw)?;+ let edited = with_cell(&plain, row, column, text)?;+ let packed = if gz {+ let mut e = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());+ e.write_all(&edited).ok()?;+ e.finish().ok()?+ } else if plain != raw {+ let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());+ e.write_all(&edited).ok()?;+ e.finish().ok()?+ } else {+ edited+ };+ Some(base64::engine::general_purpose::STANDARD.encode(packed))+}+/// The table's cells, row by row, from the attachment's `MergeableDataEncrypted` (base64)./// `None` for data that is not a table this understands.#[must_use]diff --git a/packaging/arch/PKGBUILD b/packaging/arch/PKGBUILDindex faa68b2..8de0660 100644--- a/packaging/arch/PKGBUILD+++ b/packaging/arch/PKGBUILD@@ -15,10 +15,11 @@ license=('GPL-3.0-only')# WebKitGTK is what Tauri renders through on Linux, and libsecret is where the session is# kept — the app will start without the second but cannot stay signed in.-# Exactly what the built binary asks for, read off it with ldd rather than guessed: webkit2gtk-# for the window, gtk3 under it, libsecret for the keyring. There is no tray icon, so there is-# no libappindicator either.-depends=('webkit2gtk-4.1' 'gtk3' 'libsecret')+# What the built binary asks for, read off it with ldd rather than guessed — webkit2gtk for+# the window, gtk3 under it, libsecret for the keyring — and the one it loads at run time,+# which ldd cannot see: the tray icon is drawn through libayatana-appindicator, opened when+# the tray is made. Without it the tray, and the alerts' way back into the window, is gone.+depends=('webkit2gtk-4.1' 'gtk3' 'libsecret' 'libayatana-appindicator')makedepends=('rust' 'nodejs' 'npm' 'pkgconf')# makepkg turns link-time optimisation on for everything, which compiles the C and assemblydiff --git a/packaging/aur/.SRCINFO b/packaging/aur/.SRCINFOnew file mode 100644index 0000000..e61926c--- /dev/null+++ b/packaging/aur/.SRCINFO@@ -0,0 +1,23 @@+pkgbase = quince-git+ pkgdesc = Your iCloud, on this computer — calendar, reminders, notes, contacts and Drive+ pkgver = 0.1.0.r0.g0000000+ pkgrel = 1+ url = https://github.com/YashwanthKamireddi/quince+ arch = x86_64+ license = GPL-3.0-only+ makedepends = rust+ makedepends = nodejs+ makedepends = npm+ makedepends = pkgconf+ makedepends = git+ depends = webkit2gtk-4.1+ depends = gtk3+ depends = libsecret+ depends = libayatana-appindicator+ provides = quince+ conflicts = quince+ options = !lto+ source = quince::git+https://github.com/YashwanthKamireddi/quince.git+ sha256sums = SKIP++pkgname = quince-gitdiff --git a/packaging/aur/PKGBUILD b/packaging/aur/PKGBUILDnew file mode 100644index 0000000..0cdbd26--- /dev/null+++ b/packaging/aur/PKGBUILD@@ -0,0 +1,88 @@+# The AUR package: Quince built from the latest source on GitHub, as `yay -S quince-git` or+# `makepkg -si` installs it. The same build and package steps as packaging/arch, which builds+# from a local checkout instead.++pkgname=quince-git+pkgver=0.1.0.r0.g0000000+pkgrel=1+pkgdesc="Your iCloud, on this computer — calendar, reminders, notes, contacts and Drive"+arch=('x86_64')+url="https://github.com/YashwanthKamireddi/quince"+license=('GPL-3.0-only')++# WebKitGTK is what Tauri renders through on Linux, and libsecret is where the session is+# kept — the app will start without the second but cannot stay signed in.+# What the built binary asks for, read off it with ldd rather than guessed — webkit2gtk for+# the window, gtk3 under it, libsecret for the keyring — and the one it loads at run time,+# which ldd cannot see: the tray icon is drawn through libayatana-appindicator, opened when+# the tray is made. Without it the tray, and the alerts' way back into the window, is gone.+depends=('webkit2gtk-4.1' 'gtk3' 'libsecret' 'libayatana-appindicator')+makedepends=('rust' 'nodejs' 'npm' 'pkgconf')++# makepkg turns link-time optimisation on for everything, which compiles the C and assembly+# inside ring and libsqlite3-sys to LLVM bitcode. Rust links its own way and cannot see into+# those archives, so the build failed with several hundred undefined symbols — every SQLite+# entry point and every one of ring's arithmetic primitives. Rust does its own optimising+# here; this only declines to have it done twice, in two languages that disagree about how.+options=('!lto')++provides=('quince')+conflicts=('quince')+makedepends+=('git')+source=("quince::git+https://github.com/YashwanthKamireddi/quince.git")+sha256sums=('SKIP')++_root="$srcdir/quince"++pkgver() {+ cd "$_root"+ # The last tag, and how far past it this build is: 0.1.0.r12.gabc1234.+ printf "%s" "$(git describe --long --tags 2>/dev/null | sed 's/^v//;s/\([^-]*-g\)/r\1/;s/-/./g' || printf "0.1.0.r%s.g%s" "$(git rev-list --count HEAD)" "$(git rev-parse --short HEAD)")"+}++build() {+ cd "$_root"++ # Its own build directory, not the one a developer is using. makepkg builds with its own+ # CFLAGS and LDFLAGS, and cargo reuses whatever C objects it finds — so sharing a target+ # directory with an ordinary `cargo build` produced a binary that would not link at all,+ # with sqlite3 and ring's assembly missing from it.+ export CARGO_TARGET_DIR="$srcdir/target"++ # makepkg builds in a clean environment, which does not carry a rustup installation. The+ # `rust` package puts cargo in /usr/bin and needs nothing here; a rustup one lives in the+ # user's home and would otherwise look simply absent.+ if ! command -v cargo >/dev/null; then+ export PATH="${CARGO_HOME:-$HOME/.cargo}/bin:$PATH"+ fi+ command -v cargo >/dev/null || {+ echo "cargo not found — install the 'rust' package, or put a rustup one on PATH" >&2+ return 1+ }++ npm ci --no-audit --no-fund+ npm run build+ cargo build --release --locked -p quince-app+}++package() {+ cd "$_root"+ # Cargo names the binary after its crate; `tauri build` renames it and this does not go+ # through that, so the rename happens here.+ install -Dm755 "$srcdir/target/release/quince-app" "$pkgdir/usr/bin/quince"+ install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"+ install -Dm644 packaging/dev.quince.client.metainfo.xml \+ "$pkgdir/usr/share/metainfo/dev.quince.client.metainfo.xml"+ # The same entry the .deb and .rpm get, with the names this package uses filled in.+ sed -e 's/{{name}}/Quince/' \+ -e 's/{{comment}}/Your iCloud, on this computer/' \+ -e 's/{{exec}}/quince/g' \+ -e 's/{{icon}}/dev.quince.client/' \+ -e 's/{{categories}}/Office;Calendar;ContactManagement;/' \+ packaging/dev.quince.client.desktop.in \+ > "$srcdir/dev.quince.client.desktop"+ install -Dm644 "$srcdir/dev.quince.client.desktop" \+ "$pkgdir/usr/share/applications/dev.quince.client.desktop"+ install -Dm644 src-tauri/icons/icon.png \+ "$pkgdir/usr/share/icons/hicolor/512x512/apps/dev.quince.client.png"+}diff --git a/probe/Cargo.toml b/probe/Cargo.tomlindex 40c83e9..5a71ca0 100644--- a/probe/Cargo.toml+++ b/probe/Cargo.toml@@ -6,6 +6,7 @@ license.workspace = truepublish = false[dependencies]+futures-util = "0.3"image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }sha1 = "0.10"sha2 = "0.10"diff --git a/probe/examples/cal_invitees.rs b/probe/examples/cal_invitees.rsnew file mode 100644index 0000000..6044800--- /dev/null+++ b/probe/examples/cal_invitees.rs@@ -0,0 +1,60 @@+//! Read-only: how many events this year have invitees, and the shape of one (statuses and+//! flags only, no names or addresses).+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("calendar")+ .ok_or_else(|| anyhow!("no calendar"))?;+ let (http, p) = (client.http().clone(), client.service_params());+ let mut q = p.clone();+ for (k, v) in [+ ("clientVersion", "5.1"),+ ("requestID", "4"),+ ("lang", "en-us"),+ ("usertz", "Asia/Kolkata"),+ ("startDate", "2026-09-01"),+ ("endDate", "2026-12-31"),+ ] {+ q.push((k.into(), v.into()));+ }+ let v: serde_json::Value = http+ .get(format!("{root}/ca/startup"))+ .query(&q)+ .send()+ .await?+ .json()+ .await?;+ let events = v["Event"].as_array().cloned().unwrap_or_default();+ let with: Vec<_> = events+ .iter()+ .filter(|e| e["invitees"].as_array().is_some_and(|a| !a.is_empty()))+ .collect();+ println!(+ "{} events, {} with invitees; Invitee objects: {}",+ events.len(),+ with.len(),+ v["Invitee"].as_array().map_or(0, |a| a.len())+ );+ for i in v["Invitee"].as_array().into_iter().flatten().take(6) {+ println!(+ " status={} isMe={} isOrganizer={} hasName={} hasEmail={}",+ i["inviteeStatus"],+ i["isMe"],+ i["isOrganizer"],+ i["commonName"].is_string(),+ i["email"].is_string()+ );+ }+ println!(+ "inbox items: {}",+ v["InboxItem"].as_array().map_or(0, |a| a.len())+ );+ Ok(())+}diff --git a/probe/examples/contacts_paging.rs b/probe/examples/contacts_paging.rsnew file mode 100644index 0000000..cfe8f57--- /dev/null+++ b/probe/examples/contacts_paging.rs@@ -0,0 +1,44 @@+//! Read-only: does startup hold every card its own order names, and does the page read+//! (co/contacts/card/?offset&limit) answer with cards — counts only.+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());+ let (people, tokens) =+ quince_icloud::contacts::fetch_with_tokens(&http, &root, p.clone()).await?;+ println!("fetched {} cards", people.len());+ let mut q = p.clone();+ q.push(("syncToken".into(), tokens.sync.clone()));+ q.push(("prefToken".into(), tokens.pref.clone()));+ for (k, v) in [+ ("clientVersion", "2.1"),+ ("locale", "en_US"),+ ("order", "last,first"),+ ("offset", "100"),+ ("limit", "50"),+ ] {+ q.push((k.into(), v.into()));+ }+ let r = http+ .get(format!("{root}/co/contacts/card/"))+ .query(&q)+ .send()+ .await?;+ let st = r.status();+ let v: serde_json::Value = r.json().await.unwrap_or_default();+ println!(+ "page offset 100 limit 50: {st}, {} cards, keys {:?}",+ v["contacts"].as_array().map_or(0, |a| a.len()),+ v.as_object().map(|o| o.keys().cloned().collect::<Vec<_>>())+ );+ Ok(())+}diff --git a/probe/examples/drive_cleanup_tests.rs b/probe/examples/drive_cleanup_tests.rsnew file mode 100644index 0000000..cae3c75--- /dev/null+++ b/probe/examples/drive_cleanup_tests.rs@@ -0,0 +1,25 @@+//! Live cleanup: any folder at the top of Drive named "Quince … test" that a probe left+//! behind, moved to Recently Deleted and deleted for good — nothing else is touched.+use anyhow::{anyhow, Result};+use quince_icloud::drive;+const ROOT: &str = "FOLDER::com.apple.CloudDocs::root";+#[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 dws = client.session().service_url("drivews").ok_or_else(|| anyhow!("no drivews"))?;+ let (http, p) = (client.http().clone(), client.service_params());+ let mut lib = quince_core::Library::in_memory()?;+ drive::sync_folder(&http, &dws, p.clone(), &mut lib, ROOT).await?;+ let left: Vec<_> = lib.drive_children(ROOT)?.into_iter()+ .filter(|i| i.is_container() && i.name.starts_with("Quince ") && i.name.ends_with(" test")).collect();+ println!("left behind: {:?}", left.iter().map(|i| &i.name).collect::<Vec<_>>());+ for f in &left { drive::delete(&http, &dws, p.clone(), f).await?; }+ let ids: Vec<_> = left.iter().map(|i| i.drivewsid.clone()).collect();+ let t: Vec<_> = drive::trash(&http, &dws, p.clone()).await?.into_iter().filter(|i| ids.contains(&i.drivewsid)).collect();+ println!("purged, refused: {:?}", drive::delete_forever_many(&http, &dws, p.clone(), &t).await?);+ Ok(())+}diff --git a/probe/examples/drive_create_many.rs b/probe/examples/drive_create_many.rsnew file mode 100644index 0000000..158dcab--- /dev/null+++ b/probe/examples/drive_create_many.rs@@ -0,0 +1,58 @@+//! Live, throwaway only: one "Quince create-many test" folder, then 5 folders made inside it in+//! one createFolders request — each answered with its own id — then all of it purged.+use anyhow::{anyhow, Result};+use quince_icloud::drive;+const ROOT: &str = "FOLDER::com.apple.CloudDocs::root";+#[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 dws = client+ .session()+ .service_url("drivews")+ .ok_or_else(|| anyhow!("no drivews"))?;+ let (http, p) = (client.http().clone(), client.service_params());+ let top = drive::create_folder(&http, &dws, p.clone(), ROOT, "Quince create-many test").await?;+ let names: Vec<String> = ["00", "0a", "1f", "ff", "info"]+ .iter()+ .map(|s| s.to_string())+ .collect();+ let t = std::time::Instant::now();+ let made = drive::create_folders(&http, &dws, p.clone(), &top.drivewsid, &names).await?;+ println!(+ "one request, {:?}: {:?}",+ t.elapsed(),+ made.iter()+ .map(|(n, r)| (n.as_str(), r.is_ok()))+ .collect::<Vec<_>>()+ );+ let mut lib = quince_core::Library::in_memory()?;+ drive::sync_folder(&http, &dws, p.clone(), &mut lib, &top.drivewsid).await?;+ let listed: Vec<String> = lib+ .drive_children(&top.drivewsid)?+ .into_iter()+ .map(|i| i.name)+ .collect();+ println!(+ "folder now holds: {listed:?}; ids match: {}",+ made.iter().all(|(_, r)| r.as_ref().is_ok_and(|id| lib+ .drive_item(id)+ .ok()+ .flatten()+ .is_some()))+ );+ drive::delete(&http, &dws, p.clone(), &top).await?;+ let t = drive::trash(&http, &dws, p.clone())+ .await?+ .into_iter()+ .filter(|i| i.drivewsid == top.drivewsid)+ .collect::<Vec<_>>();+ println!(+ "purged: {:?}",+ drive::delete_forever_many(&http, &dws, p.clone(), &t).await?+ );+ Ok(())+}diff --git a/probe/examples/drive_purge_sixty.rs b/probe/examples/drive_purge_sixty.rsnew file mode 100644index 0000000..9a2de97--- /dev/null+++ b/probe/examples/drive_purge_sixty.rs@@ -0,0 +1,72 @@+//! Live, throwaway only: 60 "Quince purge N" folders made in one request inside a test+//! folder, all moved to Recently Deleted, then deleted for good as Delete All sends them (in+//! fifties) — and Recently Deleted read again to see none of them is left.+use anyhow::{anyhow, Result};+use quince_icloud::drive;+const ROOT: &str = "FOLDER::com.apple.CloudDocs::root";+#[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 dws = client+ .session()+ .service_url("drivews")+ .ok_or_else(|| anyhow!("no drivews"))?;+ let (http, p) = (client.http().clone(), client.service_params());+ let top = drive::create_folder(&http, &dws, p.clone(), ROOT, "Quince purge-sixty test").await?;+ let names: Vec<String> = (0..60).map(|n| format!("Quince purge {n}")).collect();+ let made = drive::create_folders(&http, &dws, p.clone(), &top.drivewsid, &names).await?;+ let ids: Vec<String> = made.into_iter().filter_map(|(_, r)| r.ok()).collect();+ println!("made {}", ids.len());+ // All to Recently Deleted in one request, as a person deleting them would.+ let mut lib = quince_core::Library::in_memory()?;+ drive::sync_folder(&http, &dws, p.clone(), &mut lib, &top.drivewsid).await?;+ let items: Vec<_> = lib+ .drive_children(&top.drivewsid)?+ .into_iter()+ .filter(|i| ids.contains(&i.drivewsid))+ .collect();+ let body = serde_json::json!({ "items": items.iter().map(|i| serde_json::json!({ "drivewsid": i.drivewsid, "etag": i.etag, "clientId": i.drivewsid })).collect::<Vec<_>>() });+ let r = http+ .post(format!("{}/moveItemsToTrash", dws.trim_end_matches('/')))+ .query(&p)+ .json(&body)+ .send()+ .await?;+ println!("to trash: {}", r.status());+ tokio::time::sleep(std::time::Duration::from_secs(3)).await;+ let trash: Vec<_> = drive::trash(&http, &dws, p.clone())+ .await?+ .into_iter()+ .filter(|i| ids.contains(&i.drivewsid))+ .collect();+ println!("{} in Recently Deleted", trash.len());+ let t = std::time::Instant::now();+ let refused = drive::delete_forever_many(&http, &dws, p.clone(), &trash).await?;+ println!(+ "Delete All: {} refused, in {:?}",+ refused.len(),+ t.elapsed()+ );+ tokio::time::sleep(std::time::Duration::from_secs(10)).await;+ let left = drive::trash(&http, &dws, p.clone())+ .await?+ .into_iter()+ .filter(|i| ids.contains(&i.drivewsid))+ .count();+ println!("left in Recently Deleted 10s later: {left}");+ drive::delete(&http, &dws, p.clone(), &top).await?;+ let t = drive::trash(&http, &dws, p.clone())+ .await?+ .into_iter()+ .filter(|i| i.drivewsid == top.drivewsid)+ .collect::<Vec<_>>();+ println!(+ "test folder purged: {:?}",+ drive::delete_forever_many(&http, &dws, p.clone(), &t).await?+ );+ Ok(())+}diff --git a/probe/examples/notes_attachment_kinds.rs b/probe/examples/notes_attachment_kinds.rsnew file mode 100644index 0000000..4535ad6--- /dev/null+++ b/probe/examples/notes_attachment_kinds.rs@@ -0,0 +1,65 @@+//! Read-only: the kinds of attachment the account's notes hold, counted by type, and for one+//! image the fields Apple keeps on it (names only) — what showing pictures in a note needs.+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("ckdatabasews")+ .ok_or_else(|| anyhow!("no ck"))?;+ let (http, p) = (client.http().clone(), client.service_params());+ let zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p.clone());+ let walk = zc.all_records("Notes", None).await?;+ let mut kinds = std::collections::BTreeMap::new();+ let mut shown = 0;+ for r in walk+ .records+ .iter()+ .filter(|r| r["recordType"] == "Attachment" || r["recordType"] == "Media")+ {+ let uti = r["fields"]["UTIEncrypted"]["value"]+ .as_str()+ .map(|s| {+ use base64::Engine;+ String::from_utf8_lossy(+ &base64::engine::general_purpose::STANDARD+ .decode(s)+ .unwrap_or_default(),+ )+ .into_owned()+ })+ .or_else(|| r["fields"]["UTI"]["value"].as_str().map(str::to_string))+ .unwrap_or_else(|| "?".into());+ *kinds+ .entry(format!(+ "{} {}",+ r["recordType"].as_str().unwrap_or(""),+ uti+ ))+ .or_insert(0) += 1;+ if shown < 2+ && (uti.contains("jpeg")+ || uti.contains("png")+ || uti.contains("heic")+ || r["recordType"] == "Media")+ {+ shown += 1;+ println!(+ "{} fields: {:?}",+ r["recordType"],+ r["fields"]+ .as_object()+ .map(|o| o.keys().cloned().collect::<Vec<_>>())+ );+ }+ }+ for (k, n) in kinds {+ println!("{n:4} {k}");+ }+ Ok(())+}diff --git a/probe/examples/notes_folder_delete_stale.rs b/probe/examples/notes_folder_delete_stale.rsnew file mode 100644index 0000000..92e5b84--- /dev/null+++ b/probe/examples/notes_folder_delete_stale.rs@@ -0,0 +1,24 @@+//! Live, throwaway only: a "Quince folder delete test" folder with a note in it, deleted as+//! a stale screen would ask — knowing of neither the note nor anything inside — and then: is+//! the note in Recently Deleted, and the folder gone? The note is left in Recently Deleted.+use anyhow::{anyhow, Result};+use quince_icloud::notes;+#[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 folder = notes::create_folder_cloudkit(&http, &root, p.clone(), "Quince folder delete test", None).await?;+ let note = notes::create_cloudkit(&http, &root, p.clone(), Some(&folder), "Quince folder delete test note\nsafe to delete", None).await?;+ // As a screen that has not yet seen the note, nor the folder's contents.+ notes::delete_folder_cloudkit(&http, &root, p.clone(), &[], &[], &folder).await?;+ let zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p.clone());+ let n = zc.lookup_record("Notes", ¬e).await?;+ let f = zc.lookup_record("Notes", &folder).await?;+ println!("note's folder now: {:?}; folder still there: {}", n.as_ref().and_then(|r| r["fields"]["Folder"]["value"]["recordName"].as_str().map(str::to_string)), f.is_some());+ Ok(())+}diff --git a/probe/examples/notes_media_fetch.rs b/probe/examples/notes_media_fetch.rsnew file mode 100644index 0000000..d0cad64--- /dev/null+++ b/probe/examples/notes_media_fetch.rs@@ -0,0 +1,100 @@+//! Read-only: download the JPEG attachment's full file and its previews, printing only sizes+//! and content types — the bytes are not kept.+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("ckdatabasews")+ .ok_or_else(|| anyhow!("no ck"))?;+ let (http, p) = (client.http().clone(), client.service_params());+ let zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p.clone());+ let walk = zc.all_records("Notes", None).await?;+ use base64::Engine;+ let jpeg = walk+ .records+ .iter()+ .find(|r| {+ r["recordType"] == "Attachment"+ && r["fields"]["UTIEncrypted"]["value"]+ .as_str()+ .map(|s| {+ base64::engine::general_purpose::STANDARD+ .decode(s)+ .unwrap_or_default()+ == b"public.jpeg"+ })+ .unwrap_or(false)+ })+ .ok_or_else(|| anyhow!("no jpeg"))?;+ let id = jpeg["recordName"].as_str().unwrap();+ // Fresh copies: an asset's address expires.+ let att = zc+ .lookup_record("Notes", id)+ .await?+ .ok_or_else(|| anyhow!("gone"))?;+ println!(+ "size {}x{}, previews: widths {:?}",+ att["fields"]["Width"]["value"],+ att["fields"]["Height"]["value"],+ att["fields"]["PreviewWidths"]["value"]+ );+ let get = |url: &str| {+ let url = url.replace("${f}", "file");+ let http = http.clone();+ async move {+ let r = http.get(&url).send().await?;+ let ct = r.headers().get("content-type").cloned();+ let st = r.status();+ let n = r.bytes().await?.len();+ anyhow::Ok(format!("{st} {ct:?} {n} bytes"))+ }+ };+ if let Some(list) = att["fields"]["PreviewImages"]["value"].as_array() {+ for (i, a) in list.iter().enumerate().take(4) {+ if let Some(u) = a["downloadURL"].as_str() {+ println!("preview {i}: {}", get(u).await?);+ } else {+ println!(+ "preview {i}: no url, keys {:?}",+ a.as_object().map(|o| o.keys().cloned().collect::<Vec<_>>())+ );+ }+ }+ }+ let media = att["fields"]["Media"]["value"]["recordName"]+ .as_str()+ .unwrap();+ let m = zc+ .lookup_record("Notes", media)+ .await?+ .ok_or_else(|| anyhow!("no media"))?;+ match m["fields"]["Asset"]["value"]["downloadURL"].as_str() {+ Some(u) => println!("full file: {}", get(u).await?),+ None => println!(+ "media asset keys {:?}",+ m["fields"]["Asset"]["value"]+ .as_object()+ .map(|o| o.keys().cloned().collect::<Vec<_>>())+ ),+ }+ println!(+ "filename: {:?}",+ m["fields"]["FilenameEncrypted"]["value"]+ .as_str()+ .map(|s| String::from_utf8_lossy(+ &base64::engine::general_purpose::STANDARD+ .decode(s)+ .unwrap_or_default()+ )+ .into_owned()+ .chars()+ .count())+ );+ Ok(())+}diff --git a/probe/examples/notes_media_formats.rs b/probe/examples/notes_media_formats.rsnew file mode 100644index 0000000..02568b5--- /dev/null+++ b/probe/examples/notes_media_formats.rs@@ -0,0 +1,57 @@+//! Read-only: for every non-table attachment, the format of its file and its preview as read+//! from their first bytes — what the window will be asked to draw.+use anyhow::{anyhow, Result};+use quince_icloud::note_media::{self, Part};+#[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 zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p.clone());+ let walk = zc.all_records("Notes", None).await?;+ let sniff = |b: &[u8]| match b {+ [0x89, b'P', b'N', b'G', ..] => "png",+ [0xff, 0xd8, 0xff, ..] => "jpeg",+ [b'%', b'P', b'D', b'F', ..] => "pdf",+ [_, _, _, _, b'f', b't', b'y', b'p', ..] => "ftyp(heic/mp4/m4a)",+ [b'P', b'K', ..] => "zip",+ _ => "other",+ };+ for a in walk+ .records+ .iter()+ .filter(|r| r["recordType"] == "Attachment")+ {+ let id = a["recordName"].as_str().unwrap_or("");+ let info = note_media::info(&http, &root, p.clone(), id).await?;+ if info.uti.contains("table") {+ continue;+ }+ let file = note_media::bytes(&http, &root, p.clone(), id, Part::File)+ .await+ .map(|b| sniff(&b).to_string())+ .unwrap_or_else(|e| format!("ERR {e}"));+ let prev = if info.has_preview {+ note_media::bytes(&http, &root, p.clone(), id, Part::Preview)+ .await+ .map(|b| sniff(&b).to_string())+ .unwrap_or_else(|e| format!("ERR {e}"))+ } else {+ "-".into()+ };+ println!(+ "{:10} {:40} file={file:20} preview={prev} name? {}",+ info.kind,+ info.uti,+ info.filename.is_some()+ );+ }+ Ok(())+}diff --git a/probe/examples/notes_media_shape.rs b/probe/examples/notes_media_shape.rsnew file mode 100644index 0000000..025e9d5--- /dev/null+++ b/probe/examples/notes_media_shape.rs@@ -0,0 +1,62 @@+//! Read-only: for each kind of non-table attachment, its field names and types, what it+//! references, and the shape of the Media record it leads to (field names, asset keys only).+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("ckdatabasews")+ .ok_or_else(|| anyhow!("no ck"))?;+ let (http, p) = (client.http().clone(), client.service_params());+ let zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p.clone());+ let walk = zc.all_records("Notes", None).await?;+ use base64::Engine;+ let uti = |r: &serde_json::Value| {+ r["fields"]["UTIEncrypted"]["value"]+ .as_str()+ .map(|s| {+ String::from_utf8_lossy(+ &base64::engine::general_purpose::STANDARD+ .decode(s)+ .unwrap_or_default(),+ )+ .into_owned()+ })+ .unwrap_or_default()+ };+ let mut seen = std::collections::HashSet::new();+ for a in walk+ .records+ .iter()+ .filter(|r| r["recordType"] == "Attachment")+ {+ let u = uti(a);+ if u.contains("table") || !seen.insert(u.clone()) {+ continue;+ }+ println!("== {u}");+ for (k, v) in a["fields"].as_object().into_iter().flatten() {+ let r = v["value"]["recordName"]+ .as_str()+ .map(|n| format!(" -> {n}"))+ .unwrap_or_default();+ println!(" {k}: {}{r}", v["type"]);+ }+ if let Some(m) = a["fields"]["Media"]["value"]["recordName"].as_str() {+ if let Some(media) = walk.records.iter().find(|r| r["recordName"] == m) {+ for (k, v) in media["fields"].as_object().into_iter().flatten() {+ let keys = v["value"]+ .as_object()+ .map(|o| o.keys().cloned().collect::<Vec<_>>());+ println!(" media.{k}: {} {:?}", v["type"], keys);+ }+ }+ }+ }+ Ok(())+}diff --git a/probe/examples/notes_paper_shape.rs b/probe/examples/notes_paper_shape.rsnew file mode 100644index 0000000..5d7dac4--- /dev/null+++ b/probe/examples/notes_paper_shape.rs@@ -0,0 +1,71 @@+//! Read-only: the fields a "paper" document attachment (PDF, scan) carries — names, types,+//! and for assets their keys — to find where its file is kept.+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("ckdatabasews")+ .ok_or_else(|| anyhow!("no ck"))?;+ let (http, p) = (client.http().clone(), client.service_params());+ let zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p.clone());+ let walk = zc.all_records("Notes", None).await?;+ use base64::Engine;+ let mut shown = 0;+ for a in walk+ .records+ .iter()+ .filter(|r| r["recordType"] == "Attachment")+ {+ let uti = a["fields"]["UTIEncrypted"]["value"]+ .as_str()+ .map(|s| {+ String::from_utf8_lossy(+ &base64::engine::general_purpose::STANDARD+ .decode(s)+ .unwrap_or_default(),+ )+ .into_owned()+ })+ .unwrap_or_default();+ if !uti.contains("paper") || shown >= 2 {+ continue;+ }+ shown += 1;+ println!("== {uti}");+ let rec = zc+ .lookup_record("Notes", a["recordName"].as_str().unwrap())+ .await?+ .unwrap();+ for (k, v) in rec["fields"].as_object().into_iter().flatten() {+ let extra = match v["type"].as_str() {+ Some("ASSETID") => format!(+ "{:?}",+ v["value"]+ .as_object()+ .map(|o| o.keys().cloned().collect::<Vec<_>>())+ ),+ Some("REFERENCE") => format!("-> {}", v["value"]["recordName"]),+ Some("ENCRYPTED_BYTES") => {+ format!("{} b64 chars", v["value"].as_str().map_or(0, str::len))+ }+ _ => String::new(),+ };+ println!(" {k}: {} {extra}", v["type"]);+ }+ }+ // Records that are neither Note nor Attachment nor Media, by type.+ let mut types = std::collections::BTreeMap::new();+ for r in &walk.records {+ *types+ .entry(r["recordType"].as_str().unwrap_or("?").to_string())+ .or_insert(0) += 1;+ }+ println!("record types: {types:?}");+ Ok(())+}diff --git a/probe/examples/reminder_subtask_move.rs b/probe/examples/reminder_subtask_move.rsnew file mode 100644index 0000000..052da1b--- /dev/null+++ b/probe/examples/reminder_subtask_move.rs@@ -0,0 +1,84 @@+//! Live, throwaway lists only: a reminder with a subtask moved to another list, the subtask+//! moved after it as the app now does, both read back from Apple — then both lists 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("ckdatabasews")+ .ok_or_else(|| anyhow!("no ck"))?;+ let (http, p) = (client.http().clone(), client.service_params());+ use quince_icloud::reminders as r;+ let a = r::create_list_cloudkit(&http, &root, p.clone(), "Quince move test A").await?;+ let b = r::create_list_cloudkit(&http, &root, p.clone(), "Quince move test B").await?;+ let parent = r::create_cloudkit(&http, &root, p.clone(), &a, "Parent test").await?;+ let child = r::create_cloudkit(&http, &root, p.clone(), &a, "Subtask test").await?;+ let child_r = quince_core::reminders::Reminder {+ guid: child.clone(),+ list_guid: a.clone(),+ title: "Subtask test".into(),+ ..Default::default()+ };+ r::edit_cloudkit(+ &http,+ &root,+ p.clone(),+ &child_r,+ &r::ReminderEdit {+ parent_guid: Some(Some(parent.clone())),+ ..Default::default()+ },+ )+ .await?;+ let zc =+ quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.reminders", p.clone());+ let fresh = |rec: Option<serde_json::Value>| {+ rec.and_then(|r| r["recordChangeTag"].as_str().map(str::to_string))+ };+ let parent_r = quince_core::reminders::Reminder {+ guid: parent.clone(),+ list_guid: a.clone(),+ title: "Parent test".into(),+ etag: fresh(zc.lookup_record("Reminders", &parent).await?),+ ..Default::default()+ };+ let to_b = r::ReminderEdit {+ list_guid: Some(b.clone()),+ ..Default::default()+ };+ r::edit_cloudkit(&http, &root, p.clone(), &parent_r, &to_b).await?;+ let child_r = quince_core::reminders::Reminder {+ etag: fresh(zc.lookup_record("Reminders", &child).await?),+ ..child_r+ };+ r::edit_cloudkit(&http, &root, p.clone(), &child_r, &to_b).await?;+ let list_of = |rec: &serde_json::Value| {+ rec["fields"]["List"]["value"]["recordName"]+ .as_str()+ .unwrap_or("")+ .to_string()+ };+ let pr = zc+ .lookup_record("Reminders", &parent)+ .await?+ .ok_or_else(|| anyhow!("parent gone"))?;+ let cr = zc+ .lookup_record("Reminders", &child)+ .await?+ .ok_or_else(|| anyhow!("child gone"))?;+ println!(+ "parent in B: {}; subtask in B: {}; subtask still under parent: {}",+ list_of(&pr) == b,+ list_of(&cr) == b,+ cr["fields"]["ParentReminder"]["value"]["recordName"].as_str() == Some(parent.as_str())+ );+ r::delete_list_cloudkit(&http, &root, p.clone(), &a).await?;+ r::delete_list_cloudkit(&http, &root, p, &b).await?;+ println!("test lists deleted");+ Ok(())+}diff --git a/probe/examples/table_cell_live.rs b/probe/examples/table_cell_live.rsnew file mode 100644index 0000000..95c5a92--- /dev/null+++ b/probe/examples/table_cell_live.rs@@ -0,0 +1,85 @@+//! Live, on an orphaned table only (one no note's text places, so nothing anyone sees): a+//! typed cell changed through the app's own write, read back from Apple, then put back as it+//! was and read back again.+use anyhow::{anyhow, Result};+#[tokio::main]+async fn main() -> Result<()> {+ let id = std::env::args()+ .nth(1)+ .ok_or_else(|| anyhow!("pass the orphaned attachment id"))?;+ 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 zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p.clone());+ // Refuse anything a note actually shows.+ let walk = zc.all_records("Notes", None).await?;+ let placed = walk+ .records+ .iter()+ .filter(|r| r["recordType"] == "Note")+ .any(|n| {+ n["fields"]["TextDataEncrypted"]["value"]+ .as_str()+ .is_some_and(|b| {+ quince_icloud::ckdocument::runs_from_base64(b)+ .iter()+ .any(|r| r.attachment.as_deref() == Some(id.as_str()))+ })+ });+ if placed {+ return Err(anyhow!("that table is in a note; not touching it"));+ }+ let before = zc+ .lookup_record("Notes", &id)+ .await?+ .ok_or_else(|| anyhow!("gone"))?;+ let raw_before = before["fields"]["MergeableDataEncrypted"]["value"]+ .as_str()+ .unwrap()+ .to_string();+ let cells = quince_icloud::table::cells_from_base64(&raw_before)+ .ok_or_else(|| anyhow!("unreadable"))?;+ let was = cells[0][0].clone();+ let after = quince_icloud::notes::set_table_cell_cloudkit(+ &http,+ &root,+ p.clone(),+ &id,+ 0,+ 0,+ "Quince edit test",+ )+ .await?;+ let reread = zc.lookup_record("Notes", &id).await?.and_then(|r| {+ r["fields"]["MergeableDataEncrypted"]["value"]+ .as_str()+ .and_then(quince_icloud::table::cells_from_base64)+ });+ println!(+ "written: Apple answered {:?}; read back {:?}; others unchanged {}",+ after[0][0],+ reread.as_ref().map(|c| c[0][0].clone()),+ reread+ .as_ref()+ .is_some_and(|c| c.iter().enumerate().all(|(i, row)| row+ .iter()+ .enumerate()+ .all(|(j, x)| (i, j) == (0, 0) || *x == cells[i][j])))+ );+ let restored =+ quince_icloud::notes::set_table_cell_cloudkit(&http, &root, p.clone(), &id, 0, 0, &was)+ .await?;+ println!(+ "restored: {:?} (was {was:?}); whole table as before {}",+ restored[0][0],+ restored == cells+ );+ Ok(())+}diff --git a/probe/examples/table_cell_offline.rs b/probe/examples/table_cell_offline.rsnew file mode 100644index 0000000..663e8a7--- /dev/null+++ b/probe/examples/table_cell_offline.rs@@ -0,0 +1,60 @@+//! Read-only: each table the account holds, a typed cell changed in memory only — never+//! written — to show the rewrite is exact and reads back as meant.+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("ckdatabasews")+ .ok_or_else(|| anyhow!("no ck"))?;+ let (http, p) = (client.http().clone(), client.service_params());+ let zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p.clone());+ let walk = zc.all_records("Notes", None).await?;+ for a in walk+ .records+ .iter()+ .filter(|r| r["recordType"] == "Attachment")+ {+ let Some(v) = a["fields"]["MergeableDataEncrypted"]["value"].as_str() else {+ continue;+ };+ let Some(cells) = quince_icloud::table::cells_from_base64(v) else {+ continue;+ };+ let typed = cells+ .iter()+ .enumerate()+ .find_map(|(r, row)| row.iter().position(|c| !c.is_empty()).map(|c| (r, c)));+ match typed {+ None => println!(+ "{}x{} table, nothing typed in",+ cells.len(),+ cells.first().map_or(0, Vec::len)+ ),+ Some((r, c)) => {+ let edited = quince_icloud::table::with_cell_in_base64(v, r, c, "Quince edit test");+ let back = edited+ .as_deref()+ .and_then(quince_icloud::table::cells_from_base64);+ println!(+ "{}x{} table, cell ({r},{c}): rewrite {}; reads back {:?}; others unchanged {}",+ cells.len(),+ cells.first().map_or(0, Vec::len),+ if edited.is_some() { "exact" } else { "REFUSED" },+ back.as_ref().map(|b| &b[r][c]),+ back.as_ref()+ .is_some_and(|b| b.iter().enumerate().all(|(i, row)| row+ .iter()+ .enumerate()+ .all(|(j, x)| (i, j) == (r, c) || *x == cells[i][j])))+ );+ }+ }+ }+ Ok(())+}diff --git a/probe/examples/table_cell_set.rs b/probe/examples/table_cell_set.rsnew file mode 100644index 0000000..e12aaf1--- /dev/null+++ b/probe/examples/table_cell_set.rs@@ -0,0 +1,45 @@+//! Live: set one cell of an orphaned table (refused for any table a note places).+use anyhow::{anyhow, Result};+#[tokio::main]+async fn main() -> Result<()> {+ let a: Vec<String> = std::env::args().collect();+ let (id, row, col, text) = (+ a[1].clone(),+ a[2].parse::<usize>()?,+ a[3].parse::<usize>()?,+ a[4].clone(),+ );+ 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 zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p.clone());+ let walk = zc.all_records("Notes", None).await?;+ if walk+ .records+ .iter()+ .filter(|r| r["recordType"] == "Note")+ .any(|n| {+ n["fields"]["TextDataEncrypted"]["value"]+ .as_str()+ .is_some_and(|b| {+ quince_icloud::ckdocument::runs_from_base64(b)+ .iter()+ .any(|r| r.attachment.as_deref() == Some(id.as_str()))+ })+ })+ {+ return Err(anyhow!("that table is in a note; not touching it"));+ }+ let cells =+ quince_icloud::notes::set_table_cell_cloudkit(&http, &root, p, &id, row, col, &text)+ .await?;+ println!("{:?}", cells.into_iter().take(3).collect::<Vec<_>>());+ Ok(())+}diff --git a/probe/examples/table_dump.rs b/probe/examples/table_dump.rsnew file mode 100644index 0000000..44412e6--- /dev/null+++ b/probe/examples/table_dump.rs@@ -0,0 +1,44 @@+//! Read-only: an attachment's table document saved inflated to disk, for study offline.+use anyhow::{anyhow, Result};+#[tokio::main]+async fn main() -> Result<()> {+ let (id, out) = (+ std::env::args().nth(1).ok_or_else(|| anyhow!("id"))?,+ std::env::args().nth(2).ok_or_else(|| anyhow!("out"))?,+ );+ 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 zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p.clone());+ let rec = zc+ .lookup_record("Notes", &id)+ .await?+ .ok_or_else(|| anyhow!("gone"))?;+ use base64::Engine;+ let raw = base64::engine::general_purpose::STANDARD.decode(+ rec["fields"]["MergeableDataEncrypted"]["value"]+ .as_str()+ .unwrap_or(""),+ )?;+ let mut plain = Vec::new();+ use std::io::Read;+ if raw.starts_with(&[0x1f, 0x8b]) {+ flate2::read::GzDecoder::new(&raw[..]).read_to_end(&mut plain)?;+ } else {+ flate2::read::ZlibDecoder::new(&raw[..]).read_to_end(&mut plain)?;+ }+ std::fs::write(&out, &plain)?;+ println!(+ "{} bytes, gzip {}",+ plain.len(),+ raw.starts_with(&[0x1f, 0x8b])+ );+ Ok(())+}diff --git a/probe/examples/table_peek.rs b/probe/examples/table_peek.rsnew file mode 100644index 0000000..d7a2f19--- /dev/null+++ b/probe/examples/table_peek.rs@@ -0,0 +1,30 @@+//! Read-only: one attachment's cells as Apple holds them now.+use anyhow::{anyhow, Result};+#[tokio::main]+async fn main() -> Result<()> {+ let id = std::env::args().nth(1).ok_or_else(|| anyhow!("id"))?;+ 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 zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p.clone());+ let rec = zc+ .lookup_record("Notes", &id)+ .await?+ .ok_or_else(|| anyhow!("gone"))?;+ let v = rec["fields"]["MergeableDataEncrypted"]["value"]+ .as_str()+ .unwrap_or("");+ println!(+ "{:?}",+ quince_icloud::table::cells_from_base64(v)+ .map(|c| c.into_iter().take(3).collect::<Vec<_>>())+ );+ Ok(())+}diff --git a/probe/examples/table_record_shape.rs b/probe/examples/table_record_shape.rsnew file mode 100644index 0000000..29914bd--- /dev/null+++ b/probe/examples/table_record_shape.rs@@ -0,0 +1,24 @@+//! Read-only: the fields an orphaned table attachment carries, with their types.+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("ckdatabasews")+ .ok_or_else(|| anyhow!("no ck"))?;+ let (http, p) = (client.http().clone(), client.service_params());+ let zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p.clone());+ let rec = zc+ .lookup_record("Notes", "f7e8966f-6b1e-4882-880a-5d7ccf00d5e7")+ .await?+ .ok_or_else(|| anyhow!("gone"))?;+ for (k, v) in rec["fields"].as_object().into_iter().flatten() {+ println!("{k}: {}", v["type"]);+ }+ Ok(())+}diff --git a/probe/examples/upload_folder_delete.rs b/probe/examples/upload_folder_delete.rsnew file mode 100644index 0000000..938ea1e--- /dev/null+++ b/probe/examples/upload_folder_delete.rs@@ -0,0 +1,119 @@+//! Live, throwaway only: "Quince folder upload test" made in the root, 24 tiny files sent into+//! it three at a time as the app sends them — each one timed — and the folder deleted while+//! they are still going. Then: does the folder stay gone? Everything is left in Recently+//! Deleted and purged at the end.+use anyhow::{anyhow, Result};+use futures_util::StreamExt;+use quince_icloud::drive;+const ROOT: &str = "FOLDER::com.apple.CloudDocs::root";+#[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 docws = client+ .session()+ .service_url("docws")+ .ok_or_else(|| anyhow!("no docws"))?;+ let dws = client+ .session()+ .service_url("drivews")+ .ok_or_else(|| anyhow!("no drivews"))?;+ let (http, p) = (client.http().clone(), client.service_params());+ let folder =+ drive::create_folder(&http, &dws, p.clone(), ROOT, "Quince folder upload test").await?;+ let tmp = std::env::temp_dir().join("quince-folder-test");+ std::fs::create_dir_all(&tmp)?;+ let files: Vec<_> = (0..24)+ .map(|n| {+ let f = tmp.join(format!("file {n}.txt"));+ std::fs::write(&f, format!("safe to delete {n}")).unwrap();+ f+ })+ .collect();+ let start = std::time::Instant::now();+ let deleting = {+ let (http, dws, p, folder) = (http.clone(), dws.clone(), p.clone(), folder.clone());+ tokio::spawn(async move {+ tokio::time::sleep(std::time::Duration::from_secs(8)).await;+ let t = std::time::Instant::now();+ let r = drive::delete(&http, &dws, p, &folder).await;+ println!(+ "delete at 8s: {:?} after {:?}",+ r.as_ref().map(|_| "ok").map_err(|e| e.to_string()),+ t.elapsed()+ );+ })+ };+ let results: Vec<_> = futures_util::stream::iter(files.iter().cloned().enumerate())+ .map(|(n, f)| {+ let (http, docws, dws, p, id) = (+ http.clone(),+ docws.clone(),+ dws.clone(),+ p.clone(),+ folder.drivewsid.clone(),+ );+ async move {+ let t = std::time::Instant::now();+ let r = drive::upload(+ &http,+ &docws,+ &dws,+ p,+ &id,+ &f,+ std::sync::Arc::new(|_, _| {}),+ )+ .await;+ (+ n,+ t.elapsed(),+ start.elapsed(),+ r.map(|_| ()).map_err(|e| e.to_string()),+ )+ }+ })+ .buffer_unordered(3)+ .collect()+ .await;+ deleting.await?;+ let mut ok = 0;+ for (n, took, at, r) in &results {+ if r.is_ok() {+ ok += 1;+ }+ if *n < 4 || r.is_err() {+ println!("file {n}: {:?} (finished at {:?}) {:?}", took, at, r);+ }+ }+ let avg: f64 = results.iter().map(|r| r.1.as_secs_f64()).sum::<f64>() / results.len() as f64;+ println!(+ "{ok}/24 uploaded, average {avg:.1}s each, all done at {:?}",+ start.elapsed()+ );+ tokio::time::sleep(std::time::Duration::from_secs(5)).await;+ let mut lib = quince_core::Library::in_memory()?;+ drive::sync_folder(&http, &dws, p.clone(), &mut lib, ROOT).await?;+ let back = lib+ .drive_children(ROOT)?+ .into_iter()+ .any(|i| i.drivewsid == folder.drivewsid);+ println!("folder back in the root afterwards: {back}");+ // Clean up wherever it is.+ if back {+ let _ = drive::delete(&http, &dws, p.clone(), &folder).await;+ }+ let t = drive::trash(&http, &dws, p.clone())+ .await?+ .into_iter()+ .filter(|i| i.drivewsid == folder.drivewsid)+ .collect::<Vec<_>>();+ println!(+ "purged: {:?}",+ drive::delete_forever_many(&http, &dws, p.clone(), &t).await?+ );+ Ok(())+}diff --git a/probe/examples/upload_phases.rs b/probe/examples/upload_phases.rsnew file mode 100644index 0000000..995c1ea--- /dev/null+++ b/probe/examples/upload_phases.rs@@ -0,0 +1,64 @@+//! Live, throwaway file only: a 40 MB "Quince upload timing test.bin" sent to the root, timing+//! the bytes and then the filing ("Checking") apart, then deleted for good.+use anyhow::{anyhow, Result};+use quince_icloud::drive;+const ROOT: &str = "FOLDER::com.apple.CloudDocs::root";+#[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 docws = client+ .session()+ .service_url("docws")+ .ok_or_else(|| anyhow!("no docws"))?;+ let dws = client+ .session()+ .service_url("drivews")+ .ok_or_else(|| anyhow!("no drivews"))?;+ let (http, p) = (client.http().clone(), client.service_params());+ let tmp = std::env::temp_dir().join("quince-timing");+ std::fs::create_dir_all(&tmp)?;+ let f = tmp.join("Quince upload timing test.bin");+ let mut bytes = vec![0u8; 40 * 1024 * 1024];+ for (i, b) in bytes.iter_mut().enumerate() {+ *b = ((i * 2654435761usize) >> 13) as u8;+ }+ std::fs::write(&f, &bytes)?;+ let start = std::time::Instant::now();+ let sent_at = std::sync::Arc::new(std::sync::Mutex::new(None::<std::time::Duration>));+ let s2 = sent_at.clone();+ let up = drive::upload(+ &http,+ &docws,+ &dws,+ p.clone(),+ ROOT,+ &f,+ std::sync::Arc::new(move |sent, total| {+ if sent >= total {+ s2.lock().unwrap().get_or_insert(start.elapsed());+ }+ }),+ )+ .await?;+ let all = start.elapsed();+ let bytes_done = sent_at.lock().unwrap().unwrap_or_default();+ println!(+ "bytes up after {bytes_done:?}; filed and checked after {all:?} — Checking took {:?}",+ all - bytes_done+ );+ drive::delete(&http, &dws, p.clone(), &up).await?;+ let t = drive::trash(&http, &dws, p.clone())+ .await?+ .into_iter()+ .filter(|i| i.drivewsid == up.drivewsid)+ .collect::<Vec<_>>();+ println!(+ "cleanup refused: {:?}",+ drive::delete_forever_many(&http, &dws, p.clone(), &t).await?+ );+ Ok(())+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex b0efa50..c289f77 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -164,6 +164,202 @@ async fn cloudkit_context(}/// Undo percent-encoding in a path segment. Enough for the ids this scheme carries.+/// The note attachment, and which of its pictures, a `quince://` request asks for:+/// `note/<attachment id>/preview` or `note/<attachment id>/file`, escaped as Tauri escapes it.+fn note_part(path: &str) -> Option<(String, quince_icloud::note_media::Part)> {+ let path = percent_decode(path.trim_start_matches('/'));+ let rest = path.strip_prefix("note/")?;+ let (id, part) = rest.rsplit_once('/')?;+ let part = match part {+ "preview" => quince_icloud::note_media::Part::Preview,+ "file" => quince_icloud::note_media::Part::File,+ _ => return None,+ };+ (!id.is_empty()).then(|| (id.to_string(), part))+}++/// A note attachment's picture, from disk when it has been fetched before, from Apple when+/// not — kept, so a note opens on its pictures at once the next time.+async fn note_media_cached(+ app: &tauri::AppHandle,+ id: &str,+ part: quince_icloud::note_media::Part,+) -> Result<Vec<u8>, String> {+ let safe: String = id+ .chars()+ .map(|c| {+ if c.is_ascii_alphanumeric() || c == '-' {+ c+ } else {+ '_'+ }+ })+ .collect();+ let name = match part {+ quince_icloud::note_media::Part::Preview => "preview",+ quince_icloud::note_media::Part::File => "file",+ };+ let path = state_dir(app)+ .join("note-media")+ .join(format!("{safe}-{name}"));+ if let Ok(bytes) = tokio::fs::read(&path).await {+ return Ok(bytes);+ }+ let (http, root, params) = {+ let auth = app.state::<Auth>();+ let client = auth.client.lock().await;+ let root = client+ .session()+ .service_url("ckdatabasews")+ .ok_or("no CloudKit")?;+ (client.http().clone(), root, client.service_params())+ };+ let bytes = quince_icloud::note_media::bytes(&http, &root, params, id, part)+ .await+ .map_err(|e| e.to_string())?;+ if let Some(dir) = path.parent() {+ tokio::fs::create_dir_all(dir).await.ok();+ }+ tokio::fs::write(&path, &bytes).await.ok();+ Ok(bytes)+}++/// A plain report of how this install is doing, for a bug report: versions, the system, and+/// each service's last sync and last error — never a name, an address, or anything from a+/// note, card or file. Written to Downloads for the person to read and send themselves;+/// Quince sends nothing anywhere.+#[tauri::command]+async fn diagnostics_save(app: tauri::AppHandle, data: State<'_, Data>) -> UiResult<String> {+ let health = {+ let library = data.0.lock().await;+ library.sync_health().map_err(|e| e.to_string())?+ };+ let os = std::fs::read_to_string("/etc/os-release")+ .ok()+ .and_then(|t| {+ t.lines().find(|l| l.starts_with("PRETTY_NAME=")).map(|l| {+ l.trim_start_matches("PRETTY_NAME=")+ .trim_matches('"')+ .to_string()+ })+ })+ .unwrap_or_else(|| std::env::consts::OS.to_string());+ let kernel = std::fs::read_to_string("/proc/sys/kernel/osrelease").unwrap_or_default();+ let session = std::env::var("XDG_SESSION_TYPE").unwrap_or_default();+ let desktop = std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default();+ // Addresses and ids that an error might quote are taken out.+ let scrub = |t: &str| -> String {+ t.split_whitespace()+ .map(|w| {+ if w.contains('@') || w.len() > 24 && w.chars().any(|c| c.is_ascii_digit()) {+ "[…]"+ } else {+ w+ }+ })+ .collect::<Vec<_>>()+ .join(" ")+ };+ let mut out = String::new();+ use std::fmt::Write as _;+ let _ = writeln!(out, "Quince diagnostic report");+ let _ = writeln!(+ out,+ "Quince {} · {} · {} {}",+ app.package_info().version,+ os,+ std::env::consts::ARCH,+ kernel.trim()+ );+ let _ = writeln!(+ out,+ "Desktop: {} ({})",+ if desktop.is_empty() {+ "unknown"+ } else {+ &desktop+ },+ if session.is_empty() {+ "unknown"+ } else {+ &session+ }+ );+ let _ = writeln!(out, "Written: {}", jiff::Timestamp::now());+ let _ = writeln!(out, "\nSync, by service:");+ for h in &health {+ let when = h+ .last_synced_at+ .and_then(|t| jiff::Timestamp::from_second(t).ok())+ .map_or_else(|| "never".into(), |t| t.to_string());+ let _ = writeln!(+ out,+ " {:10} last synced {when}{}",+ h.service,+ h.last_error+ .as_deref()+ .map(|e| format!(" — last error: {}", scrub(e)))+ .unwrap_or_default()+ );+ }+ let dir = app.path().download_dir().map_err(|e| e.to_string())?;+ let path = dir.join(format!(+ "Quince diagnostics {}.txt",+ jiff::Zoned::now().strftime("%Y-%m-%d %H.%M")+ ));+ tokio::fs::write(&path, out)+ .await+ .map_err(|e| e.to_string())?;+ Ok(path.to_string_lossy().into_owned())+}++/// What a note's attachment is, to draw it where it sits.+#[tauri::command]+async fn note_attachment_info(+ id: String,+ auth: State<'_, Auth>,+) -> UiResult<quince_icloud::note_media::AttachmentInfo> {+ let (http, root, params) = cloudkit_context(&auth).await?;+ quince_icloud::note_media::info(&http, &root, params, &id)+ .await+ .map_err(|e| e.to_string())+}++/// Open a note's attachment in the app this computer uses for it: the file is fetched,+/// saved beside the others under its own name, and handed over.+#[tauri::command]+async fn note_attachment_open(+ id: String,+ app: tauri::AppHandle,+ auth: State<'_, Auth>,+) -> UiResult<()> {+ let (http, root, params) = cloudkit_context(&auth).await?;+ let info = quince_icloud::note_media::info(&http, &root, params, &id)+ .await+ .map_err(|e| e.to_string())?;+ let bytes = note_media_cached(&app, &id, quince_icloud::note_media::Part::File).await?;+ let name = info+ .filename+ .filter(|n| !n.contains('/') && !n.starts_with('.'))+ .unwrap_or_else(|| format!("Attachment {}", &id[..id.len().min(8)]));+ let dir = state_dir(&app).join("note-files").join(+ id.chars()+ .filter(char::is_ascii_alphanumeric)+ .collect::<String>(),+ );+ tokio::fs::create_dir_all(&dir)+ .await+ .map_err(|e| e.to_string())?;+ let path = dir.join(name);+ tokio::fs::write(&path, &bytes)+ .await+ .map_err(|e| e.to_string())?;+ use tauri_plugin_opener::OpenerExt;+ app.opener()+ .open_path(path.to_string_lossy(), None::<&str>)+ .map_err(|e| e.to_string())+}+/// The contact a `quince://` request asks for the photo of.////// WebKitGTK reads `quince://photo/<id>` with "photo" as the host, while Tauri's own helper@@ -1027,6 +1223,37 @@ async fn reminder_edit(.await.map_err(|e| e.to_string())?;+ // Moved to another list, a reminder takes its subtasks with it, as on the phone: left+ // behind, they sat in the old list nested under a parent that was no longer in it.+ if let Some(to) = edit.list_guid.as_deref().filter(|to| *to != list_guid) {+ let children: Vec<quince_core::reminders::Reminder> = {+ let library = data.0.lock().await;+ library+ .reminders_in(&list_guid, true)+ .unwrap_or_default()+ .into_iter()+ .filter(|r| r.parent_guid.as_deref() == Some(guid.as_str()))+ .collect()+ };+ let follow = quince_icloud::reminders::ReminderEdit {+ list_guid: Some(to.to_string()),+ ..Default::default()+ };+ for child in &children {+ if let Err(e) = quince_icloud::reminders::edit_cloudkit(+ &http,+ &root,+ params.clone(),+ child,+ &follow,+ )+ .await+ {+ eprintln!("a subtask did not follow its reminder: {e}");+ }+ }+ }+// A due date on its own notifies nobody. Every reminder on a real account that has a// time carries an Alarm pointing at an AlarmTrigger, and one written here used to have// the date and no alarm — so a phone showed the right time and then said nothing when it@@ -1261,6 +1488,31 @@ async fn note_runs(guid: String, data: State<'_, Data>) -> UiResult<serde_json::}/// A table's cells, row by row, as the last pass read them — `None` when none are known.+/// Change one cell of a Notes table, and keep the table as Apple now holds it.+#[tauri::command]+async fn note_table_set_cell(+ id: String,+ row: usize,+ column: usize,+ text: String,+ auth: State<'_, Auth>,+ data: State<'_, Data>,+) -> UiResult<Vec<Vec<String>>> {+ let (http, root, params) = cloudkit_context(&auth).await?;+ let cells = quince_icloud::notes::set_table_cell_cloudkit(+ &http, &root, params, &id, row, column, &text,+ )+ .await+ .map_err(|e| e.to_string())?;+ let mut library = data.0.lock().await;+ if let Ok(json) = serde_json::to_string(&cells) {+ library+ .set_state(&quince_icloud::table::state_key(&id), &json)+ .map_err(|e| e.to_string())?;+ }+ Ok(cells)+}+#[tauri::command]async fn note_table(id: String,@@ -2034,11 +2286,58 @@ struct UploadEvent {within: String,sent: u64,total: u64,- /// `waiting`, `sending`, `verifying`, `done` or `failed`.+ /// `preparing` (a folder being made on Apple), `waiting`, `sending`, `verifying`, `done`,+ /// `failed` or `cancelled`; and once per batch `planned`, when every file in it is known.state: &'static str,+ /// A folder rather than a file: its row stands for making the folder, not for bytes.+ #[serde(default)]+ folder: bool,error: Option<String>,}+/// Uploads that can still be stopped, by id: waiting, or sending their bytes.+fn uploads_running(+) -> &'static std::sync::Mutex<std::collections::HashMap<String, futures_util::future::AbortHandle>>+{+ static RUNNING: std::sync::OnceLock<+ std::sync::Mutex<std::collections::HashMap<String, futures_util::future::AbortHandle>>,+ > = std::sync::OnceLock::new();+ RUNNING.get_or_init(Default::default)+}++/// Batches stopped as a whole: no more of their folders are made or files queued.+fn cancelled_batches() -> &'static std::sync::Mutex<std::collections::HashSet<String>> {+ static CANCELLED: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> =+ std::sync::OnceLock::new();+ CANCELLED.get_or_init(Default::default)+}++fn cancelled(batch: &str) -> bool {+ cancelled_batches().lock().is_ok_and(|b| b.contains(batch))+}++/// Stop uploads: these files, or a whole batch. A file already being filed in iCloud is past+/// stopping and finishes; anything waiting or still sending stops, with nothing of it kept.+#[tauri::command]+fn drive_upload_cancel(ids: Vec<String>, batch: Option<String>) {+ if let Some(batch) = &batch {+ cancelled_batches()+ .lock()+ .map(|mut b| b.insert(batch.clone()))+ .ok();+ }+ if let Ok(running) = uploads_running().lock() {+ for (id, handle) in running.iter() {+ let in_batch = batch+ .as_deref()+ .is_some_and(|b| id.starts_with(&format!("{b}:")));+ if in_batch || ids.contains(id) {+ handle.abort();+ }+ }+ }+}+/// One file to send, and the Drive folder it goes into.struct UploadJob {event: UploadEvent,@@ -2058,7 +2357,7 @@ async fn folder_for(data: &State<'_, Data>,parent: &str,name: &str,-) -> Result<String, String> {+) -> Result<(String, bool), String> {settle(resync_drive_folder(http, root, params.to_vec(), data, parent).await)?;let existing = {let library = data.0.lock().await;@@ -2069,11 +2368,11 @@ async fn folder_for(.find(|i| i.is_container() && i.name.eq_ignore_ascii_case(name))};if let Some(folder) = existing {- return Ok(folder.drivewsid);+ return Ok((folder.drivewsid, false));}quince_icloud::drive::create_folder(http, root, params.to_vec(), parent, name).await- .map(|f| f.drivewsid)+ .map(|f| (f.drivewsid, true)).map_err(|e| e.to_string())}@@ -2083,6 +2382,7 @@ async fn folder_for(/// points outside it would upload something nobody chose.#[allow(clippy::too_many_arguments)]async fn plan_upload(+ app: &tauri::AppHandle,http: &reqwest::Client,root: &str,params: &[(String, String)],@@ -2093,18 +2393,23 @@ async fn plan_upload(failed: &mut Vec<String>,) -> Vec<UploadJob> {let mut jobs = Vec::new();+ let mut folders_made = 0;// (path on disk, Drive folder it goes into, folders below the drop target)- let mut pending: Vec<(std::path::PathBuf, String, String)> = paths+ // (path on disk, Drive folder it goes into, folders below the drop target, and for a+ // folder already made on Apple its id and whether this upload made it)+ #[allow(clippy::type_complexity)]+ let mut pending: Vec<(std::path::PathBuf, String, String, Option<(String, bool)>)> = paths.iter().map(|p| {(std::path::PathBuf::from(p),folder_id.to_string(),String::new(),+ None,)}).collect();- while let Some((path, into, within)) = pending.pop() {+ while let Some((path, into, within, resolved)) = pending.pop() {let name = path.file_name().map_or_else(|| path.display().to_string(),|n| n.to_string_lossy().into(),@@ -2116,10 +2421,42 @@ async fn plan_upload(continue;}};+ if cancelled(batch) {+ break;+ }if meta.is_dir() {- let folder = match folder_for(http, root, params, data, &into, &name).await {- Ok(folder) => folder,+ // Said at once, with its own row: making a folder tree on Apple takes a moment+ // per folder, and a folder upload used to show nothing at all until every folder+ // in it was made.+ let mut shown = UploadEvent {+ id: format!("{batch}:dir:{}", folders_made),+ batch: batch.to_string(),+ name: name.clone(),+ within: within.clone(),+ sent: 0,+ total: 0,+ state: "preparing",+ folder: true,+ error: None,+ };+ folders_made += 1;+ app.emit(UPLOAD, &shown).ok();+ // Made already, with its siblings in one request, when its parent was made by this+ // upload; otherwise found or made by name — dropped into a folder that may hold one.+ let found = match resolved {+ Some(done) => Ok(done),+ None => folder_for(http, root, params, data, &into, &name).await,+ };+ let (folder, fresh) = match found {+ Ok(folder) => {+ shown.state = "done";+ app.emit(UPLOAD, &shown).ok();+ folder+ }Err(e) => {+ shown.state = "failed";+ shown.error = Some(e.to_string());+ app.emit(UPLOAD, &shown).ok();failed.push(format!("{name}: {e}"));continue;}@@ -2142,21 +2479,77 @@ async fn plan_upload(}// Popped from the end, so reversed to go in name order.children.sort();+ // A folder this upload just made holds nothing yet, so its folders cannot clash+ // with anything there: all of them are made in one request, rather than a read of+ // the parent and a request each — hundreds of round trips for a git repository.+ let mut made: std::collections::HashMap<String, Result<String, String>> =+ std::collections::HashMap::new();+ if fresh {+ let dirs: Vec<String> = {+ let mut d = Vec::new();+ for child in &children {+ if tokio::fs::symlink_metadata(child)+ .await+ .is_ok_and(|m| m.is_dir())+ {+ d.push(+ child+ .file_name()+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_default(),+ );+ }+ }+ d+ };+ if !dirs.is_empty() {+ match quince_icloud::drive::create_folders(+ http,+ root,+ params.to_vec(),+ &folder,+ &dirs,+ )+ .await+ {+ Ok(results) => made.extend(results),+ Err(e) => {+ for d in dirs {+ made.insert(d, Err(e.to_string()));+ }+ }+ }+ }+ }for child in children.into_iter().rev() {- pending.push((child, folder.clone(), below.clone()));+ let child_name = child+ .file_name()+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_default();+ match made.remove(&child_name) {+ Some(Ok(id)) => {+ pending.push((child, folder.clone(), below.clone(), Some((id, true))))+ }+ Some(Err(e)) => failed.push(format!("{child_name}: {e}")),+ None => pending.push((child, folder.clone(), below.clone(), None)),+ }}} else if meta.is_file() {+ let event = UploadEvent {+ id: format!("{batch}:{}", jobs.len()),+ batch: batch.to_string(),+ name,+ within,+ sent: 0,+ total: meta.len(),+ state: "waiting",+ folder: false,+ error: None,+ };+ // Shown the moment it is found, not once the whole tree has been walked.+ app.emit(UPLOAD, &event).ok();jobs.push(UploadJob {- event: UploadEvent {- id: format!("{batch}:{}", jobs.len()),- batch: batch.to_string(),- name,- within,- sent: 0,- total: meta.len(),- state: "waiting",- error: None,- },+ event,path,folder: into,});@@ -2201,6 +2594,7 @@ async fn drive_upload(let mut failed = Vec::new();let jobs = plan_upload(+ &app,&http,&root,¶ms,@@ -2211,9 +2605,22 @@ async fn drive_upload(&mut failed,).await;- for job in &jobs {- app.emit(UPLOAD, &job.event).ok();- }+ // Everything in it has been found: the window can count to a total that will not move.+ app.emit(+ UPLOAD,+ &UploadEvent {+ id: format!("{batch}:planned"),+ batch: batch.clone(),+ name: String::new(),+ within: String::new(),+ sent: 0,+ total: jobs.iter().map(|j| j.event.total).sum(),+ state: "planned",+ folder: true,+ error: None,+ },+ )+ .ok();let results: Vec<Option<String>> = futures_util::stream::iter(jobs).map(|job| {@@ -2224,7 +2631,19 @@ async fn drive_upload(root.clone(),params.clone(),);- async move {+ let (abort, registration) = futures_util::future::AbortHandle::new_pair();+ uploads_running()+ .lock()+ .map(|mut m| m.insert(job.event.id.clone(), abort))+ .ok();+ let id = job.event.id.clone();+ let cancelled_event = {+ let mut e = job.event.clone();+ e.state = "cancelled";+ e+ };+ let app_for_cancel = app.clone();+ let run = async move {let mut event = job.event.clone();event.state = "sending";app.emit(UPLOAD, &event).ok();@@ -2242,6 +2661,9 @@ async fn drive_upload(let mut e = event.clone();e.sent = sent;e.state = if sent >= total {+ // Every byte is up and it is being filed: too late to stop+ // cleanly, so it can no longer be cancelled.+ uploads_running().lock().map(|mut m| m.remove(&e.id)).ok();"verifying"} else {"sending"@@ -2274,12 +2696,28 @@ async fn drive_upload(Some(format!("{}: {e}", event.name))}}+ };+ async move {+ let outcome = futures_util::future::Abortable::new(run, registration).await;+ uploads_running().lock().map(|mut m| m.remove(&id)).ok();+ match outcome {+ Ok(result) => result,+ // Stopped before its bytes were filed: nothing of it is in iCloud.+ Err(_) => {+ app_for_cancel.emit(UPLOAD, &cancelled_event).ok();+ None+ }+ }}}).buffer_unordered(3).collect().await;failed.extend(results.into_iter().flatten());+ cancelled_batches()+ .lock()+ .map(|mut b| b.remove(&batch))+ .ok();settle(resync_drive_folder(&http, &root, params, &data, &folder_id).await)?;Ok(failed)@@ -2948,7 +3386,23 @@ fn main() {// depending on which one the caller happened to build.let uri = request.uri();let wanted = photo_guid(uri.host(), uri.path());+ let attachment = note_part(uri.path());tauri::async_runtime::spawn(async move {+ // A note's picture, or the rendering of a document or film in it.+ if let Some((id, part)) = attachment {+ let response = match note_media_cached(&app, &id, part).await {+ Ok(bytes) => tauri::http::Response::builder()+ .status(200)+ .header("Content-Type", image_type(&bytes))+ .header("Cache-Control", "private, max-age=86400")+ .body(bytes),+ Err(_) => tauri::http::Response::builder()+ .status(404)+ .body(Vec::new()),+ };+ responder.respond(response.unwrap_or_default());+ return;+ }let Some(guid) = wanted else {responder.respond(tauri::http::Response::builder()@@ -3067,6 +3521,10 @@ fn main() {note_body,note_runs,note_table,+ note_table_set_cell,+ note_attachment_info,+ note_attachment_open,+ diagnostics_save,note_paragraph,note_save,note_create,@@ -3100,6 +3558,7 @@ fn main() {drive_put_back,drive_delete_forever,drive_trash_out,+ drive_upload_cancel,drive_move,drive_item,reminder_set_done,@@ -3161,6 +3620,15 @@ mod tests {);assert_eq!(photo_guid(Some("localhost"), "/other%2Fx"), None);assert_eq!(photo_guid(Some("localhost"), "/photo%2F"), None);+ // A note's attachments, as convertFileSrc("note/<id>/preview", "quince") builds them.+ assert!(+ matches!(note_part("/note%2FABC-1%2Fpreview"), Some((ref id, quince_icloud::note_media::Part::Preview)) if id == "ABC-1")+ );+ assert!(matches!(+ note_part("/note%2FABC-1%2Ffile"),+ Some((_, quince_icloud::note_media::Part::File))+ ));+ assert!(note_part("/note%2FABC-1%2Fother").is_none());assert_eq!(percent_decode("plain-uuid"), "plain-uuid");assert_eq!(percent_decode("%zz"), "%zz", "malformed stays as it was");}diff --git a/src-tauri/src/refresh.rs b/src-tauri/src/refresh.rsindex b949fa6..0f56725 100644--- a/src-tauri/src/refresh.rs+++ b/src-tauri/src/refresh.rs@@ -66,11 +66,12 @@ pub struct Refresh {const FULL_SYNC_EVERY: i64 = 24 * 60 * 60;/// The services one pass covers, in the order a person would notice them going stale.-const COVERED: [(&str, &str); 4] = [+const COVERED: [(&str, &str); 5] = [("calendar", "Calendar"),("reminders", "Reminders"),("notes", "Notes"),("contacts", "Contacts"),+ ("drive", "iCloud Drive"),];/// The calendar window a background refresh keeps warm: the month behind, so last week is@@ -101,6 +102,7 @@ struct Context {calendar: Option<String>,contacts: Option<String>,cloudkit: Option<String>,+ drive: Option<String>,}async fn context(client: &Arc<Mutex<Client>>) -> Context {@@ -112,6 +114,7 @@ async fn context(client: &Arc<Mutex<Client>>) -> Context {calendar: session.service_url("calendar"),contacts: session.service_url("contacts"),cloudkit: session.service_url("ckdatabasews"),+ drive: session.service_url("drivews"),}}@@ -259,6 +262,34 @@ async fn run(client: &Arc<Mutex<Client>>, data: &Mutex<Library>, services: &[&st});}+ // Drive is read a folder at a time as it is opened; the pass keeps its top level current,+ // so what changed there on another device is here before anyone looks, and its freshness+ // is stated with the rest. Fetched and stored as one — see `DRIVE_PASS`.+ if wanted("drive") {+ reports.push(match ctx.drive.as_deref() {+ None => unavailable("drive", "iCloud Drive"),+ Some(root) => {+ let _one = crate::DRIVE_PASS.lock().await;+ let fetched = quince_icloud::drive::fetch_folder(+ &ctx.http,+ root,+ ctx.params.clone(),+ quince_core::drive::ROOT,+ )+ .await;+ store("drive", "iCloud Drive", data, fetched, |library, items| {+ let n = quince_icloud::drive::store_folder(+ library,+ quince_core::drive::ROOT,+ &items,+ )?;+ Ok(format!("{n} item{} at the top of iCloud Drive", plural(n)))+ })+ .await+ }+ });+ }+let available: Vec<&str> = reports.iter().filter(|r| r.outcome != Outcome::Unavailable)diff --git a/src/components/Picker.tsx b/src/components/Picker.tsxindex 5655a58..0bb756e 100644--- a/src/components/Picker.tsx+++ b/src/components/Picker.tsx@@ -164,10 +164,15 @@ export function Picker({const t = e.target as Node;if (!root.current?.contains(t) && !menu.current?.contains(t)) setOpen(false);};- // A menu fixed over a page that scrolls or resizes would be left floating somewhere- // else; as on the Mac, it goes. Its own scrolling is not that.+ // A menu fixed over a page that scrolls would be left floating away from its button; as+ // on the Mac, it goes — but only when its button has really moved. Any scroll at all+ // closed it, and a page still settling as the menu opened (a panel easing into view)+ // closed it the moment it appeared: open, shut, a flicker. Its own scrolling is not that.+ const at = button.current?.getBoundingClientRect();const onMove = (e: Event) => {- if (!menu.current?.contains(e.target as Node)) setOpen(false);+ if (menu.current?.contains(e.target as Node)) return;+ const now = button.current?.getBoundingClientRect();+ if (!at || !now || Math.abs(now.top - at.top) > 2 || Math.abs(now.left - at.left) > 2) setOpen(false);};const onLeave = () => setOpen(false);document.addEventListener("mousedown", onDown);diff --git a/src/components/UploadTray.tsx b/src/components/UploadTray.tsxindex 6a640de..b119fbb 100644--- a/src/components/UploadTray.tsx+++ b/src/components/UploadTray.tsx@@ -1,63 +1,139 @@-import type { UploadEvent } from "../lib/ipc";+import { useEffect, useRef, useState } from "react";+import { api, type UploadEvent } from "../lib/ipc";import { FileGlyph } from "./FileGlyph";-/** What a person reads about one file, in the fewest words that are still true. */-function status(u: UploadEvent): string {- switch (u.state) {- case "waiting":- return "Waiting";- case "sending":- return `${Math.floor((u.sent / Math.max(u.total, 1)) * 100)}%`;- case "verifying":- return "Checking";- case "done":- return "Uploaded";- case "failed":- return "Didn’t upload";- }-}-const extensionOf = (name: string) => {const dot = name.lastIndexOf(".");return dot > 0 ? name.slice(dot + 1) : null;};+const ended = (u: UploadEvent) => u.state === "done" || u.state === "failed" || u.state === "cancelled";+/**- * Every file going up, each with its own progress, in the corner like a download list.- *- * "Uploading…" on a button said nothing about which of forty photos had gone and which had- * not. This names each one, shows how far it has got, and only calls it uploaded once iCloud- * has been shown to hold exactly its bytes — so "Uploaded" is a statement, not a hope.+ * One line of the tray: a file dropped on its own, or a whole folder with everything in it+ * counted as one — as Google Drive and Finder show a folder going up. A folder of 214 files+ * listed file by file was a scroll of names nobody could follow.*/-export function UploadTray({- uploads,- onDismiss,-}: {- uploads: UploadEvent[];- onDismiss: () => void;-}) {- if (uploads.length === 0) return null;- const finished = uploads.filter((u) => u.state === "done" || u.state === "failed");- const failed = uploads.filter((u) => u.state === "failed").length;- const active = finished.length < uploads.length;- const total = uploads.reduce((n, u) => n + u.total, 0);- const sent = uploads.reduce((n, u) => n + (u.state === "done" ? u.total : u.sent), 0);- const percent = total > 0 ? Math.floor((sent / total) * 100) : 100;+type Item = {+ key: string;+ name: string;+ folder: boolean;+ files: UploadEvent[];+ /** The folder's own row: being made on Apple, made, or refused. */+ self?: UploadEvent;+};++function group(uploads: UploadEvent[]): Item[] {+ const items: Item[] = [];+ const byFolder = new Map<string, Item>();+ for (const u of uploads) {+ if (u.state === "planned") continue;+ const top = u.within ? u.within.split("/")[0] : null;+ if (u.folder && !u.within) {+ const item: Item = { key: `${u.batch}/${u.name}`, name: u.name, folder: true, files: [], self: u };+ byFolder.set(item.key, item);+ items.push(item);+ } else if (top) {+ const key = `${u.batch}/${top}`;+ let item = byFolder.get(key);+ if (!item) {+ item = { key, name: top, folder: true, files: [] };+ byFolder.set(key, item);+ items.push(item);+ }+ if (!u.folder) item.files.push(u);+ } else if (!u.folder) {+ items.push({ key: u.id, name: u.name, folder: false, files: [u] });+ }+ }+ return items;+}+/** How far a line has got, and what it is doing, in the fewest words that are true. */+function measure(item: Item, planned: boolean) {+ const total = item.files.reduce((n, u) => n + u.total, 0);+ const sent = item.files.reduce((n, u) => n + (u.state === "done" ? u.total : u.sent), 0);+ const done = item.files.filter((u) => u.state === "done").length;+ const failed = item.files.filter((u) => u.state === "failed");+ const cancelled = item.files.filter((u) => u.state === "cancelled").length;+ const running = item.files.some((u) => !ended(u)) || item.self?.state === "preparing" || (item.folder && !planned);+ const percent = total > 0 ? Math.floor((sent / total) * 100) : running ? 0 : 100;+ let status: string;+ if (item.self?.state === "failed") status = "Couldn’t be made";+ // Still finding what is in it: a count that would only grow is not a total yet.+ else if (item.folder && !planned) status = item.files.length ? `Preparing… ${item.files.length} found` : "Preparing…";+ else if (running && item.files.length === 0) status = "Preparing…";+ else if (running && !item.folder) {+ const u = item.files[0];+ status = u.state === "waiting" ? "Waiting" : u.state === "verifying" ? "Checking" : `${percent}%`;+ } else if (running) status = `${done} of ${item.files.length}`;+ else if (failed.length > 0) status = item.folder ? `${failed.length} didn’t upload` : "Didn’t upload";+ else if (cancelled > 0 && done === 0) status = "Cancelled";+ else if (cancelled > 0) status = `${done} uploaded, ${cancelled} cancelled`;+ else status = "Uploaded";+ return { total, sent, percent, running, failed, status };+}++/**+ * Every upload going up, in the corner as a download list sits: one line per file dropped and+ * one per folder, each with its own progress, the whole batch summed in the head. A folder+ * opens to show what in it did not upload, and why. When everything has gone up cleanly the+ * tray steps aside on its own; anything that failed keeps it until it is read.+ */+export function UploadTray({ uploads, onDismiss }: { uploads: UploadEvent[]; onDismiss: () => void }) {+ const [open, setOpen] = useState<string | null>(null);+ const items = group(uploads);+ const planned = new Set(uploads.filter((u) => u.state === "planned").map((u) => u.batch));+ const measured = items.map((item) => ({ item, ...measure(item, planned.has(item.files[0]?.batch ?? item.self?.batch ?? "")) }));+ const active = measured.some((m) => m.running);+ const anyFailed = measured.some((m) => m.failed.length > 0 || m.item.self?.state === "failed");+ const allPlanned = [...new Set(uploads.map((u) => u.batch))].every((b) => planned.has(b));+ const total = measured.reduce((n, m) => n + m.total, 0);+ const sent = measured.reduce((n, m) => n + m.sent, 0);+ // Progress only ever moves forward: three files go up at once and report out of step, and+ // a bar that slid back on every report read as broken.+ const highest = useRef<Map<string, number>>(new Map());+ if (uploads.length === 0) highest.current.clear();+ const forward = (key: string, value: number) => {+ const was = highest.current.get(key) ?? 0;+ const now = Math.max(was, value);+ highest.current.set(key, now);+ return now;+ };+ const percent = allPlanned && total > 0 ? forward("all", Math.floor((sent / total) * 100)) : 0;+ const files = uploads.filter((u) => !u.folder);+ const finishedFiles = files.filter(ended).length;++ // Gone by itself a moment after a clean finish; held while anything needs reading.+ useEffect(() => {+ if (uploads.length === 0 || active || anyFailed) return undefined;+ const t = window.setTimeout(onDismiss, 4000);+ return () => window.clearTimeout(t);+ }, [uploads.length, active, anyFailed, onDismiss]);++ if (uploads.length === 0) return null;+ const batches = [...new Set(uploads.filter((u) => !ended(u)).map((u) => u.batch))];const heading = active- ? `Uploading ${finished.length + 1 > uploads.length ? uploads.length : finished.length + 1} of ${uploads.length}`- : failed > 0- ? `${failed} of ${uploads.length} didn’t upload`- : uploads.length === 1- ? "Uploaded"- : `${uploads.length} uploaded`;+ ? items.length === 1 && items[0].folder+ ? `Uploading ${items[0].name}`+ : `Uploading ${Math.min(finishedFiles + 1, Math.max(files.length, 1))} of ${Math.max(files.length, 1)}`+ : anyFailed+ ? "Some uploads didn’t finish"+ : items.length === 1+ ? `${items[0].name} uploaded`+ : `${files.length} uploaded`;return (<section className="upload-tray" aria-label="Uploads" aria-live="polite"><header className="upload-tray-head"><span className="upload-tray-title">{heading}</span>{active ? (- <span className="upload-tray-percent">{percent}%</span>+ <span className="upload-tray-actions">+ {allPlanned && <span className="upload-tray-percent">{percent}%</span>}+ <button className="upload-tray-close" onClick={() => batches.forEach((b) => void api.driveUploadCancel([], b))}>+ Cancel+ </button>+ </span>) : (<button className="upload-tray-close" onClick={onDismiss} aria-label="Close uploads">Done@@ -65,32 +141,67 @@ export function UploadTray({)}</header>{active && (- <div className="upload-bar" aria-hidden="true">- <span style={{ width: `${percent}%` }} />+ <div className={`upload-bar${allPlanned ? "" : " is-waiting"}`} aria-hidden="true">+ <span style={{ width: allPlanned ? `${percent}%` : undefined }} /></div>)}<ul className="upload-rows">- {uploads.map((u) => (- <li key={u.id} className={`upload-row is-${u.state}`}>- <span className="upload-glyph" aria-hidden="true">- <FileGlyph kind="FILE" extension={extensionOf(u.name)} />- </span>- <span className="upload-text">- <span className="upload-name">{u.name}</span>- <span className="upload-where">- {u.state === "failed" && u.error ? u.error : u.within || " "}- </span>- {(u.state === "sending" || u.state === "verifying") && (- <span className="upload-bar small" aria-hidden="true">- <span style={{ width: `${Math.floor((u.sent / Math.max(u.total, 1)) * 100)}%` }} />+ {measured.map(({ item, percent: raw, running, failed, status }) => {+ const p = forward(item.key, raw);+ const stoppable = item.files.filter((u) => u.state === "waiting" || u.state === "sending");+ const state = running ? "sending" : failed.length || item.self?.state === "failed" ? "failed" : status === "Cancelled" ? "cancelled" : "done";+ return (+ <li key={item.key} className={`upload-row is-${state}`}>+ <div className="upload-line">+ <span className="upload-glyph" aria-hidden="true">+ <FileGlyph kind={item.folder ? "FOLDER" : "FILE"} extension={item.folder ? null : extensionOf(item.name)} />+ </span>+ <span className="upload-text">+ <span className="upload-name">{item.name}</span>+ {running && (item.folder ? planned.has(item.files[0]?.batch ?? "") : true) && (+ <span className="upload-bar small" aria-hidden="true">+ <span style={{ width: `${p}%` }} />+ </span>+ )}+ {!running && !item.folder && failed[0]?.error && <span className="upload-where">{failed[0].error}</span>}+ </span>+ <span className="upload-state">+ {state === "done" && status === "Uploaded" ? <span aria-label="Uploaded">✓</span> : status}</span>+ {item.folder && failed.length > 0 && (+ <button+ className="upload-stop"+ aria-expanded={open === item.key}+ aria-label={open === item.key ? "Hide what didn’t upload" : "Show what didn’t upload"}+ onClick={() => setOpen(open === item.key ? null : item.key)}+ >+ {open === item.key ? "▾" : "▸"}+ </button>+ )}+ {/* One upload has one Cancel — the head's. */}+ {stoppable.length > 0 && measured.length > 1 && (+ <button+ className="upload-stop"+ aria-label={`Cancel ${item.name}`}+ title="Cancel"+ onClick={() => void api.driveUploadCancel(stoppable.map((u) => u.id))}+ >+ ✕+ </button>+ )}+ </div>+ {open === item.key && (+ <ul className="upload-failures">+ {failed.map((u) => (+ <li key={u.id}>+ <b>{u.within.split("/").slice(1).concat(u.name).join("/")}</b> {u.error}+ </li>+ ))}+ </ul>)}- </span>- <span className="upload-state">- {u.state === "done" ? <span aria-label="Uploaded">✓</span> : status(u)}- </span>- </li>- ))}+ </li>+ );+ })}</ul></section>);diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex 8387596..63757da 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -43,7 +43,9 @@ export type UploadEvent = {within: string;sent: number;total: number;- state: "waiting" | "sending" | "verifying" | "done" | "failed";+ state: "preparing" | "waiting" | "sending" | "verifying" | "done" | "failed" | "cancelled" | "planned";+ /** A folder being made, rather than a file being sent. */+ folder?: boolean;error: string | null;};@@ -127,6 +129,13 @@ export const api = {invoke<void>("note_paragraph", { guid, start, ...change }),/** A table's cells, row by row, by the attachment id a note's text names it by. */noteTable: (id: string) => invoke<string[][] | null>("note_table", { id }),+ /** Change one cell of a table; answers the table as Apple now holds it. */+ /** What a note's attachment is — a picture, a document, a recording, a file. */+ noteAttachmentInfo: (id: string) => invoke<NoteAttachment>("note_attachment_info", { id }),+ /** Open a note's attachment in the app this computer uses for it. */+ noteAttachmentOpen: (id: string) => invoke<void>("note_attachment_open", { id }),+ noteTableSetCell: (id: string, row: number, column: number, text: string) =>+ invoke<string[][]>("note_table_set_cell", { id, row, column, text }),noteRuns: (guid: string) => invoke<import("../screens/notes/Formatted").Run[]>("note_runs", { guid }),noteFolderCreate: (title: string, parent: string | null) =>invoke<string>("note_folder_create", { title, parent }),@@ -198,6 +207,8 @@ export const api = {* read as the whole upload failing.*//** Files and folders into a Drive folder. Progress arrives as UPLOAD events. */+ /** Stop uploads — these, or a whole batch. One already being filed finishes. */+ driveUploadCancel: (ids: string[], batch?: string) => invoke<void>("drive_upload_cancel", { ids, batch: batch ?? null }),driveUpload: (batch: string, folderId: string, paths: string[]) =>invoke<string[]>("drive_upload", { batch, folderId, paths }),driveCreateFolder: (parentId: string, name: string) =>@@ -212,6 +223,8 @@ export const api = {/** Who is signed in, as Apple names them. */accountInfo: () => invoke<AccountInfo>("account_info"),/** Settings' switches, as the backend obeys them. */+ /** Write a plain diagnostic report to Downloads; answers where. Nothing is sent anywhere. */+ diagnosticsSave: () => invoke<string>("diagnostics_save"),settingsGet: () => invoke<{ reminderAlerts: boolean; eventAlerts: boolean }>("settings_get"),settingsSet: (key: "reminderAlerts" | "eventAlerts", on: boolean) => invoke<void>("settings_set", { key, on }),drivePutBack: (item: DriveItem) => invoke<void>("drive_put_back", { item }),@@ -487,6 +500,23 @@ export type AccountInfo = {photoContact?: string | null;};+export type NoteAttachment = {+ id: string;+ uti: string;+ kind: "image" | "document" | "audio" | "video" | "file";+ filename: string | null;+ title: string | null;+ width: number | null;+ height: number | null;+ size: number | null;+ hasPreview: boolean;+};++/** A note attachment's picture — the file itself, or Apple's rendering of it. */+export function noteMediaSrc(id: string, part: "file" | "preview"): string {+ return convertFileSrc(`note/${id}/${part}`, "quince");+}+/** The picture of the contact with this id, served by the backend. */export function contactPhotoSrc(guid: string): string {return convertFileSrc(`photo/${guid}`, "quince");diff --git a/src/screens/DriveView.tsx b/src/screens/DriveView.tsxindex 4580a2b..34b8951 100644--- a/src/screens/DriveView.tsx+++ b/src/screens/DriveView.tsx@@ -1,4 +1,5 @@import { useCallback, useEffect, useRef, useState } from "react";+import { useSync } from "../lib/sync";import { Notice } from "../components/Notice";import { Portal } from "../components/Portal";import { open as openFileDialog } from "@tauri-apps/plugin-dialog";@@ -555,7 +556,35 @@ export function DriveView() {setTrail((t) => [...t, { id: item.drivewsid, name: driveName(item) }]);}- const refresh = useCallback(() => open(hereRef.current), [open]);+ /**+ * The open folder again, quietly: after files land, and whenever a sync finishes, so what+ * changed in it on another device shows without the folder being opened again. No+ * "loading", and the pictures stay: re-opening the folder wiped the thumbnails and drew+ * them back, a blink across the grid every time a file arrived.+ */+ const refresh = useCallback(async () => {+ const folderId = hereRef.current;+ const token = openToken.current;+ try {+ await api.driveSyncFolder(folderId);+ if (token !== openToken.current) return;+ const fresh = await api.driveChildren(folderId);+ if (token !== openToken.current) return;+ setItems(Array.isArray(fresh) ? fresh : []);+ api.driveThumbnails(folderId).then(+ (t) => { if (token === openToken.current && t) setThumbs((was) => ({ ...was, ...t })); },+ () => {},+ );+ } catch {+ // A quiet refresh that fails changes nothing; opening the folder says what is wrong.+ }+ }, []);+ const { revision } = useSync();+ const firstRevision = useRef(revision);+ useEffect(() => {+ if (revision === firstRevision.current) return;+ void refresh();+ }, [revision, refresh]);const download = useCallback(async (item: DriveItem) => {setBusyGuid(item.drivewsid);@@ -612,6 +641,15 @@ export function DriveView() {async (item: DriveItem) => {setError(null);setGone((g) => new Set(g).add(item.drivewsid));+ // A folder still being uploaded into stops taking files first: deleting it while files+ // went on landing was what Apple would not do.+ if (isContainer(item)) {+ const into = [...uploadsRef.current.values()].filter(+ (u) => !["done", "failed", "cancelled"].includes(u.state) &&+ ((u.folder && !u.within && u.name === item.name) || u.within.split("/")[0] === item.name),+ );+ for (const batch of new Set(into.map((u) => u.batch))) await api.driveUploadCancel([], batch).catch(() => {});+ }try {await api.driveDelete(item.drivewsid);await refresh();@@ -714,12 +752,12 @@ export function DriveView() {const next = new Map(was);const before = next.get(u.id);// Events for one file can pass each other; a finished file never goes back.- if (before && (before.state === "done" || before.state === "failed")) return was;+ if (before && (before.state === "done" || before.state === "failed" || before.state === "cancelled")) return was;next.set(u.id, u);return next;});// Each file that lands shows as it lands, not all at once when the batch ends.- if (u.state === "done") landed();+ if (u.state === "done" && !u.folder) landed();}).then((unlisten) => {// Stopping may throw where there is no event system behind the page — a plain@@ -742,6 +780,10 @@ export function DriveView() {};}, []);+ const uploadsRef = useRef(uploads);+ uploadsRef.current = uploads;+ const dismissUploads = useCallback(() => setUploads(new Map()), []);+const upload = useCallback(async (paths: string[]) => {if (paths.length === 0) return;@@ -766,6 +808,19 @@ export function DriveView() {setError(messageOf(e));} finally {settle(batch);+ // The batch is over: the backend has said all it will. A row of it still open — a+ // report that never came, an upload stopped part-way — is closed now, so nothing can+ // sit at "0 of 80" for ever.+ setUploads((was) => {+ let changed = false;+ const next = new Map(was);+ for (const [id, u] of was) {+ if (u.batch !== batch || ["done", "failed", "cancelled", "planned"].includes(u.state)) continue;+ next.set(id, { ...u, state: u.folder ? "failed" : "cancelled", error: "Stopped before it finished" });+ changed = true;+ }+ return changed ? next : was;+ });}},[here.id, refresh]@@ -932,7 +987,7 @@ export function DriveView() {className="quiet with-glyph"title="New Folder"onClick={() => setCreatingFolder(true)}- disabled={loading || creatingFolder}+ disabled={creatingFolder}><ActionGlyph name="newFolder" />New Folder@@ -944,7 +999,7 @@ export function DriveView() {aria-haspopup="menu"aria-expanded={uploadMenu}onClick={() => setUploadMenu((open) => !open)}- disabled={loading || !acceptsUploads(here.id)}+ disabled={!acceptsUploads(here.id)}title={acceptsUploads(here.id)? undefined@@ -1215,7 +1270,7 @@ export function DriveView() {<InfoSheet item={info} where={trail.map((c) => c.name).join(" › ")} thumb={thumbs[info.drivewsid]} onClose={() => setInfo(null)} />)}- <UploadTray uploads={[...uploads.values()]} onDismiss={() => setUploads(new Map())} />+ <UploadTray uploads={[...uploads.values()]} onDismiss={dismissUploads} /></div>);}diff --git a/src/screens/RemindersView.tsx b/src/screens/RemindersView.tsxindex 33e1051..1ee5fc9 100644--- a/src/screens/RemindersView.tsx+++ b/src/screens/RemindersView.tsx@@ -1,4 +1,4 @@-import { Fragment, useCallback, useEffect, useMemo, useState } from "react";+import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";import { usePending } from "../lib/pending";import { Notice } from "../components/Notice";import { Portal } from "../components/Portal";@@ -179,6 +179,9 @@ type Selection =export function RemindersView() {const [lists, setLists] = useState<ReminderList[]>([]);+ const focusedBeforePress = useRef<Element | null>(null);+ /** A reminder's menu, from a right-click on its row. */+ const [rowMenu, setRowMenu] = useState<{ reminder: Reminder; at: { x: number; y: number; alignRight: boolean } } | null>(null);/** A list's menu, from its ⋯ or a right-click. */const [listMenu, setListMenu] = useState<{ list: ReminderList; at: { x: number; y: number; alignRight: boolean } } | null>(null);/** The list whose Show List Info sheet is open. */@@ -198,10 +201,17 @@ export function RemindersView() {return next;});}, []);- const [selection, setSelection] = useState<Selection>({+ /**+ * What was picked, and what the pane shows. The sidebar answers a click at once from+ * `picked`; the pane moves to it only when the picked view's reminders and headings have+ * arrived, and takes all of them in one draw. Moving the heading first left the new+ * list's title over the old list's reminders for a moment — the flicker on every switch.+ */+ const [picked, setSelection] = useState<Selection>({type: "smart",kind: "today",});+ const [selection, setShown] = useState<Selection>(picked);const [items, setItems] = useState<Reminder[]>([]);const [showDone, setShowDone] = useState(false);const [syncing, setSyncing] = useState(false);@@ -240,22 +250,7 @@ export function RemindersView() {setLoaded(true);}, []);- useEffect(() => {- if (selection.type !== "list") return setListSections([]);- let cancelled = false;- api- .reminderSections(selection.guid)- .then((found) => {- if (!cancelled) setListSections(Array.isArray(found) ? found : []);- })- .catch(() => {- // Without sections the list still shows every reminder, just without headings.- if (!cancelled) setListSections([]);- });- return () => {- cancelled = true;- };- }, [selection, revision]);+ // A list's headings are read with its reminders (readItems), so they arrive together./** What is typed in the search field. While it holds anything, the pane is the results. */const [query, setQuery] = useState("");@@ -267,17 +262,30 @@ export function RemindersView() {const [detail, setDetail] = useState(false);const { hold, over } = usePending<Reminder>();+ /** Each read is numbered: one overtaken by a later pick is dropped, never drawn late. */+ const reads = useRef(0);const readItems = useCallback(async (): Promise<Reminder[]> => {+ const sel = picked;+ const seq = ++reads.current;// Search reaches every list, as Apple's does, whatever is open in the sidebar.- const found = searching- ? await api.remindersSearch(query)- : selection.type === "smart"- ? await api.remindersSmart(selection.kind, endOfToday())- : await api.remindersIn(selection.guid, showDone);+ const [found, sections] = await Promise.all([+ searching+ ? api.remindersSearch(query)+ : sel.type === "smart"+ ? api.remindersSmart(sel.kind, endOfToday())+ : api.remindersIn(sel.guid, showDone),+ sel.type === "list"+ ? api.reminderSections(sel.guid).catch(() => [] as ReminderSection[])+ : Promise.resolve([] as ReminderSection[]),+ ]);const fresh = over((Array.isArray(found) ? found : []).map(asShown));+ if (seq !== reads.current) return fresh;+ // The view, its reminders and its headings, together.+ setShown(sel);setItems(fresh);+ setListSections(Array.isArray(sections) ? sections : []);return fresh;- }, [selection, showDone, query, searching, over]);+ }, [picked, showDone, query, searching, over]);// Both reads come from the library. `revision` ticks when the shared refresh finishes —// pressed, or on the timer — so a reminder ticked on the phone appears here without this@@ -455,10 +463,21 @@ export function RemindersView() {patch(r.guid, { parentGuid: null }),);+ // The reminder goes, and its subtasks with it — the backend moves them after it, as the+ // phone does — at once: out of the list on screen, or re-filed where a view gathers lists.const moveToList = (r: Reminder, listGuid: string) =>listGuid === r.listGuid? Promise.resolve(null)- : write(r, () => api.reminderEdit(r.guid, r.listGuid, { listGuid }));+ : write(+ r,+ () => api.reminderEdit(r.guid, r.listGuid, { listGuid }),+ (rows) => {+ const moving = (x: Reminder) => x.guid === r.guid || x.parentGuid === r.guid;+ return selection.type === "list"+ ? rows.filter((x) => !moving(x))+ : rows.map((x) => (moving(x) ? { ...x, listGuid } : x));+ },+ );/** List writes go to Apple first, then the whole set is re-read. */const listWrite = useCallback(@@ -842,7 +861,7 @@ export function RemindersView() {<><buttonclassName="rx-list"- aria-current={listGuid === list.guid}+ aria-current={picked.type === "list" && picked.guid === list.guid}onClick={() => {setQuery("");setSelection({ type: "list", guid: list.guid });@@ -963,7 +982,7 @@ export function RemindersView() {smart.glyph,smart.colour,counts?.[smart.kind] ?? 0,- !searching && selection.type === "smart" && selection.kind === smart.kind,+ !searching && picked.type === "smart" && picked.kind === smart.kind,() => setSelection({ type: "smart", kind: smart.kind }),),)}@@ -974,7 +993,7 @@ export function RemindersView() {emblemGlyph(list.emblem),colourOf(list),countOf(list.guid),- !searching && listGuid === list.guid,+ !searching && picked.type === "list" && picked.guid === list.guid,() => setSelection({ type: "list", guid: list.guid }),),)}@@ -1105,6 +1124,21 @@ export function RemindersView() {setDragging(reminder.guid);}}onDragEnd={() => { setDragging(null); setDropBefore(null); }}+ // Right-click, as on the Mac: what can be done to this reminder, in one menu.+ onMouseDownCapture={() => {+ // What had focus before this press: the press itself focuses a title it+ // lands on, which is not the same as someone already typing in it.+ focusedBeforePress.current = document.activeElement;+ }}+ onContextMenu={(e) => {+ // Text being edited keeps its own menu; anywhere else on the row, the+ // reminder's — its title included, until someone is typing in it.+ const field = (e.target as HTMLElement).closest("input, textarea, [contenteditable=true]");+ if (field && field === focusedBeforePress.current) return;+ (document.activeElement as HTMLElement | null)?.blur?.();+ e.preventDefault();+ setRowMenu({ reminder, at: { x: e.clientX, y: e.clientY, alignRight: false } });+ }}onDragOver={(e) => {if (!dragging || dragging === reminder.guid || depth > 0 || reminder.completedAt) return;e.preventDefault();@@ -1341,6 +1375,35 @@ export function RemindersView() {</p>)}</section>+ {rowMenu && (+ <RowMenu+ at={rowMenu.at}+ onClose={() => setRowMenu(null)}+ entries={(() => {+ const r = rowMenu.reminder;+ return [+ { label: "Show Info", run: () => setOpenGuid(r.guid) },+ { label: r.flagged ? "Unflag" : "Flag", run: () => void flag(r) },+ { label: r.completedAt ? "Mark as Not Completed" : "Mark as Completed", run: () => void toggle(r) },+ null,+ r.parentGuid+ ? { label: "Outdent", run: () => void outdent(r) }+ : { label: "Indent", run: () => void indent(r) },+ // Only where there is somewhere else to go: an empty submenu is a dead end.+ ...(lists.some((l) => l.guid !== r.listGuid)+ ? [{+ label: "Move to List",+ submenu: lists+ .filter((l) => l.guid !== r.listGuid)+ .map((l) => ({ label: l.title, run: () => void moveToList(r, l.guid) })),+ }]+ : []),+ null,+ { label: "Delete", danger: true, run: () => void remove(r) },+ ];+ })()}+ />+ )}{listMenu && (<RowMenuat={listMenu.at}diff --git a/src/screens/SettingsView.tsx b/src/screens/SettingsView.tsxindex b0a9aff..ad5e0df 100644--- a/src/screens/SettingsView.tsx+++ b/src/screens/SettingsView.tsx@@ -12,6 +12,7 @@ const ICON: Record<string, string> = {reminders: "reminders",notes: "notes",contacts: "contacts",+ drive: "drivews",};function size(bytes: number): string {@@ -34,6 +35,7 @@ export function SettingsView({ onSignOut }: { onSignOut: () => void }) {const [version, setVersion] = useState<string | null>(null);const [error, setError] = useState<string | null>(null);const [confirming, setConfirming] = useState(false);+ const [savedReport, setSavedReport] = useState<string | null>(null);const { report, syncing, refresh } = useSync();useEffect(() => {@@ -180,6 +182,19 @@ export function SettingsView({ onSignOut }: { onSignOut: () => void }) {Your iCloud is kept on this computer and talks only to Apple. Quince has no servers.</span></div>+ <div className="settings-row">+ <span className="settings-label settings-hint">+ {savedReport+ ? `Saved to ${savedReport.split("/").slice(-2).join("/")} — versions and sync states only, no names or contents. Attach it to a bug report.`+ : "A plain report of how Quince is doing, for a bug report. Nothing is sent anywhere."}+ </span>+ <button+ className="quiet"+ onClick={() => api.diagnosticsSave().then(setSavedReport, (e) => setError(messageOf(e)))}+ >+ Save Diagnostic Report+ </button>+ </div></section></div>);diff --git a/src/screens/notes/NoteEditor.tsx b/src/screens/notes/NoteEditor.tsxindex 1409883..f32fcf1 100644--- a/src/screens/notes/NoteEditor.tsx+++ b/src/screens/notes/NoteEditor.tsx@@ -8,13 +8,97 @@ import { baseKeymap, splitBlockAs, toggleMark, chainCommands } from "prosemirrorimport type { Node as PMNode } from "prosemirror-model";import type { Run } from "./Formatted";import { fromDoc, LIST_STYLES, schema, STYLE, toDoc } from "./rich";-import { api } from "../../lib/ipc";+import { api, noteMediaSrc, type NoteAttachment } from "../../lib/ipc";/*** An attachment in the note: a table drawn as the grid it is, with the cells Apple holds;- * anything else — a picture, a sketch — as a labelled placeholder that keeps its place. Not- * editable here, and never written from here: the note keeps the attachment exactly.+ * anything else — a picture, a sketch — as a labelled placeholder that keeps its place.+ *+ * A table's cells are edited where they stand. Each cell already typed in is a plain-text+ * field of its own — keys typed there are the cell's, never the note's — saved to Apple when+ * it is left or Return is pressed, drawn at once, and put back with the reason if Apple+ * refuses. A cell never typed in has nothing in Apple's table yet to change, and says so.*/+/** What each attachment is, asked once a session: a note re-drawn does not ask again. */+const described = new Map<string, Promise<NoteAttachment | null>>();+function describe(id: string): Promise<NoteAttachment | null> {+ let known = described.get(id);+ if (!known) {+ known = api.noteAttachmentInfo(id).catch(() => null);+ described.set(id, known);+ }+ return known;+}++function size(bytes: number | null): string {+ if (!bytes) return "";+ if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(1)} MB`;+ return `${Math.max(1, Math.round(bytes / 1024))} KB`;+}++/**+ * A picture, document, recording or file where it sits in its note, as Notes shows it: a+ * picture at its own proportions, a PDF, scan or film as Apple's rendering of it with its+ * name, anything else as a labelled chip. Clicking one opens it in the app this computer uses+ * for it. A picture that cannot be had falls back to the chip, never a broken frame.+ */+function drawMedia(dom: HTMLElement, info: NoteAttachment) {+ const name = info.filename ?? info.title ?? (info.kind === "audio" ? "Recording" : "Attachment");+ const open = () => void api.noteAttachmentOpen(info.id).catch(() => {});+ const chip = () => {+ const c = document.createElement("button");+ c.type = "button";+ c.className = `nf-file is-${info.kind}`;+ const glyph = document.createElement("span");+ glyph.className = "nf-file-glyph";+ // The kind of file, as Finder labels a document: its extension, short.+ const ext = name.includes(".") ? name.split(".").pop()!.slice(0, 4).toUpperCase() : "";+ glyph.textContent = info.kind === "audio" ? "♪" : info.kind === "video" ? "▶" : ext || "FILE";+ const label = document.createElement("span");+ label.className = "nf-file-name";+ label.textContent = name;+ const meta = document.createElement("span");+ meta.className = "nf-file-meta";+ meta.textContent = size(info.size);+ c.append(glyph, label, meta);+ c.title = `Open ${name}`;+ c.addEventListener("click", open);+ return c;+ };+ const picture = (part: "file" | "preview", cls: string) => {+ const img = document.createElement("img");+ img.className = cls;+ img.alt = name;+ img.decoding = "async";+ img.draggable = false;+ if (info.width && info.height) img.style.aspectRatio = `${info.width} / ${info.height}`;+ img.src = noteMediaSrc(info.id, part);+ img.addEventListener("error", () => dom.replaceChildren(chip()));+ return img;+ };+ dom.title = `Open ${name}`;+ if (info.kind === "image") {+ const img = picture("file", "nf-image");+ img.addEventListener("click", open);+ dom.className = "nf-attachment is-image";+ dom.replaceChildren(img);+ } else if ((info.kind === "document" || info.kind === "video") && info.hasPreview) {+ const figure = document.createElement("button");+ figure.type = "button";+ figure.className = `nf-doc is-${info.kind}`;+ const caption = document.createElement("span");+ caption.className = "nf-doc-name";+ caption.textContent = name;+ figure.append(picture("preview", "nf-doc-preview"), caption);+ figure.addEventListener("click", open);+ dom.className = "nf-attachment is-doc";+ dom.replaceChildren(figure);+ } else {+ dom.className = "nf-attachment is-file";+ dom.replaceChildren(chip());+ }+}+function attachmentView(node: PMNode) {const dom = document.createElement("span");dom.className = "nf-attachment";@@ -22,24 +106,79 @@ function attachmentView(node: PMNode) {dom.textContent = "Attachment";dom.title = "Open it on an Apple device to change it";const id = node.attrs.id as string | null;++ const draw = (cells: string[][]) => {+ const table = document.createElement("table");+ table.className = "nf-table";+ cells.forEach((row, r) => {+ const tr = table.insertRow();+ row.forEach((cell, c) => {+ const td = tr.insertCell();+ const was = cell.trimEnd();+ if (!id || was === "") {+ td.textContent = was;+ td.className = "nf-cell-empty";+ td.title = "Type in this cell on an Apple device first — Quince can change cells that have text";+ return;+ }+ const field = document.createElement("div");+ field.className = "nf-cell-edit";+ field.contentEditable = "plaintext-only";+ field.spellcheck = true;+ field.textContent = was;+ let saved = was;+ const save = () => {+ const now = (field.textContent ?? "").replace(/\n+/g, " ");+ if (now === saved) return;+ const before = saved;+ saved = now;+ field.classList.add("is-saving");+ api.noteTableSetCell(id, r, c, now).then(+ () => field.classList.remove("is-saving"),+ (e) => {+ // Refused: back as Apple has it, and why.+ saved = before;+ field.textContent = before;+ field.classList.remove("is-saving");+ field.title = String(e);+ field.classList.add("is-refused");+ window.setTimeout(() => { field.classList.remove("is-refused"); field.title = ""; }, 4000);+ },+ );+ };+ field.addEventListener("keydown", (e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ field.blur();+ } else if (e.key === "Escape") {+ field.textContent = saved;+ field.blur();+ }+ });+ field.addEventListener("blur", save);+ td.appendChild(field);+ });+ });+ dom.className = "nf-attachment is-table";+ dom.title = "";+ dom.replaceChildren(table);+ };+if (id) {api.noteTable(id).then((cells) => {- if (!cells || !cells.length) return;- const table = document.createElement("table");- table.className = "nf-table";- for (const row of cells) {- const tr = table.insertRow();- for (const cell of row) tr.insertCell().textContent = cell.trimEnd();- }- dom.className = "nf-attachment is-table";- dom.title = "A table — edit it on an Apple device for now";- dom.replaceChildren(table);+ if (cells && cells.length) draw(cells);+ else describe(id).then((info) => info && drawMedia(dom, info), () => {});},() => {},);}- return { dom, ignoreMutation: () => true, stopEvent: () => false };+ return {+ dom,+ ignoreMutation: () => true,+ // A cell's keys, clicks and typing are the cell's, not the note editor's.+ stopEvent: (e: Event) => Boolean((e.target as HTMLElement | null)?.closest?.(".nf-cell-edit, .nf-image, .nf-doc, .nf-file")),+ };}/** What the toolbar shows as on: the style of the line the cursor is in, and its marks. */diff --git a/src/styles/app.css b/src/styles/app.cssindex 452e563..6192ae6 100644--- a/src/styles/app.css+++ b/src/styles/app.css@@ -267,9 +267,10 @@/* Its own width changing lays out only itself. */contain: layout paint;overflow: hidden;- background: var(--glass);- -webkit-backdrop-filter: var(--glass-blur);- backdrop-filter: var(--glass-blur);+ /* Frosted to opaque, without a live blur: folding animates its width, and a blurred layer+ has its blur worked out again on every frame of that — a stutter in WebKitGTK, which+ does not draw the blur on many machines in any case. Content still passes under it. */+ background: var(--glass-thick);box-shadow: var(--glass-specular), 0 0 0 0.5px var(--glass-edge);border-radius: var(--r-plateau);padding: 12px 9px;@@ -1521,8 +1522,6 @@padding: 20px 22px;border-radius: var(--r-window);background: var(--glass-thick);- -webkit-backdrop-filter: var(--glass-blur);- backdrop-filter: var(--glass-blur);box-shadow: var(--glass-float);/* A sheet arrives on the smooth spring, growing the last few percent into place. */animation: modal-sheet-in 360ms var(--spring-smooth) both;@@ -1689,9 +1688,7 @@flex-direction: column;border: 1px solid var(--glass-edge);border-radius: 12px;- background: var(--glass);- -webkit-backdrop-filter: var(--glass-blur);- backdrop-filter: var(--glass-blur);+ background: var(--glass-thick);box-shadow: var(--shadow-sheet), var(--glass-specular);overflow: hidden;}@@ -1735,13 +1732,21 @@.upload-rows { margin: 0; padding: 0 6px 8px; list-style: none; overflow-y: auto; }.upload-row {+ padding: 6px 8px;+ border-radius: 8px;+}+/* A file, or a whole folder counted as one: glyph, name over its bar, how far, and its+ controls — the folder's ▸ to see what in it did not upload, and ✕ while it can stop. */+.upload-line {display: grid;- grid-template-columns: 22px minmax(0, 1fr) auto;+ grid-template-columns: 22px minmax(0, 1fr) auto auto auto;gap: 8px;align-items: center;- padding: 6px 8px;- border-radius: 8px;}+.upload-state { font-variant-numeric: tabular-nums; white-space: nowrap; }+.upload-failures { margin: 6px 0 2px 30px; padding: 0; list-style: none; font-size: var(--t-11); color: var(--text-2); max-height: 160px; overflow: auto; }+.upload-failures li { padding: 2px 0; }+.upload-failures b { color: var(--text); font-weight: 600; }.upload-glyph { display: grid; place-items: center; }.upload-text { display: flex; flex-direction: column; min-width: 0; }.upload-name,@@ -2028,3 +2033,24 @@.web-access-off p { color: var(--text-2); font-size: var(--t-15); line-height: 1.5; margin: 0 0 12px; }.web-access-off b { color: var(--text); font-weight: 600; }.settings-gap { margin-top: 12px; }++/* A new folder in the grid, named as Finder names one: the field fits its cell under the+ icon, its text centred. At the field's own width it overflowed the 112px cell and was cut+ off at the left. */+.drive-rows.is-grid .drive-row-new { flex-direction: column; justify-content: flex-start; gap: 8px; padding: 10px 6px; border-bottom: 0; }+.drive-rows.is-grid .drive-row-new input { flex: none; width: 100%; min-width: 0; text-align: center; font-size: var(--t-11); padding: 3px 4px; }++/* Uploads that can still be stopped have a ✕; the tray's Cancel stops every one of them. */+.upload-tray-actions { display: flex; align-items: center; gap: 10px; }+.upload-stop {+ flex: none; display: grid; place-items: center; width: 20px; height: 20px; margin-left: 6px; padding: 0;+ border: 0; border-radius: 50%; background: color-mix(in srgb, var(--text) 10%, transparent);+ color: var(--text-2); font-size: 10px; cursor: pointer;+}+.upload-stop:hover { background: color-mix(in srgb, var(--text) 18%, transparent); color: var(--text); }+.upload-row.is-cancelled .upload-name { color: var(--text-3); }+/* Still finding what is in a folder: no total yet, so no share of one — a segment gliding+ across instead of a number that would only shrink. */+.upload-bar.is-waiting > span { width: 30%; animation: upload-finding 1.2s var(--ease) infinite alternate; }+@keyframes upload-finding { from { transform: translateX(-10%); } to { transform: translateX(240%); } }+@media (prefers-reduced-motion: reduce) { .upload-bar.is-waiting > span { animation: none; width: 100%; opacity: 0.4; } }diff --git a/src/styles/calendar.css b/src/styles/calendar.cssindex c5de999..ac146a2 100644--- a/src/styles/calendar.css+++ b/src/styles/calendar.css@@ -181,9 +181,7 @@padding: 4px;overflow-y: auto;border-radius: 12px;- background: var(--glass);- -webkit-backdrop-filter: var(--glass-blur);- backdrop-filter: var(--glass-blur);+ background: var(--glass-thick);box-shadow: var(--glass-specular), 0 0 0 0.5px var(--glass-edge), var(--shadow-sheet);}.cx-found-row {@@ -589,6 +587,9 @@}/* ---- the event popover --------------------------------------------------------------- */+/* Frosted to opaque without a live blur, as the menus are: a blurred layer is one WebKitGTK+ composites on the frame it appears, and the popover appearing is what making an event+ is — the stutter. The sidebar and toolbars, which never appear or move, keep theirs. */.cx-popover {position: fixed;@@ -600,8 +601,6 @@padding: 14px 14px 12px;border-radius: 14px;background: var(--glass-thick);- -webkit-backdrop-filter: var(--glass-blur);- backdrop-filter: var(--glass-blur);box-shadow: var(--glass-float);/* Opacity and a small lift only, on the compositor: scaling from the corner read as ajump toward the click, and re-ran on every re-anchor. */@@ -684,8 +683,6 @@transform: translateX(-50%);border-radius: var(--r-pill);background: var(--glass-thick);- -webkit-backdrop-filter: var(--glass-blur);- backdrop-filter: var(--glass-blur);box-shadow: var(--glass-float);font-size: var(--t-13);}diff --git a/src/styles/notes.css b/src/styles/notes.cssindex ed058ff..765bca7 100644--- a/src/styles/notes.css+++ b/src/styles/notes.css@@ -405,3 +405,26 @@ textarea.note-title::placeholder { color: var(--text-3); }.note-rich .nf-attachment.is-table { display: block; padding: 0; margin: 6px 0; background: none; color: inherit; font-size: inherit; overflow-x: auto; }.nf-table { border-collapse: collapse; min-width: 50%; }.nf-table td { min-width: 120px; padding: 4px 8px; border: 1px solid color-mix(in srgb, var(--text) 22%, transparent); vertical-align: top; white-space: pre-wrap; }+/* A table's cells, edited in place: a typed cell is a quiet field that lights when it is the+ one being typed in; one Apple refused flashes red while it goes back. */+.nf-cell-edit { outline: none; min-height: 1.4em; border-radius: 3px; cursor: text; }+.nf-cell-edit:focus { box-shadow: 0 0 0 2px var(--accent-ring); background: color-mix(in srgb, var(--accent) 6%, transparent); }+.nf-cell-edit.is-saving { opacity: 0.7; }+.nf-cell-edit.is-refused { box-shadow: 0 0 0 2px color-mix(in srgb, var(--danger) 55%, transparent); }+.nf-cell-empty { color: var(--text-3); }+/* What a note holds besides text, drawn where it sits (NoteEditor's drawMedia): a picture at+ its own proportions, a document or film as its rendering with its name, anything else a+ chip. Each opens in the app this computer uses for it. */+.nf-attachment.is-image, .nf-attachment.is-doc, .nf-attachment.is-file { display: inline-block; vertical-align: top; max-width: 100%; }+.nf-image { display: block; max-width: min(100%, 640px); height: auto; border-radius: 10px; cursor: zoom-in; background: color-mix(in srgb, var(--text) 6%, transparent); }+.nf-doc { display: inline-flex; flex-direction: column; gap: 6px; padding: 8px; border: 0; border-radius: 12px; background: color-mix(in srgb, var(--text) 5%, transparent); color: var(--text); font: inherit; cursor: pointer; text-align: left; }+.nf-doc:hover { background: color-mix(in srgb, var(--text) 9%, transparent); }+.nf-doc-preview { display: block; width: 180px; max-width: 100%; height: auto; border-radius: 6px; box-shadow: 0 0 0 0.5px color-mix(in srgb, var(--text) 16%, transparent); background: #fff; }+.nf-doc.is-video .nf-doc-preview { background: #000; }+.nf-doc-name { font-size: var(--t-11); color: var(--text-2); max-width: 180px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.nf-file { display: inline-flex; align-items: center; gap: 10px; max-width: 360px; padding: 8px 12px; border: 0; border-radius: 12px; background: color-mix(in srgb, var(--text) 6%, transparent); color: var(--text); font: inherit; font-size: var(--t-13); cursor: pointer; }+.nf-file:hover { background: color-mix(in srgb, var(--text) 10%, transparent); }+.nf-file-glyph { flex: none; display: grid; place-items: center; min-width: 30px; height: 30px; padding: 0 4px; border-radius: 8px; background: var(--accent); color: var(--on-accent); font-size: 9px; font-weight: 700; letter-spacing: 0.02em; }+.nf-file.is-audio .nf-file-glyph, .nf-file.is-video .nf-file-glyph { font-size: 13px; }+.nf-file-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.nf-file-meta { flex: none; color: var(--text-3); font-size: var(--t-11); }