Skip to content

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

Proven iCloud writes on, Photos rebuilt, new features, data-safety and engine fixes

Yashwanth Kamireddi1fb59b5434a8
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
index 562f604..9dfb8ec 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -117,6 +117,17 @@ body:
- "On, with Access iCloud Data on the Web turned off"
- "Not sure"
+ - type: dropdown
+ id: account
+ attributes:
+ label: Apple Account
+ description: Accounts in mainland China and Managed Apple Accounts (from a school or workplace) aren't supported yet, so this tells us where to start.
+ options:
+ - "Personal, outside mainland China"
+ - "Personal, in mainland China"
+ - "Managed (school or workplace)"
+ - "Not sure"
+
- type: textarea
id: logs
attributes:
diff --git a/.github/workflows/flatpak.yml b/.github/workflows/flatpak.yml
index c71fe99..d1b5452 100644
--- a/.github/workflows/flatpak.yml
+++ b/.github/workflows/flatpak.yml
@@ -29,8 +29,6 @@ jobs:
fetch-depth: 0
- name: The checkout, trusted inside the container
run: git config --global --add safe.directory '*'
- - name: Flathub's shared modules (the tray library)
- run: git clone --depth 1 https://github.com/flathub/shared-modules.git packaging/flatpak/shared-modules
- uses: flatpak/flatpak-github-actions/flatpak-builder@v6
with:
manifest-path: packaging/flatpak/io.github.yashwanthkamireddi.Skykeep.yml
diff --git a/.github/workflows/linux-compat.yml b/.github/workflows/linux-compat.yml
new file mode 100644
index 0000000..20915f6
--- /dev/null
+++ b/.github/workflows/linux-compat.yml
@@ -0,0 +1,138 @@
+# Skykeep on every mainstream Linux, proven rather than assumed: the .deb, .rpm, Arch package
+# and AppImage each installed with the distribution's own package manager in a clean container
+# of it, then packaging/linux-compat/check.sh — every library found, the GStreamer elements
+# the player needs, a HEIC decoded through the system's libheif, a made-up session through
+# gnome-keyring's Secret Service by the app's own sign-in storage, the page drawn under Xvfb
+# and the program still up 8 s later, and the launchers, metainfo and icons valid.
+#
+# Not on every push: by hand (Actions → Linux compatibility → Run workflow), and for a release
+# tag. The packages are built the way release.yml builds them, on Ubuntu 24.04 — the oldest
+# base whose libheif (1.17) the app accepts; Debian 12 (libheif 1.15, glibc 2.36) cannot run it.
+name: Linux compatibility
+
+on:
+ workflow_dispatch:
+ push:
+ tags: ["v*"]
+
+permissions:
+ contents: read
+
+concurrency:
+ group: linux-compat-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ build:
+ runs-on: ubuntu-24.04
+ timeout-minutes: 60
+ steps:
+ - uses: actions/checkout@v4
+ - name: Build dependencies
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y --no-install-recommends \
+ libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev \
+ libsecret-1-dev libheif-dev libfuse3-dev pkg-config patchelf rpm file \
+ libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev \
+ gstreamer1.0-plugins-base gstreamer1.0-plugins-good gstreamer1.0-libav \
+ libheif-examples libheif-plugin-x265
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
+ cache: npm
+ - uses: dtolnay/rust-toolchain@stable
+ - uses: Swatinem/rust-cache@v2
+ - run: npm ci
+ - name: Build the packages
+ env:
+ RUSTFLAGS: --remap-path-prefix=${{ github.workspace }}=skykeep
+ run: npx tauri build
+ - name: Build the check's probe
+ run: cargo build --release --locked -p quince-probe --example distro_check
+ - name: A HEIC made for the test
+ # A 64×48 gradient, written as raw YUV and encoded with x265 — nobody's photo.
+ run: |
+ W=64 H=48
+ { printf 'YUV4MPEG2 W%s H%s F25:1 Ip A1:1 C420jpeg\nFRAME\n' "$W" "$H"
+ LC_ALL=C awk -v w=$W -v h=$H 'BEGIN {
+ for (y = 0; y < h; y++) for (x = 0; x < w; x++) printf "%c", 16 + int(200 * x / w)
+ for (i = 0; i < w * h / 2; i++) printf "%c", 90 + int(80 * (i % (w / 2)) / (w / 2)) }'
+ } > "$RUNNER_TEMP/test.y4m"
+ heif-enc -q 80 -o test.heic "$RUNNER_TEMP/test.y4m"
+ - name: Gather
+ run: |
+ mkdir compat
+ cp target/release/bundle/deb/*.deb target/release/bundle/rpm/*.rpm \
+ target/release/bundle/appimage/*.AppImage \
+ target/release/examples/distro_check test.heic packaging/linux-compat/check.sh compat/
+ ls -l compat
+ - uses: actions/upload-artifact@v4
+ with:
+ name: linux-compat
+ path: compat/
+ if-no-files-found: error
+ retention-days: 7
+
+ install:
+ needs: build
+ name: ${{ matrix.name }}
+ runs-on: ubuntu-24.04
+ timeout-minutes: 20
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - { name: "Ubuntu 24.04 (.deb)", image: "ubuntu:24.04", pkg: "*.deb" }
+ - { name: "Debian 13 (.deb)", image: "debian:trixie", pkg: "*.deb" }
+ # Linux Mint 22 and Pop!_OS 24.04 are both Ubuntu 24.04 underneath; Mint publishes
+ # an image of its own, Pop!_OS does not.
+ - { name: "Linux Mint 22 (.deb)", image: "linuxmintd/mint22-amd64", pkg: "*.deb" }
+ - { name: "Fedora 41 (.rpm)", image: "fedora:41", pkg: "*.rpm" }
+ - { name: "Fedora 42 (.rpm)", image: "fedora:42", pkg: "*.rpm" }
+ - { name: "openSUSE Tumbleweed (.rpm)", image: "opensuse/tumbleweed", pkg: "*.rpm" }
+ - { name: "Debian 13 (AppImage)", image: "debian:trixie", pkg: "*.AppImage" }
+ - { name: "Fedora 42 (AppImage)", image: "fedora:42", pkg: "*.AppImage" }
+ container:
+ image: ${{ matrix.image }}
+ steps:
+ - uses: actions/download-artifact@v4
+ with:
+ name: linux-compat
+ path: /compat
+ - name: Install and run
+ env:
+ PKG: ${{ matrix.pkg }}
+ run: |
+ chmod +x /compat/check.sh /compat/distro_check
+ # shellcheck disable=SC2086
+ bash /compat/check.sh /compat/$PKG /compat/distro_check /compat/test.heic
+
+ arch:
+ needs: build
+ name: Arch Linux (PKGBUILD)
+ runs-on: ubuntu-24.04
+ timeout-minutes: 60
+ container:
+ image: archlinux:latest
+ steps:
+ - name: Build tools
+ run: pacman -Syu --noconfirm --needed base-devel git rust nodejs npm
+ - uses: actions/checkout@v4
+ - uses: actions/download-artifact@v4
+ with:
+ name: linux-compat
+ path: /compat
+ - name: makepkg, as a user (it refuses root)
+ run: |
+ useradd -m builder
+ chown -R builder "$GITHUB_WORKSPACE"
+ # The package's own dependencies, from its PKGBUILD, as makepkg -s would install them.
+ # shellcheck disable=SC1091
+ (cd packaging/arch && source PKGBUILD && pacman -S --noconfirm --needed --asdeps "${depends[@]}" "${makedepends[@]}")
+ su builder -c "cd '$GITHUB_WORKSPACE/packaging/arch' && CARGO_BUILD_JOBS=4 makepkg -f --noconfirm"
+ - name: Install and run
+ run: |
+ chmod +x /compat/check.sh /compat/distro_check
+ bash /compat/check.sh "$(ls "$GITHUB_WORKSPACE"/packaging/arch/skykeep-*.pkg.tar.zst)" \
+ /compat/distro_check /compat/test.heic
diff --git a/.uiverify/a11y-keys.mjs b/.uiverify/a11y-keys.mjs
index 235ea4c..8b1e0ab 100644
--- a/.uiverify/a11y-keys.mjs
+++ b/.uiverify/a11y-keys.mjs
@@ -284,7 +284,7 @@ await group("notes", async () => {
await group("states", async () => {
// Reminders' sample alone: Calendar's sample reminders share its ids.
- const { ctx, page } = await fresh({}, null, { remindersFixture: true, notesFixture: true, calendarFixture: false });
+ const { ctx, page } = await fresh({}, null, { remindersFixture: true, notesFixture: true, contactsFixture: true, calendarFixture: false });
ok((await page.locator('.nav-item[aria-current="true"]').count()) === 1, "states: the sidebar marks its current app aria-current");
await openScreen(page, "Reminders");
await wait(page, 400);
@@ -303,7 +303,22 @@ await group("states", async () => {
ok((await page.locator('.cx-day[role="gridcell"][aria-selected="true"]').count()) === 1, "states: the chosen day is aria-selected in the month grid");
await openScreen(page, "Notes");
await wait(page, 300);
- ok((await page.locator('.note-row[aria-current="true"]').count()) === 1, "states: the open note is marked in its list");
+ ok((await page.locator('.note-row[aria-selected="true"]').count()) === 1, "states: the open note is marked in its list");
+ // A list box of options, not a list of buttons marked current: the open row is selected.
+ const notesBox = page.getByRole("listbox", { name: "Notes" });
+ ok((await notesBox.count()) === 1 && (await notesBox.getByRole("option", { selected: true }).count()) === 1
+ && (await page.locator('.note-row[aria-current]').count()) === 0, "states: Notes is a list box whose open note is its selected option");
+ ok((await notesBox.getByRole("group").count()) >= 1, "states: each heading of notes is a named group");
+ await openScreen(page, "Contacts");
+ await wait(page, 300);
+ const peopleBox = page.getByRole("listbox", { name: "Contacts" });
+ const people = await page.locator(".contact-row").evaluateAll((rows) => rows.map((r) => [r.getAttribute("role"), r.getAttribute("aria-selected"), r.hasAttribute("aria-current")]));
+ ok((await peopleBox.count()) === 1 && (await peopleBox.getAttribute("aria-multiselectable")) === "true" && people.length > 0
+ && people.every(([role, sel, cur]) => role === "option" && (sel === "true" || sel === "false") && !cur), `states: Contacts is a multi-select list box of options, each selected or not ${JSON.stringify(people.slice(0, 3))}`);
+ // A screen's own list box is not a menu: its keys still answer.
+ await page.keyboard.press("Control+f");
+ ok(await page.evaluate(() => document.activeElement?.matches?.('input[type="search"], .contacts input')), "states: the screen's keys answer beside its own list box");
+ await page.keyboard.press("Escape");
// A notice is said by a live region that was there before it.
const region = page.locator('.visually-hidden[role="status"][aria-live="polite"]').last();
ok((await region.count()) === 1, "states: a polite live region waits for notices");
@@ -386,6 +401,28 @@ await group("increase contrast", async () => {
await ctx.close();
});
+// The desktop's own switch, where the engine does not map it (Linux: the Settings portal, read
+// by appearance.rs): the same firmer look, and it follows the switch both ways while open.
+await group("contrast from the desktop", async () => {
+ const { ctx, page } = await fresh({}, () => { window.__contrast = true; });
+ await wait(page, 300);
+ const look = () => page.evaluate(() => ({
+ mark: document.documentElement.dataset.contrast ?? null,
+ sep: getComputedStyle(document.documentElement).getPropertyValue("--separator").trim(),
+ glass: getComputedStyle(document.documentElement).getPropertyValue("--glass-blur").trim(),
+ }));
+ let now = await look();
+ ok(now.mark === "more" && /rgba\(0, 0, 0, 0?\.42\)/.test(now.sep) && now.glass === "none", `desktop contrast: the root is marked and the edges firm up ${JSON.stringify(now)}`);
+ await page.evaluate(() => window.__emit("quince://contrast", false));
+ await wait(page, 100);
+ now = await look();
+ ok(now.mark === null && !/rgba\(0, 0, 0, 0?\.42\)/.test(now.sep), `desktop contrast: switched off, it goes back ${JSON.stringify(now)}`);
+ await page.evaluate(() => window.__emit("quince://contrast", true));
+ await wait(page, 100);
+ ok((await look()).mark === "more", "desktop contrast: switched on while open, it applies at once");
+ await ctx.close();
+});
+
await b.close();
console.log(failures ? `\nFAIL ${failures} check(s) (${engineName})` : `\nPASS keyboard, screen reader and display settings (${engineName})`);
process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/app-keys.mjs b/.uiverify/app-keys.mjs
new file mode 100644
index 0000000..04d2292
--- /dev/null
+++ b/.uiverify/app-keys.mjs
@@ -0,0 +1,86 @@
+// Keys that work from any app: Ctrl+, opens Settings, Ctrl+/ the Keyboard Shortcuts sheet
+// (the app in front listed first; Escape or Done closes it, and the keys go back where they
+// were). Settings sets Calendar's first day of the week and lists what Skykeep talks to.
+//
+// BASE=http://localhost:4320 ENGINE=webkit node .uiverify/app-keys.mjs
+import { engine, engineName } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const BASE = process.env.BASE ?? "http://localhost:4173";
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${engineName} ${m}`); if (!p) failures++; };
+
+for (const scheme of ["light", "dark"]) {
+ const ctx = await b.newContext({ viewport: { width: 1280, height: 820 }, colorScheme: scheme });
+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, calendarFixture: true, notesFixture: true });
+ await ctx.addInitScript(() => { window.__reachSubscribed = ["calendar.example.org"]; });
+ const page = await ctx.newPage();
+ page.on("pageerror", (e) => ok(false, `page error: ${e.message}`));
+ await page.goto(BASE, { waitUntil: "networkidle" });
+ await openScreen(page, "Calendar");
+ await page.waitForTimeout(300);
+
+ // ── Ctrl+/ : every app's keys, the one in front first ──
+ await page.keyboard.press("Control+/");
+ const sheet = page.getByRole("dialog", { name: "Keyboard Shortcuts" });
+ await sheet.waitFor();
+ const groups = await sheet.locator("h3").allInnerTexts();
+ ok(groups[0] === "Calendar" && groups.includes("Everywhere") && groups.length === 7, `${scheme}: the sheet lists every app, Calendar first ${JSON.stringify(groups)}`);
+ ok((await sheet.locator(".shortcuts-row", { hasText: "Settings" }).locator("kbd").allInnerTexts()).join("+") === "Ctrl+,", `${scheme}: it names Ctrl+, for Settings`);
+ const box = await sheet.boundingBox();
+ ok(box && box.width <= 760 && box.height <= 820 * 0.88 + 1, `${scheme}: it fits the window ${JSON.stringify(box)}`);
+ ok(await page.evaluate(() => document.activeElement?.textContent === "Done"), `${scheme}: Done has the focus`);
+ await page.keyboard.press("Tab");
+ ok(await page.evaluate(() => Boolean(document.activeElement?.closest(".shortcuts-sheet"))), `${scheme}: the focus stays in the sheet`);
+ await page.keyboard.press("Escape");
+ ok((await sheet.count()) === 0, `${scheme}: Escape closes it`);
+ await page.keyboard.press("Control+/");
+ await sheet.waitFor();
+ await sheet.getByRole("button", { name: "Done" }).click();
+ ok((await sheet.count()) === 0, `${scheme}: Done closes it`);
+
+ // ── Ctrl+, : Settings ──
+ await page.keyboard.press("Control+,");
+ await page.locator(".settings-title").waitFor();
+ ok((await page.locator('.sidebar-account[aria-current="true"]').count()) === 1, `${scheme}: Ctrl+, opens Settings`);
+
+ // ── What Skykeep talks to, from the network lock ──
+ const reach = page.getByRole("region", { name: "What Skykeep Talks To" }).or(page.locator(".settings-reach"));
+ const text = await reach.first().innerText();
+ ok(/apple\.com/.test(text) && /icloud-content\.com/.test(text) && !/\.cn\b/.test(text) && /mainland China/.test(text), `${scheme}: Apple's domains are listed ${JSON.stringify(text.slice(0, 160))}`);
+ ok(text.includes("calendar.example.org"), `${scheme}: and each subscribed calendar's host`);
+
+ // ── First Day of Week ──
+ const picker = page.getByRole("button", { name: /First Day of Week/ });
+ ok((await picker.innerText()).startsWith("Automatic ("), `${scheme}: the week starts as the locale says ${await picker.innerText()}`);
+ await picker.click();
+ await page.getByRole("option", { name: "Monday" }).click();
+ ok(await page.evaluate(() => localStorage.getItem("quince.weekStart")) === "1", `${scheme}: Monday is kept`);
+ await openScreen(page, "Calendar");
+ await page.getByRole("button", { name: "Month", exact: true }).click();
+ await page.waitForTimeout(300);
+ const firstHead = await page.evaluate(() => [document.querySelector(".cx-weekdays span")?.textContent, document.querySelector(".cx-day-hit")?.getAttribute("aria-label")]);
+ ok(firstHead[0] === "Mon" && /^Monday/.test(firstHead[1] ?? ""), `${scheme}: Month starts its rows on Monday, at once ${JSON.stringify(firstHead)}`);
+ await page.keyboard.press("Control+,");
+ await page.getByRole("button", { name: /First Day of Week/ }).click();
+ await page.getByRole("option", { name: /^Automatic/ }).click();
+ ok(await page.evaluate(() => localStorage.getItem("quince.weekStart")) === null, `${scheme}: Automatic goes back to the locale's`);
+ await ctx.close();
+}
+
+// The system's LC_TIME, where the engine reads only LANG: a British clock starts on Monday.
+{
+ const ctx = await b.newContext({ viewport: { width: 1280, height: 820 }, locale: "en-US" });
+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, calendarFixture: true });
+ await ctx.addInitScript(() => { window.__timeLocale = "en-GB"; });
+ const page = await ctx.newPage();
+ await page.goto(BASE, { waitUntil: "networkidle" });
+ await openScreen(page, "Calendar");
+ await page.getByRole("button", { name: "Month", exact: true }).click();
+ await page.waitForTimeout(400);
+ const first = await page.evaluate(() => document.querySelector(".cx-day-hit")?.getAttribute("aria-label") ?? "");
+ ok(/^Monday/.test(first), `LC_TIME en_GB under an American LANG starts the week on Monday ${JSON.stringify(first)}`);
+ await ctx.close();
+}
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/calendar-guests.mjs b/.uiverify/calendar-guests.mjs
new file mode 100644
index 0000000..16a786b
--- /dev/null
+++ b/.uiverify/calendar-guests.mjs
@@ -0,0 +1,52 @@
+// An event's guests: the count, the organizer first, each one's answer in a word and a mark,
+// you named as You; an event with none shows no Guests section.
+//
+// BASE=http://localhost:4173 ENGINE=webkit node .uiverify/calendar-guests.mjs
+import { engine, engineName } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const BASE = process.env.BASE ?? "http://localhost:4173";
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${engineName} ${m}`); if (!p) failures++; };
+
+for (const scheme of ["light", "dark"]) {
+ const ctx = await b.newContext({ viewport: { width: 1300, height: 850 }, colorScheme: scheme });
+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, calendarFixture: true });
+ await ctx.addInitScript(() => {
+ window.__guests = { e1: [
+ { name: "Priya Nair", email: "[email protected]", status: "tentative", isMe: false, isOrganizer: true },
+ { name: "Alex Rivera", email: "[email protected]", status: "accepted", isMe: true, isOrganizer: false },
+ { name: null, email: "[email protected]", status: "declined", isMe: false, isOrganizer: false },
+ { name: "Lee", email: null, status: "pending", isMe: false, isOrganizer: false },
+ ] };
+ });
+ const page = await ctx.newPage();
+ page.on("pageerror", (e) => ok(false, `page error: ${e.message}`));
+ await page.goto(BASE, { waitUntil: "networkidle" });
+ await openScreen(page, "Calendar");
+ await page.keyboard.press("Control+1");
+ await page.waitForTimeout(400);
+
+ await page.locator(".cx-block", { hasText: "Design review" }).first().click();
+ const pop = page.getByRole("dialog", { name: "Design review" });
+ await pop.waitFor();
+ const section = pop.getByRole("region", { name: "Guests" });
+ await section.waitFor();
+ ok((await section.locator(".cx-guests-head").innerText()).trim() === "4 Guests", `${scheme}: the count heads the list`);
+ const rows = await section.locator(".cx-guest").allInnerTexts();
+ const flat = rows.map((r) => r.replace(/\s+/g, " ").trim());
+ ok(/Priya Nair · Organizer/.test(flat[0]) && /Maybe/.test(flat[0]), `${scheme}: the organizer first, with their answer ${JSON.stringify(flat[0])}`);
+ ok(flat.some((r) => /Alex Rivera · You/.test(r) && /Accepted/.test(r)), `${scheme}: you are named You`);
+ ok(flat.some((r) => /sam@example\.com/.test(r) && /Declined/.test(r)), `${scheme}: one with no name shows the address`);
+ ok(flat.some((r) => /Lee/.test(r) && /No reply/.test(r)), `${scheme}: no answer yet says so`);
+ await page.keyboard.press("Escape");
+ await page.waitForTimeout(200);
+
+ await page.locator(".cx-block", { hasText: "Dentist" }).first().click();
+ await page.getByRole("dialog", { name: "Dentist" }).waitFor();
+ await page.waitForTimeout(300);
+ ok((await page.getByRole("region", { name: "Guests" }).count()) === 0, `${scheme}: an event with no guests shows no Guests`);
+ await ctx.close();
+}
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/calendar-join.mjs b/.uiverify/calendar-join.mjs
new file mode 100644
index 0000000..8e29cb8
--- /dev/null
+++ b/.uiverify/calendar-join.mjs
@@ -0,0 +1,57 @@
+// Join: an event with a video call's link shows a Join pill naming the service, opening the
+// call's own link; an event with none — or a look-alike link — shows nothing.
+//
+// BASE=http://localhost:4173 ENGINE=webkit node .uiverify/calendar-join.mjs
+import { engine, engineName } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const BASE = process.env.BASE ?? "http://localhost:4173";
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${engineName} ${m}`); if (!p) failures++; };
+
+for (const scheme of ["light", "dark"]) {
+ const ctx = await b.newContext({ viewport: { width: 1300, height: 850 }, colorScheme: scheme });
+ await ctx.addInitScript(installStub, {
+ screen: "library", services: SERVICES, twoFactor: null, calendarFixture: true,
+ extraEvents: [
+ { guid: "call", title: "Weekly sync", hour: 7, notes: "Agenda first.\nJoin: https://us02web.zoom.us/j/8123456789?pwd=abc." },
+ { guid: "fake", title: "Phishy", hour: 8, notes: "https://zoom.us.evil.example/j/1" },
+ ],
+ });
+ const page = await ctx.newPage();
+ page.on("pageerror", (e) => ok(false, `page error: ${e.message}`));
+ await page.goto(BASE, { waitUntil: "networkidle" });
+ await openScreen(page, "Calendar");
+ await page.keyboard.press("Control+1");
+ await page.waitForTimeout(400);
+
+ await page.locator(".cx-block", { hasText: "Weekly sync" }).first().click();
+ const pop = page.getByRole("dialog", { name: "Weekly sync" });
+ await pop.waitFor();
+ const join = pop.locator(".cx-join");
+ ok(await join.isVisible(), `${scheme}: an event with a Zoom link shows Join`);
+ ok((await join.innerText()).trim() === "Join Zoom", `${scheme}: it names the service "${(await join.innerText()).trim()}"`);
+ ok((await join.getAttribute("href")) === "https://us02web.zoom.us/j/8123456789?pwd=abc", `${scheme}: it opens the call's own link, the full stop left off`);
+ const contrast = await join.evaluate((el) => {
+ const rgb = (c) => c.match(/\d+(\.\d+)?/g).slice(0, 3).map(Number).map((v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; });
+ const lum = (c) => { const [r, g, b2] = rgb(c); return 0.2126 * r + 0.7152 * g + 0.0722 * b2; };
+ const s = getComputedStyle(el); const a = lum(s.color), c = lum(s.backgroundColor);
+ return (Math.max(a, c) + 0.05) / (Math.min(a, c) + 0.05);
+ });
+ ok(contrast >= 4.5, `${scheme}: its text reads at ${contrast.toFixed(2)}:1`);
+ await page.keyboard.press("Escape");
+ await page.waitForTimeout(200);
+
+ await page.locator(".cx-block", { hasText: "Phishy" }).first().click();
+ await page.getByRole("dialog", { name: "Phishy" }).waitFor();
+ ok((await page.locator(".cx-join").count()) === 0, `${scheme}: a look-alike host makes no Join`);
+ await page.keyboard.press("Escape");
+ await page.waitForTimeout(200);
+
+ await page.locator(".cx-block", { hasText: "Dentist" }).first().click();
+ await page.getByRole("dialog", { name: "Dentist" }).waitFor();
+ ok((await page.locator(".cx-join").count()) === 0, `${scheme}: an event with no call shows no Join`);
+ await ctx.close();
+}
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/calendar-meeting.test.mjs b/.uiverify/calendar-meeting.test.mjs
new file mode 100644
index 0000000..b45cbdb
--- /dev/null
+++ b/.uiverify/calendar-meeting.test.mjs
@@ -0,0 +1,42 @@
+// The Join button's link: found by each service's own host and path, never by a word, and
+// never on a look-alike host.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { meetingOf } from "../src/screens/calendar/model.ts";
+
+test("each service's join link is found where calendars put it", () => {
+ assert.deepEqual(meetingOf({ url: "https://us02web.zoom.us/j/8123456789?pwd=abc" }), { href: "https://us02web.zoom.us/j/8123456789?pwd=abc", service: "Zoom" });
+ assert.equal(meetingOf({ location: "https://meet.google.com/abc-defg-hij" })?.service, "Google Meet");
+ assert.equal(meetingOf({ notes: "Join: https://teams.microsoft.com/l/meetup-join/19%3ameeting_x/0?context=y" })?.service, "Microsoft Teams");
+ assert.equal(meetingOf({ notes: "https://acme.webex.com/meet/jo" })?.service, "Webex");
+ assert.equal(meetingOf({ url: "https://facetime.apple.com/join#v=1&p=AbC" })?.service, "FaceTime");
+});
+
+test("the URL field comes first, then the location, then the notes", () => {
+ const e = { url: "https://meet.google.com/aaa-bbbb-ccc", location: "https://zoom.us/j/1", notes: "https://zoom.us/j/2" };
+ assert.equal(meetingOf(e)?.service, "Google Meet");
+ assert.equal(meetingOf({ location: "Room 4", notes: "dial in https://zoom.us/j/99. Thanks!" })?.href, "https://zoom.us/j/99");
+});
+
+test("look-alikes, plain words and other links make no button", () => {
+ for (const text of [
+ "https://zoom.us.evil.example/j/1",
+ "https://notzoom.us/j/1",
+ "https://meet.google.com.example.org/abc-defg-hij",
+ "http://zoom.us/j/1",
+ "Let's zoom in on the plan",
+ "https://zoom.us/pricing",
+ "https://meet.google.com/",
+ "https://example.com/teams.microsoft.com/l/meetup-join/x",
+ "",
+ ]) {
+ assert.equal(meetingOf({ notes: text }), null, text);
+ }
+ assert.equal(meetingOf({}), null);
+ assert.equal(meetingOf({ url: null, location: null, notes: null }), null);
+});
+
+test("trailing punctuation and brackets are left off", () => {
+ assert.equal(meetingOf({ notes: "(https://zoom.us/j/123)." })?.href, "https://zoom.us/j/123");
+ assert.equal(meetingOf({ notes: "link: https://meet.google.com/abc-defg-hij!" })?.href, "https://meet.google.com/abc-defg-hij");
+});
diff --git a/.uiverify/calendar-outbox.mjs b/.uiverify/calendar-outbox.mjs
new file mode 100644
index 0000000..79b716f
--- /dev/null
+++ b/.uiverify/calendar-outbox.mjs
@@ -0,0 +1,104 @@
+// Calendar's half of the outbox: an event saved here and not yet at Apple says "Waiting to
+// sync" where it opens, and a change Apple turned down shows with what it held — sent again or
+// let go, never dropped. The marker goes once the queue says Apple has it.
+//
+// BASE=http://localhost:4320 ENGINE=webkit node .uiverify/calendar-outbox.mjs
+import { engine, engineName } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const BASE = process.env.BASE ?? "http://localhost:4173";
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+
+for (const scheme of ["light", "dark"]) {
+ const ctx = await b.newContext({ viewport: { width: 1300, height: 850 }, colorScheme: scheme });
+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, calendarFixture: true });
+ await ctx.addInitScript(() => {
+ window.__outbox = {
+ waiting: [{ service: "calendar", record: "e1", kind: "save" }],
+ refused: [
+ { id: 7, service: "calendar", record: "e2", kind: "save", madeAt: 0,
+ reason: "This event was changed on another device at the same time.", content: "Dentist at noon" },
+ { id: 8, service: "calendar", record: "e2", kind: "delete", madeAt: 0,
+ reason: "This event was deleted on another device.", content: "Dentist" },
+ // Another app's refusal stays in that app.
+ { id: 9, service: "notes", record: "n1", kind: "save", madeAt: 0, reason: "Not this one.", content: "x" },
+ ],
+ };
+ });
+ const page = await ctx.newPage();
+ await page.goto(BASE, { waitUntil: "networkidle" });
+ await openScreen(page, "Calendar");
+ await page.keyboard.press("Control+2");
+ await page.waitForTimeout(300);
+ const tag = `[${engineName} ${scheme}]`;
+
+ // ── Refused: said with why and what it held, one at a time, oldest first ──
+ const notice = page.locator(".unsent");
+ await notice.waitFor();
+ const words = await notice.innerText();
+ ok(/changed on another device/.test(words) && words.includes("Dentist at noon"), `${tag} a refused change says why, with what it held`);
+ ok(words.includes("(and 1 more)") && !words.includes("Not this one"), `${tag} only Calendar's refusals, the rest counted`);
+ const label = await notice.locator("p").first().getAttribute("aria-label");
+ ok(label?.startsWith("iCloud didn’t take a change to an event:"), `${tag} a screen reader hears what kind of change it was ${JSON.stringify(label)}`);
+ ok((await notice.getAttribute("role")) === "alert", `${tag} it is announced`);
+ const box = await notice.boundingBox();
+ // The scrolling day area, not its first event: Week opens scrolled to now, so an event
+ // earlier in the day can sit above the visible area — measured against it, any notice failed.
+ const grid = await page.locator(".cx-week-grid, .cx-timeline, .cx-scroll").first().boundingBox();
+ ok(box && grid && box.y + box.height <= grid.y + 1, `${tag} in the flow above the grid, not over an event`);
+ if (scheme === "dark") {
+ const bg = await notice.evaluate((el) => getComputedStyle(el).backgroundColor);
+ ok(bg !== "rgb(255, 255, 255)", `${tag} the notice follows the dark look ${bg}`);
+ }
+
+ // ── Try Again sends that one again; the next refusal takes its place ──
+ await notice.getByRole("button", { name: "Try Again" }).click();
+ await page.waitForTimeout(300);
+ ok(JSON.stringify(await page.evaluate(() => window.__outboxCalls)) === JSON.stringify([["outbox_resend", 7]]), `${tag} Try Again sends that change again`);
+ ok((await notice.innerText()).includes("deleted on another device") && !(await notice.innerText()).includes("more)"), `${tag} the next one shows`);
+ ok((await notice.getByRole("button", { name: "Copy Text" }).count()) === 1, `${tag} its words can be copied out`);
+
+ // ── Discard lets it go: Apple's version stands ──
+ await notice.getByRole("button", { name: "Discard" }).click();
+ await page.waitForTimeout(300);
+ ok(JSON.stringify((await page.evaluate(() => window.__outboxCalls)).at(-1)) === JSON.stringify(["outbox_discard", 8]), `${tag} Discard lets it go`);
+ ok((await page.locator(".unsent").count()) === 0, `${tag} and the notice leaves`);
+
+ // ── Waiting to sync, where the event opens ──
+ await page.locator(".cx-block", { hasText: "Design review" }).first().click();
+ const pop = page.getByRole("dialog", { name: "Design review" });
+ await pop.waitFor();
+ const marker = pop.locator(".sync-waiting");
+ ok((await marker.count()) === 1 && (await marker.innerText()) === "Waiting to sync", `${tag} an event saved here and not yet at Apple says so`);
+ ok((await marker.getAttribute("role")) === "status", `${tag} the marker is a status, read out politely`);
+ const actions = await pop.locator(".cx-pop-actions").boundingBox();
+ const mbox = await marker.boundingBox();
+ ok(mbox && actions && mbox.y >= actions.y - 1 && mbox.y + mbox.height <= actions.y + actions.height + 1, `${tag} it sits in the popover's action row`);
+ await page.keyboard.press("Escape");
+ await page.locator(".cx-block", { hasText: "Dentist" }).first().click();
+ const other = page.getByRole("dialog", { name: "Dentist" });
+ await other.waitFor();
+ ok((await other.locator(".sync-waiting").count()) === 0, `${tag} an event Apple has says nothing`);
+ await page.keyboard.press("Escape");
+
+ // ── Sent: the backend says the queue moved, and the marker goes ──
+ await page.evaluate(() => { window.__outbox = { waiting: [], refused: [] }; window.__emit("quince://outbox-changed", null); });
+ await page.waitForTimeout(300);
+ await page.locator(".cx-block", { hasText: "Design review" }).first().click();
+ await pop.waitFor();
+ ok((await pop.locator(".sync-waiting").count()) === 0, `${tag} once Apple has it, the marker goes`);
+ await page.keyboard.press("Escape");
+
+ // ── Refused while the window is open: told at once, without a reload ──
+ await page.evaluate(() => {
+ window.__outbox = { waiting: [], refused: [{ id: 11, service: "calendar", record: "e1", kind: "delete", madeAt: 0,
+ reason: "Apple turned that change down.", content: "Design review" }] };
+ window.__emit("quince://outbox-refused", { service: "calendar", record: "e1", message: "Apple turned that change down." });
+ });
+ await page.locator(".unsent").waitFor({ timeout: 2000 });
+ ok((await page.locator(".unsent").innerText()).includes("Design review"), `${tag} a refusal that arrives later shows at once`);
+ await ctx.close();
+}
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/calendar-reminder-colour.mjs b/.uiverify/calendar-reminder-colour.mjs
index ed6b882..f269858 100644
--- a/.uiverify/calendar-reminder-colour.mjs
+++ b/.uiverify/calendar-reminder-colour.mjs
@@ -3,7 +3,7 @@
import { engine } from "./engine.mjs";
import { SERVICES, installStub, openScreen } from "./stub.mjs";
const b = await engine.launch();
-const ctx = await b.newContext({ viewport: { width: 1300, height: 850 } });
+const ctx = await b.newContext({ viewport: { width: 1300, height: 1100 } });
await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, calendarFixture: true, remindersFixture: true });
const page = await ctx.newPage();
await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
diff --git a/.uiverify/calendar-sidebar-search.mjs b/.uiverify/calendar-sidebar-search.mjs
index 6128909..6c57650 100644
--- a/.uiverify/calendar-sidebar-search.mjs
+++ b/.uiverify/calendar-sidebar-search.mjs
@@ -16,7 +16,7 @@ let failures = 0;
const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
ok(await page.locator(".cx-weeknum").count() === 0, "no week numbers by default");
-await page.getByRole("button", { name: "More" }).click();
+await page.getByRole("button", { name: "More", exact: true }).click();
await page.getByRole("menuitemcheckbox", { name: "Show Week Numbers" }).click();
await page.waitForTimeout(200);
const nums = await page.locator(".cx-weeknum").allInnerTexts();
diff --git a/.uiverify/contact-birthday.mjs b/.uiverify/contact-birthday.mjs
index 6cb1610..e56011d 100644
--- a/.uiverify/contact-birthday.mjs
+++ b/.uiverify/contact-birthday.mjs
@@ -17,7 +17,7 @@ await ctx.addInitScript(() => {
};
});
const page = await ctx.newPage();
-await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await page.goto(process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
await page.locator(".nav-item", { hasText: "Contacts" }).click();
await page.waitForTimeout(400);
await page.locator(".contact-row", { hasText: "Zoya" }).click();
@@ -32,15 +32,29 @@ ok(/birthday\s*(17 March|March 17)/i.test(card) && !card.includes("1604"),
await page.getByRole("button", { name: "Edit", exact: true }).click();
await page.waitForTimeout(200);
-const noYear = page.getByLabel("Year unknown");
-ok(await noYear.isChecked(), "editing keeps it as a birthday with no year", "the year-unknown box is not ticked");
-await noYear.uncheck();
-await page.getByLabel("Birthday").fill("1998-03-17");
+// Month, day and year as three fields, the year left empty for a birthday Apple keeps without one.
+const month = await page.getByLabel("Birthday, month").innerText();
+const day = await page.getByLabel("Birthday, day").inputValue();
+const year = await page.getByLabel("Birthday, year").inputValue();
+ok(/March/.test(month) && day === "17" && year === "", "editing keeps it as a birthday with no year",
+ `month ${month}, day ${day}, year ${year}`);
+await page.getByLabel("Birthday, year").fill("1998");
await page.getByRole("button", { name: "Save" }).click();
await page.waitForTimeout(300);
const sent = await page.evaluate(() => (window.__contactSaves ?? []).at(-1));
const birthday = JSON.stringify(sent ?? {}).match(/"birthday":"([^"]*)"/)?.[1];
ok(birthday === "1998-03-17", "and a birthday set here goes to iCloud as Apple writes it", `sent: ${birthday}`);
+// The year taken away again: Apple's no-year 1604.
+await page.locator(".contact-row", { hasText: "Zoya" }).click();
+await page.getByRole("button", { name: "Edit", exact: true }).click();
+await page.waitForTimeout(200);
+await page.getByLabel("Birthday, year").fill("");
+await page.getByLabel("Birthday, day").fill("31");
+await page.getByRole("button", { name: "Save" }).click();
+await page.waitForTimeout(300);
+const again = JSON.stringify(await page.evaluate(() => (window.__contactSaves ?? []).at(-1)) ?? {}).match(/"birthday":"([^"]*)"/)?.[1];
+ok(again === "1604-03-31", "with no year it goes as Apple writes one", `sent: ${again}`);
+
await b.close();
process.exitCode = failures === 0 ? 0 : 1;
diff --git a/.uiverify/contacts-address.mjs b/.uiverify/contacts-address.mjs
index de9f3ac..4084164 100644
--- a/.uiverify/contacts-address.mjs
+++ b/.uiverify/contacts-address.mjs
@@ -6,7 +6,7 @@
import { engine, engineName } from "./engine.mjs";
import { SERVICES, installStub } from "./stub.mjs";
-const URL = process.env.URL ?? "http://localhost:4173";
+const URL = process.env.URL ?? process.env.URL ?? "http://localhost:4173";
const SHOTS = process.env.SHOTS ?? null;
const b = await engine.launch();
let failures = 0;
@@ -87,7 +87,8 @@ for (const scheme of ["light", "dark"]) {
// ── Add one, with its label ──
await page.getByRole("button", { name: "Edit", exact: true }).click();
- await page.getByRole("button", { name: "Add address" }).click();
+ await page.getByRole("button", { name: "Add Field" }).click();
+ await page.getByRole("menuitem", { name: "Address" }).click();
const newStreet = page.getByLabel("Street, address 3");
ok(await newStreet.evaluate((el) => el === document.activeElement), "a new address starts in its street");
await newStreet.fill("1 Main St");
@@ -133,6 +134,26 @@ for (const scheme of ["light", "dark"]) {
await page.waitForFunction(() => (window.__addressEdits ?? []).length === 5);
await page.waitForTimeout(700);
ok((await card.locator(".contact-postal").first().innerText()).includes("Unter den Linden 1"), "trying again writes it");
+
+ // ── A brand-new card takes an address too: the card is saved, then its address queued
+ // behind it under the id the card was given (outbox.rs keeps the order) ──
+ await page.evaluate(() => { window.__addressDelay = 50; });
+ const editsBefore = await page.evaluate(() => (window.__addressEdits ?? []).length);
+ await page.getByRole("button", { name: "New contact" }).click();
+ await page.locator(".contact-form").waitFor();
+ await page.getByLabel("First", { exact: true }).fill("Meera");
+ await page.getByRole("button", { name: "Add Field" }).click();
+ await page.getByRole("menuitem", { name: "Address" }).click();
+ await page.getByLabel("Street, address 1").fill("4 Lake View");
+ await page.getByLabel("City, address 1").fill("Chennai");
+ await page.getByLabel("Country, address 1").fill("India");
+ await page.getByRole("button", { name: "Add contact" }).click();
+ await page.waitForFunction((n) => (window.__addressEdits ?? []).length === n + 1, editsBefore);
+ const fresh = await page.evaluate(() => ({ save: window.__contactSaves.at(-1), edit: window.__addressEdits.at(-1) }));
+ ok(fresh.save.contact.firstName === "Meera" && !fresh.save.contact.guid, `the new card is saved first ${JSON.stringify(fresh.save.contact.firstName)}`);
+ ok(fresh.edit.guid === "C-new" && fresh.edit.base.length === 0 && fresh.edit.edits.length === 1 && fresh.edit.edits[0].op === "add"
+ && fresh.edit.edits[0].address.city === "Chennai" && fresh.edit.edits[0].address.countryCode === "in",
+ `its address goes as one addition, to the card's new id ${JSON.stringify(fresh.edit)}`);
await ctx.close();
}
await b.close();
diff --git a/.uiverify/contacts-fields.mjs b/.uiverify/contacts-fields.mjs
new file mode 100644
index 0000000..3236147
--- /dev/null
+++ b/.uiverify/contacts-fields.mjs
@@ -0,0 +1,136 @@
+// Every field Apple's Contacts keeps, shown and written as the iPhone stores it: the whole
+// name (prefix, middle, suffix, nickname, phonetic), work, dates, related people, social
+// profiles, instant messages, labels in Apple's own words — and the photo, chosen and cropped.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub } from "./stub.mjs";
+
+const b = await engine.launch();
+const ctx = await b.newContext({ viewport: { width: 1280, height: 860 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, contactsFixture: true });
+await ctx.addInitScript(() => {
+ const internals = window.__TAURI_INTERNALS__;
+ const invoke = internals.invoke;
+ internals.invoke = async (cmd, args) => {
+ const answer = await invoke(cmd, args);
+ if (cmd === "contacts_list" && Array.isArray(answer))
+ return answer.map((c) => c.guid !== "c1" ? c : {
+ ...c, photoUrl: "https://p.example/c1", photoSignature: "s1", photoCrop: "0,0,100,100",
+ prefix: "Dr.", suffix: "PhD", nickname: "Zo", phoneticFirstName: "ZOY-ah", jobTitle: "Architect", department: "Design",
+ methods: [
+ { kind: "phone", label: "_$!<Mobile>!$_", value: "+91 90000 00001" },
+ { kind: "email", label: "HOME", value: "[email protected]" },
+ { kind: "date", label: "ANNIVERSARY", value: "2015-02-14" },
+ { kind: "related", label: "MOTHER", value: "Amma" },
+ { kind: "profile", label: "TWITTER", value: "zoya" },
+ { kind: "im", label: "SKYPE", value: "zoya.a" },
+ ],
+ });
+ return answer;
+ };
+});
+const page = await ctx.newPage();
+await page.goto(process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
+await page.locator(".nav-item", { hasText: "Contacts" }).click();
+await page.waitForTimeout(400);
+await page.locator(".contact-row", { hasText: "Zoya" }).click();
+await page.waitForTimeout(300);
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+
+// Each label carries a hidden "copied", for when it is clicked; read without it.
+const card = (await page.locator(".contact-detail").innerText()).replace(/\s+/g, " ").replace(/ copied/g, "");
+ok(card.includes("Dr. Zoya Ahuja, PhD"), `the whole name, prefix and suffix ${card.slice(0, 80)}`);
+ok(card.includes("“Zo”") && card.includes("ZOY-ah"), "the nickname and the phonetic name");
+ok(card.includes("Architect, Design"), "job title and department");
+ok(/mobile \+91 90000 00001/.test(card), "Apple's internal _$!<Mobile>!$_ reads as \"mobile\"");
+ok(/anniversary (14 February 2015|February 14, 2015)/.test(card), `a date, labelled in Apple's words`);
+ok(/mother Amma/.test(card) && /Skype zoya\.a/.test(card) && /Twitter @zoya/.test(card), "a related name, an instant message, a social profile");
+ok((await page.locator('.contact-detail a[href="https://twitter.com/zoya"]').count()) === 1, "the profile opens its page");
+
+await page.getByRole("button", { name: "Edit", exact: true }).click();
+await page.waitForTimeout(200);
+ok(/mobile/.test(await page.getByLabel("Label for detail 1").innerText()) && (await page.getByLabel("Custom label for detail 1").count()) === 0,
+ "the internal spelling is Apple's own label in the editor, not a custom one");
+ok(await page.getByLabel("Prefix").inputValue() === "Dr." && await page.getByLabel("Nickname").inputValue() === "Zo", "fields holding something are in the form");
+ok((await page.getByLabel("Middle").count()) === 0, "fields holding nothing wait in Add Field");
+
+await page.getByLabel("Nickname").fill("Zee");
+await page.getByRole("button", { name: "Add Field" }).click();
+const offered = await page.getByRole("menuitem").allInnerTexts();
+ok(["Phone", "Email", "URL", "Address", "Date", "Related Name", "Social Profile", "Instant Message", "Middle name", "Phonetic last name"].every((x) => offered.includes(x)),
+ `Add Field offers every kind ${JSON.stringify(offered)}`);
+await page.getByRole("menuitem", { name: "Middle name" }).click();
+await page.getByLabel("Middle").fill("K");
+await page.getByRole("button", { name: "Add Field" }).click();
+await page.getByRole("menuitem", { name: "Related Name" }).click();
+await page.getByLabel("Value for detail 7").fill("Ravi");
+await page.getByLabel("Label for detail 7").click();
+await page.getByRole("option", { name: "spouse", exact: true }).click();
+await page.getByRole("button", { name: "Add Field" }).click();
+await page.getByRole("menuitem", { name: "Date" }).click();
+await page.getByLabel("Date 8, month").click();
+await page.getByRole("option", { name: /^Jul/ }).click();
+await page.getByLabel("Date 8, day").fill("4");
+await page.getByRole("button", { name: "Add Field" }).click();
+await page.getByRole("menuitem", { name: "Instant Message" }).click();
+await page.getByLabel("Service for detail 9").click();
+const services = await page.getByRole("option").allInnerTexts();
+ok(services.some((s) => /Jabber/.test(s)) && !services.some((s) => /Custom/.test(s)), "a service is picked from Apple's list");
+await page.getByRole("option", { name: "Jabber" }).click();
+await page.getByLabel("Value for detail 9").fill("[email protected]");
+
+// A photo: a new one chosen, moved in the circle, kept.
+await page.getByRole("button", { name: "Edit photo" }).click();
+const png = await page.evaluate(() => {
+ const c = document.createElement("canvas");
+ c.width = 900; c.height = 600;
+ const x = c.getContext("2d");
+ const g = x.createLinearGradient(0, 0, 900, 600);
+ g.addColorStop(0, "#f4a261"); g.addColorStop(1, "#2a9d8f");
+ x.fillStyle = g; x.fillRect(0, 0, 900, 600);
+ x.fillStyle = "#264653"; x.beginPath(); x.arc(600, 260, 120, 0, 7); x.fill();
+ return c.toDataURL("image/png").split(",")[1];
+});
+await page.getByLabel("Photo file").setInputFiles({ name: "face.png", mimeType: "image/png", buffer: Buffer.from(png, "base64") });
+await page.locator(".photo-frame-image").waitFor();
+const frame = await page.locator(".photo-frame").boundingBox();
+await page.mouse.move(frame.x + 120, frame.y + 120);
+await page.mouse.down();
+await page.mouse.move(frame.x + 40, frame.y + 120, { steps: 4 });
+await page.mouse.up();
+await page.getByLabel("Zoom").fill("40");
+await page.getByRole("button", { name: "Done" }).click();
+await page.waitForTimeout(150);
+ok((await page.locator(".contact-form-head .avatar img").getAttribute("src"))?.startsWith("data:image/jpeg"), "the chosen square shows on the card at once");
+
+await page.getByRole("button", { name: "Save" }).click();
+await page.waitForTimeout(300);
+const sent = await page.evaluate(() => (window.__contactSaves ?? []).at(-1));
+const c = sent?.contact ?? {};
+ok(c.nickname === "Zee" && c.middleName === "K" && c.prefix === "Dr." && c.jobTitle === "Architect", `the name and work go together ${JSON.stringify({ n: c.nickname, m: c.middleName })}`);
+ok(c.methods?.[0]?.label === "_$!<Mobile>!$_", "a label left alone goes back exactly as it came");
+const kinds = JSON.stringify(c.methods?.slice(6));
+ok(kinds === JSON.stringify([
+ { kind: "related", label: "SPOUSE", value: "Ravi" },
+ { kind: "date", label: "ANNIVERSARY", value: "1604-07-04" },
+ { kind: "im", label: "JABBER", value: "[email protected]" },
+]), `new details in Apple's spelling, a date with no year as 1604 ${kinds}`);
+const crop = (c.photoCrop ?? "").split(",").map(Number);
+ok(c.photoUrl?.startsWith("data:image/jpeg;base64,") && c.photoUrl.length <= 229376, "the picture goes whole, as icloud.com sends it, under its size");
+ok(crop.length === 4 && crop[2] === crop[3] && crop[2] > 0 && crop[0] > 0, `with the square chosen ${c.photoCrop}`);
+ok(sent?.base?.nickname === "Zo", "against the card as the form opened it");
+
+// Taken away again.
+await page.locator(".contact-row", { hasText: "Zoya" }).click();
+await page.getByRole("button", { name: "Edit", exact: true }).click();
+await page.getByRole("button", { name: /photo/ }).first().click();
+const remove = page.getByRole("button", { name: "Delete Photo" });
+ok((await remove.count()) === 1, "a card with a picture offers to delete it");
+await remove.click();
+await page.getByRole("button", { name: "Save" }).click();
+await page.waitForTimeout(300);
+const gone = (await page.evaluate(() => (window.__contactSaves ?? []).at(-1)))?.contact ?? {};
+ok(gone.photoUrl === null && gone.photoCrop === null, "Delete Photo takes it away");
+
+await b.close();
+process.exitCode = failures === 0 ? 0 : 1;
diff --git a/.uiverify/contacts-keys.mjs b/.uiverify/contacts-keys.mjs
index 5053f6e..b8341bc 100644
--- a/.uiverify/contacts-keys.mjs
+++ b/.uiverify/contacts-keys.mjs
@@ -9,12 +9,12 @@ const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });
await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, contactsFixture: true });
const page = await ctx.newPage();
await ctx.addInitScript(autoConfirm);
-await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await page.goto(process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
await openScreen(page, "Contacts");
await page.waitForTimeout(400);
let failures = 0;
const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
-const current = () => page.locator('.contact-row[aria-current="true"] .contact-row-name').allInnerTexts();
+const current = () => page.locator('.contact-row[aria-selected="true"] .contact-row-name').allInnerTexts();
await page.locator(".contact-row", { hasText: "Zoya Ahuja" }).click();
await page.keyboard.press("ArrowDown");
@@ -101,7 +101,7 @@ await big.addInitScript(() => {
wrap(); document.addEventListener("DOMContentLoaded", wrap);
});
const p2 = await big.newPage();
-await p2.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await p2.goto(process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
await openScreen(p2, "Contacts");
await p2.waitForTimeout(800);
ok((await p2.locator(".contact-index button").count()) >= 26, "a long list has the letters down its edge");
@@ -116,7 +116,7 @@ ok(top < 2, `a letter goes straight to its names ${top}`);
await p2.locator(".contact-row").first().click();
const t0 = await p2.evaluate(() => performance.now());
for (let i = 0; i < 10; i++) await p2.keyboard.press("ArrowDown");
-await p2.waitForFunction(() => document.querySelectorAll('.contact-row[aria-current="true"]').length === 1);
+await p2.waitForFunction(() => document.querySelectorAll('.contact-row[aria-selected="true"]').length === 1);
const per = ((await p2.evaluate(() => performance.now())) - t0) / 10;
ok(per < 100, `walking 3000 people stays quick ${per.toFixed(1)} ms a step`);
await b.close();
diff --git a/.uiverify/contacts-labels.mjs b/.uiverify/contacts-labels.mjs
index ab4853e..927b94c 100644
--- a/.uiverify/contacts-labels.mjs
+++ b/.uiverify/contacts-labels.mjs
@@ -8,7 +8,7 @@ const ctx = await b.newContext({ viewport: { width: 1280, height: 820 } });
await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null,
calendarFixture: false, notesFixture: false, contactsFixture: true, driveFixture: false, remindersFixture: false });
const page = await ctx.newPage();
-await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await page.goto(process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
await page.locator(".nav-item", { hasText: "Contacts" }).click();
await page.waitForTimeout(400);
await page.locator(".contact-row", { hasText: "Zoya" }).click();
diff --git a/.uiverify/contacts-lists.mjs b/.uiverify/contacts-lists.mjs
index 444f618..a279bdc 100644
--- a/.uiverify/contacts-lists.mjs
+++ b/.uiverify/contacts-lists.mjs
@@ -9,7 +9,7 @@ const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });
await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, contactsFixture: true });
const page = await ctx.newPage();
await ctx.addInitScript(autoConfirm);
-await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await page.goto(process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
await openScreen(page, "Contacts");
await page.waitForTimeout(400);
diff --git a/.uiverify/contacts-merge.mjs b/.uiverify/contacts-merge.mjs
new file mode 100644
index 0000000..5557cea
--- /dev/null
+++ b/.uiverify/contacts-merge.mjs
@@ -0,0 +1,67 @@
+// Duplicate cards, as the iPhone finds them: a quiet "Duplicates Found" at the top of the
+// list, each person with what their cards share, one press to merge — nothing lost — and
+// Undo until iCloud has it.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub } from "./stub.mjs";
+
+const b = await engine.launch();
+const ctx = await b.newContext({ viewport: { width: 1280, height: 820 } });
+await ctx.addInitScript(() => {
+ window.__contactsExtra = [
+ { guid: "c5", firstName: "Zoya", lastName: null, company: null, isCompany: false, birthday: null,
+ notes: "Prefers WhatsApp", etag: null,
+ methods: [{ kind: "phone", label: null, value: "090000 00001" }, { kind: "email", label: "WORK", value: "[email protected]" }] },
+ { guid: "c6", firstName: "Ravi", lastName: "Nair", company: null, isCompany: false, birthday: null, notes: null, etag: null,
+ methods: [{ kind: "email", label: "HOME", value: "[email protected]" }] },
+ { guid: "c7", firstName: "Ravi", lastName: "Nair", company: null, isCompany: false, birthday: null, notes: null, etag: null,
+ methods: [{ kind: "phone", label: "MOBILE", value: "+91 98000 00007" }] },
+ ];
+});
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, contactsFixture: true });
+const page = await ctx.newPage();
+await page.goto(process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
+await page.locator(".nav-item", { hasText: "Contacts" }).click();
+await page.waitForTimeout(400);
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+const rows = () => page.locator(".contact-row").count();
+
+const banner = page.locator(".dupes-banner");
+ok((await banner.innerText()).replace(/\s+/g, " ").includes("Duplicates Found 2 people have more than one card"), `the list says so, quietly ${await banner.innerText()}`);
+ok((await rows()) === 7, "every card is in the list until merged");
+await banner.click();
+await page.waitForTimeout(200);
+const view = (await page.locator(".dupes").innerText()).replace(/\s+/g, " ");
+ok(/Zoya Ahuja 2 cards\. Same phone number\./.test(view), `Zoya's cards share a number ${view.slice(0, 220)}`);
+ok(/Ravi Nair 2 cards\. Same name\./.test(view), "Ravi's cards share a name");
+ok(view.includes("Merge All"), "and all of them can be merged at once");
+
+await page.getByRole("button", { name: "Merge Zoya Ahuja" }).click();
+await page.waitForTimeout(300);
+ok(JSON.stringify(await page.evaluate(() => window.__merges?.at(-1))) === JSON.stringify({ guids: ["c1", "c5"] }), "the merge names both cards");
+ok((await rows()) === 6, "one card where there were two, at once");
+const toastText = await page.locator(".toast").last().innerText();
+ok(/Merged 2 cards into one for Zoya Ahuja\./.test(toastText) && /Undo/.test(toastText), `said, with Undo ${toastText}`);
+ok((await page.locator(".dupes-group").count()) === 1, "the view goes on with the people left");
+
+await page.locator(".toast").getByRole("button", { name: "Undo" }).click();
+await page.waitForTimeout(300);
+ok(JSON.stringify(await page.evaluate(() => window.__mergeUndos?.at(-1))) === JSON.stringify({ kept: "c1" }), "Undo takes the merge back");
+ok((await rows()) === 7, "and both cards are back");
+ok((await page.locator(".dupes-group").count()) === 2, "found again as duplicates");
+
+await page.getByRole("button", { name: "Merge All" }).click();
+await page.waitForTimeout(400);
+ok((await rows()) === 5, "Merge All makes each person one card");
+ok((await page.locator(".dupes-banner").count()) === 0, "and the list stops saying so");
+const card = (await page.locator(".contact-detail").innerText()).replace(/\s+/g, " ");
+ok(/zoya@studio\.example/.test(card) && /Prefers WhatsApp/.test(card), `the kept card holds what the other had ${card.slice(0, 160)}`);
+
+// Once iCloud has it, it stays merged, and the window says so.
+await page.evaluate(() => { window.__mergeSent = true; });
+await page.locator(".toast").getByRole("button", { name: "Undo" }).click();
+await page.waitForTimeout(300);
+ok(/iCloud already has this merge/.test(await page.locator(".toast").last().innerText()), "an Undo too late says why");
+await page.screenshot({ path: process.env.SHOT ?? "/dev/null" }).catch(() => {});
+await b.close();
+process.exitCode = failures === 0 ? 0 : 1;
diff --git a/.uiverify/contacts-order.mjs b/.uiverify/contacts-order.mjs
index 05ad56a..2c05ade 100644
--- a/.uiverify/contacts-order.mjs
+++ b/.uiverify/contacts-order.mjs
@@ -6,7 +6,7 @@ const b = await engine.launch();
const ctx = await b.newContext({ viewport: { width: 1200, height: 800 } });
await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, contactsFixture: true });
const page = await ctx.newPage();
-await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await page.goto(process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
await openScreen(page, "Contacts");
await page.waitForTimeout(400);
const seen = await page.locator(".contact-rows > li").allInnerTexts();
diff --git a/.uiverify/contacts-select.mjs b/.uiverify/contacts-select.mjs
index d07140e..f8b6433 100644
--- a/.uiverify/contacts-select.mjs
+++ b/.uiverify/contacts-select.mjs
@@ -7,12 +7,12 @@ const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });
await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, contactsFixture: true });
const page = await ctx.newPage();
await ctx.addInitScript(autoConfirm);
-await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await page.goto(process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
await openScreen(page, "Contacts");
await page.waitForTimeout(400);
let failures = 0;
const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
-const chosen = () => page.locator('.contact-row[aria-current="true"] .contact-row-name').allInnerTexts();
+const chosen = () => page.locator('.contact-row[aria-selected="true"] .contact-row-name').allInnerTexts();
const heading = () => page.locator(".contact-many h2").innerText().catch(() => "");
await page.locator(".contact-row", { hasText: "Zoya Ahuja" }).click();
diff --git a/.uiverify/contacts-vcard.mjs b/.uiverify/contacts-vcard.mjs
index 29f3afb..719741f 100644
--- a/.uiverify/contacts-vcard.mjs
+++ b/.uiverify/contacts-vcard.mjs
@@ -7,7 +7,7 @@ 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, contactsFixture: true });
const page = await ctx.newPage();
-await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await page.goto(process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
await openScreen(page, "Contacts");
await page.waitForTimeout(400);
let failures = 0;
diff --git a/.uiverify/drive-keys.mjs b/.uiverify/drive-keys.mjs
index 2590d75..a5c5385 100644
--- a/.uiverify/drive-keys.mjs
+++ b/.uiverify/drive-keys.mjs
@@ -6,7 +6,7 @@ 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, driveFixture: true });
const page = await ctx.newPage();
-await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await page.goto(process.env.BASE ?? process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
await page.locator(".nav-item", { hasText: "Drive" }).click();
await page.waitForTimeout(400);
let failures = 0;
diff --git a/.uiverify/drive-watch.mjs b/.uiverify/drive-watch.mjs
index 659bb67..0793f2f 100644
--- a/.uiverify/drive-watch.mjs
+++ b/.uiverify/drive-watch.mjs
@@ -55,5 +55,16 @@ await page.waitForTimeout(10_600);
ok((await page.evaluate(() => window.__checks)) === during, "no check while a rename is on its way");
ok((await names()).some((n) => n.startsWith("Downloads 2")), "and the new name stays on screen meanwhile");
+// The window open but not in front (behind another, on another workspace): no timed checks —
+// and focus coming back checks at once.
+await page.waitForTimeout(2500); // the rename's answer lands
+await page.evaluate(() => { document.hasFocus = () => false; });
+const away = await page.evaluate(() => window.__checks);
+await page.waitForTimeout(10_600);
+ok((await page.evaluate(() => window.__checks)) === away, "no timed check while the window is in the background");
+await page.evaluate(() => { document.hasFocus = () => true; window.dispatchEvent(new Event("focus")); });
+await page.waitForTimeout(300);
+ok((await page.evaluate(() => window.__checks)) > away, "and one at once when it comes to the front");
+
await b.close();
if (failures) process.exitCode = 1;
diff --git a/.uiverify/look-reminder.mjs b/.uiverify/look-reminder.mjs
index 5ec8fbf..a5c9c93 100644
--- a/.uiverify/look-reminder.mjs
+++ b/.uiverify/look-reminder.mjs
@@ -5,7 +5,7 @@ const b = await engine.launch();
const ctx = await b.newContext({ viewport: { width: 1300, height: 820 }, colorScheme: "dark" });
await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, remindersFixture: true });
const p = await ctx.newPage();
-await p.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await p.goto(process.env.BASE ?? "http://localhost:4173", { waitUntil: "networkidle" });
await openScreen(p, "Reminders");
await p.locator(".rx-list", { hasText: "GYM" }).click();
await p.waitForTimeout(300);
diff --git a/.uiverify/notes-attach-feedback.mjs b/.uiverify/notes-attach-feedback.mjs
new file mode 100644
index 0000000..efde334
--- /dev/null
+++ b/.uiverify/notes-attach-feedback.mjs
@@ -0,0 +1,46 @@
+// Adding a file to a note never looks stuck: at once a card shows the picture and its name with
+// "Adding to the note", the note waits under it (so nothing typed meanwhile is lost), and when
+// Apple has it the card goes and the note is editable again.
+//
+// BASE=http://localhost:4173 ENGINE=webkit node .uiverify/notes-attach-feedback.mjs
+import { engine, engineName } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const BASE = process.env.BASE ?? "http://localhost:4173";
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${engineName} ${m}`); if (!p) failures++; };
+
+const ctx = await b.newContext({ viewport: { width: 1300, height: 850 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, notesFixture: true });
+await ctx.addInitScript(() => { window.__attachOn = true; window.__pick = "/home/someone/Pictures/beach.jpg"; window.__attachDelay = 1500; });
+const page = await ctx.newPage();
+page.on("pageerror", (e) => ok(false, `page error: ${e.message}`));
+await page.goto(BASE, { waitUntil: "networkidle" });
+await openScreen(page, "Notes");
+await page.locator(".note-row", { hasText: "Curtains" }).click();
+await page.locator(".note-rich .nf-p", { hasText: "Washing Machine cover" }).waitFor();
+
+const t0 = Date.now();
+await page.getByRole("button", { name: "Add a picture or file" }).click();
+const card = page.locator(".note-adding-card");
+await card.waitFor({ timeout: 1000 });
+ok(Date.now() - t0 < 800, `the card is there at once (${Date.now() - t0} ms)`);
+ok((await card.innerText()).includes("beach.jpg") && (await card.innerText()).includes("Adding to the note"), "it names the file and says it is being added");
+await page.locator(".note-adding-thumb[src^='blob:']").waitFor({ timeout: 1000 });
+ok(true, "its picture shows while it uploads");
+const covered = await page.evaluate(() => {
+ const r = document.querySelector(".note-rich")?.getBoundingClientRect();
+ const top = r && document.elementFromPoint(r.left + 20, r.top + 20);
+ return !!top?.closest(".note-adding");
+});
+ok(covered, "the note waits under it, so nothing is typed into it meanwhile");
+
+await card.waitFor({ state: "detached", timeout: 5000 });
+ok((await page.locator(".note-adding").count()) === 0, "when Apple has it, the card goes");
+const sent = await page.evaluate(() => window.__attaches?.length ?? 0);
+ok(sent === 1, "the file was sent once");
+const editable = await page.locator(".note-rich [contenteditable='true'], .note-rich[contenteditable='true']").count();
+ok(editable > 0, "and the note is editable again");
+
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/notes-attachments.mjs b/.uiverify/notes-attachments.mjs
new file mode 100644
index 0000000..7add784
--- /dev/null
+++ b/.uiverify/notes-attachments.mjs
@@ -0,0 +1,60 @@
+// A note's pictures and files shown as Notes shows them: a picture inline at its own
+// proportions — its place held at that shape before a byte of it arrives — a film or PDF as
+// Apple's rendering of it, any other file as a card with its kind, name and size that opens on
+// a click. One whose lookup fails is asked about again, never left a blank gap.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+
+const PNG = Buffer.from(
+ "iVBORw0KGgoAAAANSUhEUgAAAAIAAAADCAIAAAA2iEnWAAAAFklEQVR4nGP4z8DAwMDAxMDAwMAAAA8bAQPsc2MxAAAAAElFTkSuQmCC",
+ "base64",
+);
+const b = await engine.launch();
+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });
+await ctx.addInitScript(() => {
+ window.__attachNote = true;
+ window.__picBase = "http://pics.test";
+ // The film's lookup fails twice before it answers; the pictures arrive slowly.
+ window.__flakyInfo = { A3: 2 };
+});
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, notesFixture: true });
+let release;
+const held = new Promise((r) => { release = r; });
+await ctx.route("http://pics.test/**", async (route) => {
+ await held;
+ await route.fulfill({ status: 200, contentType: "image/png", body: PNG });
+});
+const page = await ctx.newPage();
+await page.goto(process.env.BASE ?? "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: "Attachments" }).first().click();
+await page.waitForSelector(".nf-table");
+await page.waitForTimeout(500);
+
+// Pictures not yet arrived already hold their place at their own shape, no wider than the note.
+const boxes = await page.locator(".note-rich .nf-attachment.is-image img").evaluateAll((imgs) =>
+ imgs.map((i) => { const r = i.getBoundingClientRect(); return [Math.round(r.width), Math.round(r.height), i.complete && i.naturalWidth > 0]; }));
+ok(boxes.length === 4 && boxes.every(([w, h, done]) => !done && w > 100 && h > 100 && w <= 640),
+ `a picture holds its place at its proportions before it arrives ${JSON.stringify(boxes)}`);
+const portrait = boxes.find(([w, h]) => h > w);
+ok(portrait && Math.abs(portrait[0] / portrait[1] - 3024 / 4032) < 0.02, "a portrait picture is drawn portrait");
+release();
+await page.waitForTimeout(400);
+
+// The film whose lookup failed: a frame holds its place, then it is drawn once asked again.
+const film = page.locator(".nf-doc.is-video");
+const pendingNow = await page.evaluate(() => [...document.querySelectorAll(".note-rich .nf-attachment.is-pending")].map((a) => Math.round(a.getBoundingClientRect().height)));
+ok((await film.count()) === 1 || (pendingNow.length === 1 && pendingNow[0] > 20), `an attachment not yet known holds its place, never a blank gap ${JSON.stringify(pendingNow)}`);
+await film.waitFor({ timeout: 15000 }).catch(() => {});
+ok((await film.count()) === 1, "an attachment whose lookup failed is asked about again and drawn");
+
+// A file opens on a click.
+await page.locator(".nf-file", { hasText: "servers.json" }).click();
+await page.waitForTimeout(150);
+ok(JSON.stringify(await page.evaluate(() => window.__opened)) === JSON.stringify(["A2"]), "clicking a file card opens it");
+ok((await page.evaluate(() => (window.__noteSaves ?? []).length)) === 0, "and the note is left alone");
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/notes-compose.mjs b/.uiverify/notes-compose.mjs
index a88f52d..a9deaea 100644
--- a/.uiverify/notes-compose.mjs
+++ b/.uiverify/notes-compose.mjs
@@ -55,7 +55,7 @@ await ctx.addInitScript(() => {
});
const page = await ctx.newPage();
-await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await page.goto(process.env.BASE ?? "http://localhost:4173", { waitUntil: "networkidle" });
await page.locator(".nav-item", { hasText: "Notes" }).click();
await page.waitForTimeout(300);
diff --git a/.uiverify/notes-delete.mjs b/.uiverify/notes-delete.mjs
index e8a91e1..ae70358 100644
--- a/.uiverify/notes-delete.mjs
+++ b/.uiverify/notes-delete.mjs
@@ -6,14 +6,14 @@ 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, notesFixture: true });
const page = await ctx.newPage();
-await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await page.goto(process.env.BASE ?? process.env.URL ?? "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++; };
const titles = () => page.locator(".note-row .note-row-title, .note-row strong").allInnerTexts();
const rows = page.locator(".note-row");
-const openTitle = () => page.locator(".note-row[aria-current='true'], .note-row.is-open, .note-row[aria-selected='true']").first().innerText();
+const openTitle = () => page.locator(".note-row.is-open, .note-row[aria-selected='true']").first().innerText();
await page.evaluate(() => { window.__slowDelete = 1500; });
const before = await rows.allInnerTexts();
diff --git a/.uiverify/notes-instant.mjs b/.uiverify/notes-instant.mjs
index 76511cc..33e8907 100644
--- a/.uiverify/notes-instant.mjs
+++ b/.uiverify/notes-instant.mjs
@@ -19,7 +19,7 @@ await ctx.addInitScript(() => {
wrap(); document.addEventListener("DOMContentLoaded", wrap);
});
const page = await ctx.newPage();
-await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await page.goto(process.env.BASE ?? "http://localhost:4173", { waitUntil: "networkidle" });
await openScreen(page, "Notes");
await page.locator(".note-row", { hasText: "Curtains" }).click();
await page.waitForTimeout(300);
diff --git a/.uiverify/notes-keys.mjs b/.uiverify/notes-keys.mjs
index 97eb84e..315e161 100644
--- a/.uiverify/notes-keys.mjs
+++ b/.uiverify/notes-keys.mjs
@@ -23,7 +23,7 @@ async function open(setup = () => {}) {
await page.waitForTimeout(500);
return { ctx, page };
}
-const current = (page) => page.evaluate(() => document.querySelector('.note-row[aria-current="true"] .note-row-name')?.textContent ?? null);
+const current = (page) => page.evaluate(() => document.querySelector('.note-row[aria-selected="true"] .note-row-name')?.textContent ?? null);
const focusIn = (page, sel) => page.evaluate((s) => Boolean(document.activeElement?.closest(s)), sel);
{
diff --git a/.uiverify/notes-media.mjs b/.uiverify/notes-media.mjs
index 88c9626..1469e2d 100644
--- a/.uiverify/notes-media.mjs
+++ b/.uiverify/notes-media.mjs
@@ -8,7 +8,7 @@ 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 page.goto(process.env.BASE ?? "http://localhost:4173", { waitUntil: "networkidle" });
await openScreen(page, "Notes");
await page.waitForTimeout(400);
let failures = 0;
diff --git a/.uiverify/notes-model.test.mjs b/.uiverify/notes-model.test.mjs
index c43a626..c6c417e 100644
--- a/.uiverify/notes-model.test.mjs
+++ b/.uiverify/notes-model.test.mjs
@@ -38,3 +38,37 @@ test("splitting a note into title and the rest loses nothing", () => {
assert.equal(joinTitle(title, rest, text.includes("\n")), text, JSON.stringify(text));
}
});
+
+test("sorted by date created, the groups follow when each note was made", () => {
+ const n = (guid, created, modified) => ({ ...note(guid, modified), createdAt: created });
+ const sections = groupNotes([n("made-today", at(2026, 8, 30), at(2026, 8, 30)), n("made-in-aug", at(2026, 7, 2), at(2026, 8, 30))],
+ now, { by: "created", groupByDate: true });
+ assert.deepEqual(sections.map((s) => [s.key, s.notes.map((x) => x.guid)]), [["today", ["made-today"]], ["m7", ["made-in-aug"]]]);
+});
+
+test("sorted by title: A to Z in one run, numbers in number order, pinned still first", () => {
+ const sections = groupNotes([note("banana", at(2026, 8, 1)), note("Apple", at(2026, 8, 2)), note("item 10", at(2026, 8, 3)),
+ note("item 9", at(2026, 8, 4)), note("zed", at(2026, 8, 5), true)], now, { by: "title", groupByDate: true });
+ assert.deepEqual(sections.map((s) => [s.key, s.heading, s.notes.map((x) => x.guid)]), [
+ ["pinned", "Pinned", ["zed"]], ["notes", "Notes", ["Apple", "banana", "item 9", "item 10"]],
+ ]);
+});
+
+test("not grouped by date: one run newest first, with no heading when nothing is pinned", () => {
+ const sections = groupNotes([note("old", at(2025, 1, 1)), note("new", at(2026, 8, 30))], now, { by: "edited", groupByDate: false });
+ assert.deepEqual(sections.map((s) => [s.heading, s.notes.map((x) => x.guid)]), [["", ["new", "old"]]]);
+});
+
+test("a note with no date comes last, under Earlier, whatever the order", () => {
+ const sections = groupNotes([note("nodate", null), note("today", at(2026, 8, 30))], now, { by: "created", groupByDate: true });
+ assert.deepEqual(sections.map((s) => s.key), ["undated"].length ? sections.map((s) => s.key) : []);
+ assert.equal(sections.at(-1).key, "undated");
+});
+
+test("every note appears exactly once, in every order", () => {
+ const all = [note("a", at(2026, 8, 30)), note("b", null), note("c", at(2025, 1, 1), true), note("d", at(2026, 6, 1))];
+ for (const by of ["edited", "created", "title"]) for (const groupByDate of [true, false]) {
+ const seen = groupNotes(all, now, { by, groupByDate }).flatMap((s) => s.notes.map((n) => n.guid)).sort();
+ assert.deepEqual(seen, ["a", "b", "c", "d"], `${by} ${groupByDate}`);
+ }
+});
diff --git a/.uiverify/notes-move-checked.mjs b/.uiverify/notes-move-checked.mjs
new file mode 100644
index 0000000..c63bcf8
--- /dev/null
+++ b/.uiverify/notes-move-checked.mjs
@@ -0,0 +1,73 @@
+// Move Checked Items to the Bottom: off, a tick only ticks; on, a ticked item goes to the end
+// of its own checklist and an unticked one back above the ticked — one edit, the text saved
+// whole, nothing else in the note touched.
+//
+// BASE=http://localhost:4173 ENGINE=webkit node .uiverify/notes-move-checked.mjs
+import { engine, engineName } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const BASE = process.env.BASE ?? "http://localhost:4173";
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${engineName} ${m}`); if (!p) failures++; };
+
+async function noteWithList(on) {
+ const ctx = await b.newContext({ viewport: { width: 1300, height: 850 } });
+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, notesFixture: true });
+ await ctx.addInitScript((v) => { try { localStorage.setItem("notes.moveChecked", v); } catch {} }, on ? "1" : "0");
+ const page = await ctx.newPage();
+ page.on("pageerror", (e) => ok(false, `page error: ${e.message}`));
+ await page.goto(BASE, { waitUntil: "networkidle" });
+ await openScreen(page, "Notes");
+ await page.locator(".note-row", { hasText: "Curtains" }).click();
+ await page.locator(".note-rich .nf-p", { hasText: "Washing Machine cover" }).waitFor();
+ await page.locator(".note-rich .nf-p").last().click();
+ await page.keyboard.press("End");
+ await page.waitForTimeout(150);
+ await page.keyboard.press("Enter");
+ await page.keyboard.press("Enter");
+ await page.keyboard.type("- ");
+ await page.keyboard.type("[ ] apples");
+ for (const item of ["bread", "cheese"]) { await page.keyboard.press("Enter"); await page.keyboard.type(item); }
+ await page.waitForTimeout(1300);
+ return { ctx, page };
+}
+// The three items this suite made (the note has a checklist line of its own, earlier on).
+const items = (page) => page.locator('.note-rich .nf-p[data-style="103"]').evaluateAll((ps) =>
+ ps.filter((p) => ["apples", "bread", "cheese"].includes(p.textContent)).map((p) => `${p.dataset.checked === "true" ? "x" : " "} ${p.textContent}`));
+const tick = async (page, name) => {
+ const line = page.locator('.note-rich .nf-p[data-style="103"]', { hasText: name });
+ const box = await line.boundingBox();
+ await page.mouse.click(box.x + 6, box.y + box.height / 2);
+ await page.waitForTimeout(1300);
+};
+const lastSave = (page) => page.evaluate(() => window.__noteSaves?.at(-1)?.body ?? "");
+
+// Off (the default): a tick only ticks.
+{
+ const { ctx, page } = await noteWithList(false);
+ await tick(page, "apples");
+ ok(JSON.stringify(await items(page)) === JSON.stringify(["x apples", " bread", " cheese"]), `off: ticked in place ${JSON.stringify(await items(page))}`);
+ await ctx.close();
+}
+
+// On: to the bottom, and back.
+{
+ const { ctx, page } = await noteWithList(true);
+ const before = await lastSave(page);
+ await tick(page, "apples");
+ ok(JSON.stringify(await items(page)) === JSON.stringify([" bread", " cheese", "x apples"]), `on: a ticked item goes to the end of its list ${JSON.stringify(await items(page))}`);
+ const body = await lastSave(page);
+ ok(body.endsWith("bread\ncheese\napples") && body.startsWith(before.slice(0, before.lastIndexOf("apples"))), "the saved text has it moved, the rest of the note as it was");
+ await tick(page, "bread");
+ ok(JSON.stringify(await items(page)) === JSON.stringify([" cheese", "x apples", "x bread"]), `a second tick goes below the first ${JSON.stringify(await items(page))}`);
+ await tick(page, "apples");
+ ok(JSON.stringify(await items(page)) === JSON.stringify([" cheese", " apples", "x bread"]), `unticked, it comes back above the ticked ${JSON.stringify(await items(page))}`);
+ ok(await page.locator(".note-rich .nf-p", { hasText: "Washing Machine cover" }).count() === 1, "the note's other lines are untouched");
+ await page.keyboard.press("Control+z");
+ await page.waitForTimeout(300);
+ ok(JSON.stringify(await items(page)) === JSON.stringify([" cheese", "x apples", "x bread"]), `one undo puts the tick and the move back together ${JSON.stringify(await items(page))}`);
+ await ctx.close();
+}
+
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/notes-open-quiet.mjs b/.uiverify/notes-open-quiet.mjs
new file mode 100644
index 0000000..d9d7ab5
--- /dev/null
+++ b/.uiverify/notes-open-quiet.mjs
@@ -0,0 +1,108 @@
+// Opening a note is not an edit. A note of pictures, files, a film, a recording and a table —
+// with Apple's runs in pieces, as a phone leaves them — is opened, looked at, scrolled, clicked
+// into, its pictures and table clicked, the cursor moved, the note left and opened again: no
+// save may be queued. One written then would rewrite the note's formatting on iCloud without
+// anyone touching it (it happened, on his "Attachments" note). A real edit still saves.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+
+// A real picture to draw, served where the stub's routes point.
+const PNG = Buffer.from(
+ "iVBORw0KGgoAAAANSUhEUgAAAAIAAAADCAIAAAA2iEnWAAAAFklEQVR4nGP4z8DAwMDAxMDAwMAAAA8bAQPsc2MxAAAAAElFTkSuQmCC",
+ "base64",
+);
+const b = await engine.launch();
+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });
+await ctx.addInitScript(() => {
+ window.__attachNote = true;
+ window.__picBase = "http://pics.test";
+});
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, notesFixture: true });
+await ctx.route("http://pics.test/**", (route) => route.fulfill({ status: 200, contentType: "image/png", body: PNG }));
+const page = await ctx.newPage();
+await page.goto(process.env.BASE ?? "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++; };
+const saves = () => page.evaluate(() => (window.__noteSaves ?? []).length);
+
+await page.locator(".note-row", { hasText: "Attachments" }).first().click();
+await page.waitForSelector(".nf-table");
+await page.waitForTimeout(1500);
+ok((await saves()) === 0, "opening a note with attachments and a table queues no save");
+
+// Looking at it: scrolled, clicked into its text, the cursor moved, a picture and the table
+// clicked, a word selected — nothing typed.
+const editor = page.locator(".note-rich");
+await editor.hover();
+await page.mouse.wheel(0, 600);
+await page.waitForTimeout(200);
+await page.mouse.wheel(0, -600);
+await editor.locator("p").first().click();
+for (const k of ["End", "ArrowDown", "ArrowDown", "ArrowDown", "ArrowUp", "Home", "Shift+ArrowRight", "ArrowLeft"]) await page.keyboard.press(k);
+await page.locator(".nf-table td").first().click();
+await page.locator(".note-rich p", { hasText: "A few words" }).dblclick();
+const pic = page.locator(".nf-image").first();
+if (await pic.count()) {
+ await pic.click();
+ await page.waitForTimeout(200);
+ await page.keyboard.press("Escape");
+}
+await page.waitForTimeout(1500);
+ok((await saves()) === 0, `looking, scrolling, clicking and selecting queue no save ${JSON.stringify(await page.evaluate(() => window.__noteSaves?.[0]?.runs?.slice(0, 3)))}`);
+
+// A press that drifts a few pixels is a drag: of the table, a file card, a picture, or of
+// selected text — let go where it began. That queued the save he found (the same text, the
+// runs merged), and a table so dragged came back as its cells' text, the table gone.
+const nudge = async (box) => {
+ await page.mouse.move(box.x + 6, box.y + 6);
+ await page.mouse.down();
+ await page.mouse.move(box.x + 10, box.y + 8, { steps: 5 });
+ await page.mouse.move(box.x + 7, box.y + 6, { steps: 4 });
+ await page.mouse.up();
+};
+for (const sel of [".nf-table td", ".nf-file", ".nf-attachment.is-image img"]) {
+ const box = await page.locator(sel).first().boundingBox();
+ await page.mouse.click(box.x + 6, box.y + 6);
+ await nudge(box);
+}
+const words = page.locator(".note-rich p", { hasText: "A few words" });
+await words.dblclick({ position: { x: 30, y: 8 } });
+await nudge(await words.boundingBox());
+await page.waitForTimeout(1500);
+ok((await saves()) === 0 && (await page.locator(".nf-table").count()) === 1,
+ `a drag let go where it began queues no save, and the table stays a table ${JSON.stringify(await page.evaluate(() => window.__noteSaves?.[0]?.body))}`);
+
+// Left and opened again.
+await page.locator(".note-row").filter({ hasNotText: "Attachments" }).first().click();
+await page.waitForTimeout(400);
+await page.locator(".note-row", { hasText: "Attachments" }).first().click();
+await page.waitForSelector(".nf-table");
+await page.waitForTimeout(1500);
+ok((await saves()) === 0, "leaving the note and opening it again queues no save");
+
+// Attachments are shown: pictures as pictures, files as cards with their name and size.
+const shown = await page.evaluate(() => ({
+ images: document.querySelectorAll(".note-rich .nf-attachment.is-image img").length,
+ cards: [...document.querySelectorAll(".note-rich .nf-file")].map((c) => c.textContent),
+ docs: document.querySelectorAll(".note-rich .nf-doc").length,
+ blank: [...document.querySelectorAll(".note-rich .nf-attachment")].filter((a) => a.getBoundingClientRect().height < 8).length,
+}));
+ok(shown.images === 4 && shown.docs === 2 && shown.cards.length === 2 && shown.blank === 0,
+ `every attachment is drawn — 4 pictures, 2 previews, 2 file cards, none blank ${JSON.stringify(shown)}`);
+ok(shown.cards.some((c) => /servers\.json/.test(c) && /KB/.test(c)) && shown.cards.some((c) => /recording\.m4a/.test(c)),
+ "a file card names the file and its size");
+
+// A real edit still saves — and keeps every untouched run as Apple has it.
+await page.locator(".note-rich p", { hasText: "A few words" }).click();
+await page.keyboard.press("End");
+await page.keyboard.type("!");
+await page.waitForTimeout(1500);
+const saved = await page.evaluate(() => window.__noteSaves ?? []);
+ok(saved.length === 1 && saved[0].body.includes("!"), `a typed key saves once ${saved.length}`);
+const s = saved[0];
+const ids = (rs) => (rs ?? []).filter((r) => r.attachment).map((r) => r.attachment).join(",");
+ok(s && ids(s.runs) === ids(s.baseRuns ?? s.base_runs), "every attachment keeps its place in the saved runs");
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/notes-pin.mjs b/.uiverify/notes-pin.mjs
index f9e7eb0..e23d5a0 100644
--- a/.uiverify/notes-pin.mjs
+++ b/.uiverify/notes-pin.mjs
@@ -7,7 +7,7 @@ const ctx = await b.newContext({ viewport: { width: 1280, height: 820 } });
await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null,
calendarFixture: false, notesFixture: true, contactsFixture: false, driveFixture: false, remindersFixture: false });
const page = await ctx.newPage();
-await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await page.goto(process.env.BASE ?? process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
await page.locator(".nav-item", { hasText: "Notes" }).click();
await page.waitForTimeout(400);
diff --git a/.uiverify/notes-rich.test.mjs b/.uiverify/notes-rich.test.mjs
index adf7c64..a4c59bc 100644
--- a/.uiverify/notes-rich.test.mjs
+++ b/.uiverify/notes-rich.test.mjs
@@ -45,3 +45,40 @@ test("two edits merge as Notes merges them — nothing typed is lost", () => {
assert.equal(mergeEdits("milk\neggs\nbread\njam", "milk!\neggs\nbread\njam?", "milk\neggs\nbutter\njam"), "milk!\neggs\nbutter\njam?");
assert.equal(mergeEdits("one two three", "one three", "one two three!"), "one three!");
});
+
+import { checklistMove } from "../src/screens/notes/rich.ts";
+// A note of lines, each "[ ] text", "[x] text", " [ ] nested", or plain text.
+const listDoc = (lines) => {
+ const text = lines.map((l) => l.replace(/^\s*\[[ x]\] /, "")).join("\n");
+ const runs = lines.map((l, i) => {
+ const m = /^(\s*)\[([ x])\] /.exec(l);
+ const len = l.replace(/^\s*\[[ x]\] /, "").length + (i < lines.length - 1 ? 1 : 0);
+ return m ? r(len, { style: STYLE.checklist, checked: m[2] === "x", indent: m[1].length / 2 }) : r(len);
+ });
+ return toDoc(text, runs);
+};
+
+test("ticked, an item goes to the end of its own checklist, nested items with it", () => {
+ const doc = listDoc(["Title", "[x] a", "[ ] b", " [ ] b1", "[ ] c", "after"]);
+ assert.deepEqual(checklistMove(doc, 1, true), { from: 1, to: 2, before: 5 });
+ assert.deepEqual(checklistMove(doc, 2, true), { from: 2, to: 4, before: 5 });
+});
+
+test("ticked, the last item already at the end stays; a nested item never moves on its own", () => {
+ const doc = listDoc(["[ ] a", "[ ] b", " [ ] b1"]);
+ assert.equal(checklistMove(doc, 1, true), null);
+ assert.equal(checklistMove(doc, 2, true), null);
+});
+
+test("unticked, an item goes back above the ticked ones", () => {
+ const doc = listDoc(["[ ] a", "[x] b", "[x] c", "[ ] d"]);
+ assert.deepEqual(checklistMove(doc, 2, false), { from: 2, to: 3, before: 1 });
+ assert.equal(checklistMove(doc, 0, false), null, "already above them");
+});
+
+test("only checklist lines move, and only within their own run", () => {
+ const doc = listDoc(["[ ] a", "plain", "[ ] x", "[ ] y"]);
+ assert.equal(checklistMove(doc, 1, true), null, "a plain line is not an item");
+ assert.equal(checklistMove(doc, 0, true), null, "alone in its run, it stays");
+ assert.deepEqual(checklistMove(doc, 2, true), { from: 2, to: 3, before: 4 });
+});
diff --git a/.uiverify/notes-table.mjs b/.uiverify/notes-table.mjs
index 8ced254..66dc686 100644
--- a/.uiverify/notes-table.mjs
+++ b/.uiverify/notes-table.mjs
@@ -8,7 +8,7 @@ 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 page.goto(process.env.BASE ?? process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
await openScreen(page, "Notes");
await page.waitForTimeout(400);
let failures = 0;
@@ -20,7 +20,7 @@ ok(JSON.stringify(grid) === JSON.stringify([["Item", "Qty"], ["Milk", "2"], ["",
// Read-only for now: edits made here reached the iPhone, but Notes there kept conflict copies of
// the note with the text doubled. No cell is offered for typing and no table menu opens.
-ok((await page.locator(".nf-cell-edit").count()) === 0, "no table cell is offered for typing while table writes are off");
+ok((await page.locator(".nf-cell-edit").count()) > 0, "table cells are offered for typing now table writes are on (proven on the iPhone)");
await page.locator(".nf-table tr").nth(1).locator("td").first().click({ button: "right" });
ok((await page.getByRole("menuitem", { name: /Add Row|Delete Row/ }).count()) === 0, "and right-click offers no row or column changes");
await page.keyboard.press("Escape");
@@ -87,11 +87,63 @@ const ctx2 = await b.newContext({ viewport: { width: 1280, height: 800 } });
await ctx2.addInitScript(() => { window.__tableNote = true; window.__unreadTable = true; });
await ctx2.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, notesFixture: true });
const p2 = await ctx2.newPage();
-await p2.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await p2.goto(process.env.BASE ?? process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
await openScreen(p2, "Notes");
await p2.locator(".note-row", { hasText: "Groceries" }).first().click();
await p2.waitForTimeout(600);
ok((await p2.locator(".nf-table-unread").count()) === 1 && (await p2.locator(".nf-file").count()) === 0,
`a table that can't be read says so, and is no file to open ${await p2.locator(".nf-attachment").first().innerText().catch(() => "")}`);
+await ctx2.close();
+
+// At a fractional scale (1.25×, a common laptop setting) the note's column starts between two
+// device pixels. A bordered table then lost its left edge in WebKit and drew its right edge two
+// pixels wide. Read from the pixels: both edges carry ink, the same weight, neither smeared
+// wider than two device pixels; at 1×, 1.5× and 2× each is one crisp column.
+const inkAcross = async (page, scale) => {
+ const r = await page.locator(".nf-table").first().boundingBox();
+ const shot = (await page.screenshot()).toString("base64");
+ return page.evaluate(async ({ b64, r, s }) => {
+ const img = new Image();
+ img.src = `data:image/png;base64,${b64}`;
+ await img.decode();
+ const c = document.createElement("canvas");
+ c.width = img.width; c.height = img.height;
+ const g = c.getContext("2d");
+ g.drawImage(img, 0, 0);
+ const y = Math.round((r.y + r.height * 0.3) * s);
+ const row = g.getImageData(0, y, img.width, 1).data;
+ const dark = (x) => 255 - (row[x * 4] + row[x * 4 + 1] + row[x * 4 + 2]) / 3;
+ const base = dark(Math.floor((r.x + r.width * 0.25) * s));
+ const edge = (at) => {
+ const cols = [];
+ for (let x = Math.floor(at) - 3; x <= Math.floor(at) + 3; x++) cols.push(Math.max(0, Math.round(dark(x) - base)));
+ return { ink: cols.reduce((a, b) => a + b, 0), wide: cols.filter((v) => v > 4).length };
+ };
+ return { left: edge(r.x * s), right: edge((r.x + r.width) * s) };
+ }, { b64: shot, r, s: scale });
+};
+for (const scale of [1, 1.25, 1.5, 2]) {
+ const ctx3 = await b.newContext({ viewport: { width: 1180, height: 800 }, deviceScaleFactor: scale });
+ await ctx3.addInitScript(() => { window.__tableNote = true; });
+ await ctx3.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, notesFixture: true });
+ const p3 = await ctx3.newPage();
+ await p3.goto(process.env.BASE ?? process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
+ await openScreen(p3, "Notes");
+ await p3.locator(".note-row", { hasText: "Groceries" }).first().click();
+ await p3.waitForSelector(".nf-table");
+ await p3.mouse.move(0, 0);
+ const bad = [];
+ for (const width of scale === 1.25 ? [1180, 1183, 1201] : [1180]) {
+ await p3.setViewportSize({ width, height: 800 });
+ await p3.waitForTimeout(120);
+ const { left, right } = await inkAcross(p3, scale);
+ const whole = scale !== 1.25;
+ const fine = left.ink > 10 && right.ink > 10 && Math.abs(left.ink - right.ink) <= Math.max(left.ink, right.ink) * 0.5
+ && left.wide <= (whole ? 1 : 2) && right.wide <= (whole ? 1 : 2);
+ if (!fine) bad.push({ width, left, right });
+ }
+ ok(bad.length === 0, `at ${scale}×, the table's left and right edges are both drawn, the same weight, unsmeared ${JSON.stringify(bad)}`);
+ await ctx3.close();
+}
await b.close();
process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/notes-view-options.mjs b/.uiverify/notes-view-options.mjs
new file mode 100644
index 0000000..7241486
--- /dev/null
+++ b/.uiverify/notes-view-options.mjs
@@ -0,0 +1,58 @@
+// Notes' View Options: sort by Date Edited, Date Created or Title, and Group By Date — the
+// headings follow, every note stays listed once, and the choice is still there after a reload.
+//
+// BASE=http://localhost:4173 ENGINE=webkit node .uiverify/notes-view-options.mjs
+import { engine, engineName } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const BASE = process.env.BASE ?? "http://localhost:4173";
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${engineName} ${m}`); if (!p) failures++; };
+
+const ctx = await b.newContext({ viewport: { width: 1300, height: 850 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, notesFixture: true });
+const page = await ctx.newPage();
+page.on("pageerror", (e) => ok(false, `page error: ${e.message}`));
+await page.goto(BASE, { waitUntil: "networkidle" });
+await openScreen(page, "Notes");
+await page.waitForTimeout(400);
+
+const headings = () => page.locator(".note-rows .notes-section").allInnerTexts();
+const rows = () => page.locator(".note-rows .note-row").count();
+const choose = async (label) => {
+ await page.getByRole("button", { name: "View Options" }).click();
+ await page.getByRole("menuitemcheckbox", { name: label }).click();
+ await page.waitForTimeout(200);
+};
+
+const before = await headings();
+const count = await rows();
+ok(before[0] === "Pinned" && before.length >= 2, `by date edited, Pinned leads and the rest are grouped by date ${JSON.stringify(before)}`);
+
+await page.getByRole("button", { name: "View Options" }).click();
+const items = await page.getByRole("menuitemcheckbox").allInnerTexts();
+ok(["Date Edited", "Date Created", "Title", "Group By Date"].every((l) => items.some((i) => i.includes(l))), `the menu offers every order ${JSON.stringify(items)}`);
+ok((await page.getByRole("menuitemcheckbox", { name: "Date Edited" }).getAttribute("aria-checked")) === "true", "Date Edited is the one checked");
+await page.keyboard.press("Escape");
+
+await choose("Title");
+ok(JSON.stringify(await headings()) === JSON.stringify(["Pinned", "Notes"]), `by title, one run under Pinned ${JSON.stringify(await headings())}`);
+ok((await rows()) === count, "every note is still listed");
+await page.getByRole("button", { name: "View Options" }).click();
+ok((await page.getByRole("menuitemcheckbox", { name: "Group By Date" }).count()) === 0, "Group By Date is not offered for Title, as in Notes");
+await page.keyboard.press("Escape");
+
+await page.reload({ waitUntil: "networkidle" });
+await openScreen(page, "Notes");
+await page.waitForTimeout(400);
+ok(JSON.stringify(await headings()) === JSON.stringify(["Pinned", "Notes"]), "the order is kept after a reload");
+
+await choose("Date Edited");
+await choose("Group By Date");
+ok(JSON.stringify(await headings()) === JSON.stringify(["Pinned", "Notes"]), `not grouped, the dated notes run as one ${JSON.stringify(await headings())}`);
+ok((await rows()) === count, "and every note is still listed");
+await choose("Group By Date");
+ok(JSON.stringify(await headings()) === JSON.stringify(before), "grouping back on restores the date headings");
+
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/outbox-pending.mjs b/.uiverify/outbox-pending.mjs
index 5538dfc..5d059fe 100644
--- a/.uiverify/outbox-pending.mjs
+++ b/.uiverify/outbox-pending.mjs
@@ -14,7 +14,7 @@ await ctx.addInitScript(() => {
};
});
const page = await ctx.newPage();
-await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await page.goto(process.env.BASE ?? process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
await openScreen(page, "Notes");
await page.locator(".note-row", { hasText: "Curtains" }).click();
await page.waitForTimeout(400);
diff --git a/.uiverify/photos-paging.mjs b/.uiverify/photos-paging.mjs
new file mode 100644
index 0000000..4aa7b6e
--- /dev/null
+++ b/.uiverify/photos-paging.mjs
@@ -0,0 +1,151 @@
+// A library of 50,000 photos paged over IPC: the first screen paints from the first page before
+// the index (made slow here) lands; no answer carries more than a page of photos; scrolling
+// fetches the pages ahead, so tiles are there when the grid reaches them; the photos held, the
+// tiles drawn and (in Chromium) the JS heap stay flat from top to bottom; a fling never freezes.
+//
+// URL=http://localhost:4280 node .uiverify/photos-paging.mjs (ENGINE=webkit for WebKit)
+import { engine, engineName } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+
+const N = 50_000;
+const PAGE = 240;
+const KEEP = 2400;
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+
+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });
+await ctx.addInitScript(([n]) => {
+ const P = (i, t) => ({ id: `q${i}`, master: `mq${i}`, takenAt: t, addedAt: t, kind: i % 17 === 4 ? "video" : "image", width: 4032, height: 3024,
+ duration: i % 17 === 4 ? 21 : null, filename: `IMG_${i}.JPG`, size: 2400000, uti: "public.jpeg", favorite: i % 9 === 0, hidden: false,
+ deleted: false, deletedAt: null, subtype: 0, changeTag: null });
+ window.__photos = Array.from({ length: n }, (_, i) => P(i, 1792600000 - i * 3000));
+ window.__indexDelay = 1500;
+ // Every answer the window gets, by command, with how many photos it carried. The stub's own
+ // reads of whole lists (to make an index or a page from) are told apart by depth.
+ window.__calls = [];
+ let inner = 0;
+ const wrap = () => {
+ const real = window.__TAURI_INTERNALS__?.invoke;
+ if (!real || real.__wrapped) return;
+ const w = async (cmd, args, o) => {
+ const mine = inner === 0;
+ if (cmd === "photos_index" || cmd === "photos_page") inner++;
+ try {
+ const out = await real(cmd, args, o);
+ if (mine) window.__calls.push({ cmd, at: performance.now(), n: Array.isArray(out) ? out.length : out?.ids ? -out.ids.length : 0 });
+ return out;
+ } finally {
+ if (cmd === "photos_index" || cmd === "photos_page") inner--;
+ }
+ };
+ w.__wrapped = true;
+ window.__TAURI_INTERNALS__.invoke = w;
+ };
+ wrap();
+ document.addEventListener("DOMContentLoaded", wrap);
+}, [N]);
+const page = await ctx.newPage();
+page.on("pageerror", (e) => ok(false, `page error: ${e.message}`));
+await page.goto(process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
+const cdp = engineName === "chromium" ? await ctx.newCDPSession(page) : null;
+const heap = async () => {
+ if (!cdp) return null;
+ await cdp.send("HeapProfiler.collectGarbage");
+ return (await cdp.send("Runtime.getHeapUsage")).usedSize;
+};
+
+const t0 = Date.now();
+await openScreen(page, "Photos");
+await page.locator(".px-tile").first().waitFor();
+const painted = Date.now() - t0;
+const indexIn = await page.evaluate(() => (window.__indexReads ?? []).length);
+ok(indexIn === 0 || (await page.evaluate(() => !window.__calls.some((c) => c.cmd === "photos_index"))), `the first screen paints from the first page, before the index lands (${painted} ms)`);
+await page.waitForFunction(() => window.__calls.some((c) => c.cmd === "photos_index"), null, { timeout: 8000 }).catch(() => ok(false, "the index is asked for"));
+await page.waitForTimeout(500);
+const calls = await page.evaluate(() => window.__calls);
+const photoCalls = calls.filter((c) => ["photos_list", "photos_page", "photos_get", "photos_search", "photos_in_album"].includes(c.cmd));
+ok(!calls.some((c) => c.cmd === "photos_list"), "the whole list is never asked for");
+ok(photoCalls.every((c) => c.n <= PAGE), `no answer carries more than a page (largest ${Math.max(...photoCalls.map((c) => c.n))})`);
+const height = await page.evaluate(() => document.querySelector(".px-scroll").scrollHeight);
+ok(height > N / 10 * 50, `the grid is laid out for all ${N.toLocaleString()} from the index (${height.toLocaleString()} px)`);
+const heapStart = await heap();
+
+/** Tiles drawn in the window's view, and blocks still waiting for their photos there. */
+const inView = () => page.evaluate(() => {
+ const el = document.querySelector(".px-scroll");
+ const r = el.getBoundingClientRect();
+ const tiles = [...el.querySelectorAll(".px-tile")].filter((t) => { const b = t.getBoundingClientRect(); return b.bottom > r.top && b.top < r.bottom; }).length;
+ return { tiles, drawn: el.querySelectorAll(".px-tile").length };
+});
+
+// Scrolled at a steady 3,000 px/s for a while: pages fetched ahead, so the screen is never bare.
+const run = (speed, ms) => page.evaluate(([speed, ms]) => new Promise((done) => {
+ const el = document.querySelector(".px-scroll");
+ const gaps = [];
+ let bare = 0;
+ let last = performance.now();
+ const start = last;
+ const step = (now) => {
+ gaps.push(now - last);
+ el.scrollTop += (speed * (now - last)) / 1000;
+ last = now;
+ const r = el.getBoundingClientRect();
+ const mid = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2);
+ if (!mid?.closest(".px-tile, .px-month-title")) bare++;
+ if (now - start < ms && el.scrollTop + el.clientHeight < el.scrollHeight - 2) requestAnimationFrame(step);
+ else done({ gaps: gaps.slice(2), bare, frames: gaps.length });
+ };
+ requestAnimationFrame(step);
+}), [speed, ms]);
+const stats = (gaps) => {
+ const s = [...gaps].sort((x, y) => x - y);
+ const q = (p) => s[Math.min(s.length - 1, Math.floor(p * s.length))];
+ return { p50: q(0.5), p95: q(0.95), max: s[s.length - 1] };
+};
+const BOUND = engineName === "chromium" ? 120 : 900;
+const steady = await run(3000, 5000);
+const st = stats(steady.gaps);
+console.log(` steady scroll: ${steady.frames} frames, p50 ${st.p50.toFixed(1)} ms, p95 ${st.p95.toFixed(1)} ms, max ${st.max.toFixed(1)} ms, ${steady.bare} frames with the middle bare`);
+ok(st.max < BOUND, `a steady scroll never freezes (longest frame ${Math.round(st.max)} ms)`);
+ok(steady.bare <= steady.frames * 0.1, `pages land ahead of a steady scroll (${steady.bare} of ${steady.frames} frames bare in the middle)`);
+const fling = await run(9000, 3000);
+const sf = stats(fling.gaps);
+console.log(` fling: p50 ${sf.p50.toFixed(1)} ms, p95 ${sf.p95.toFixed(1)} ms, max ${sf.max.toFixed(1)} ms`);
+ok(sf.max < BOUND, `a fling never freezes (longest frame ${Math.round(sf.max)} ms)`);
+
+// Jumped through the whole library, top to bottom: each place fills in, and what is held stays flat.
+const drawnAt = [];
+for (const at of [0.2, 0.4, 0.6, 0.8, 1]) {
+ await page.evaluate((f) => { const el = document.querySelector(".px-scroll"); el.scrollTop = (el.scrollHeight - el.clientHeight) * f; }, at);
+ await page.waitForFunction(() => {
+ const el = document.querySelector(".px-scroll");
+ const r = el.getBoundingClientRect();
+ return [...el.querySelectorAll(".px-tile")].some((t) => { const b = t.getBoundingClientRect(); return b.bottom > r.top && b.top < r.bottom; });
+ }, null, { timeout: 5000 }).catch(() => {});
+ await page.waitForTimeout(300);
+ const v = await inView();
+ drawnAt.push(v.drawn);
+ ok(v.tiles > 20, `${Math.round(at * 100)}% down, the screen fills in (${v.tiles} tiles in view, ${v.drawn} drawn)`);
+}
+const fetched = await page.evaluate(() => window.__calls.filter((c) => c.cmd === "photos_get").reduce((a, c) => a + c.n, 0));
+ok(fetched > KEEP, `photos fetched as they came near (${fetched.toLocaleString()} in all)`);
+ok(Math.max(...drawnAt) <= KEEP, `tiles drawn stay bounded however far it goes (${drawnAt.join(", ")})`);
+const heapEnd = await heap();
+if (heapStart !== null) {
+ const mb = (x) => (x / 1024 ** 2).toFixed(1);
+ console.log(` JS heap: ${mb(heapStart)} MB at the top, ${mb(heapEnd)} MB at the foot`);
+ ok(heapEnd - heapStart < 25 * 1024 ** 2, `memory stays flat from top to bottom (${mb(heapStart)} → ${mb(heapEnd)} MB)`);
+}
+
+// The last photo opens in the viewer, and steps back across a page boundary.
+await page.locator(".px-tile").last().dblclick();
+await page.locator(".px-viewer, .px-stage").first().waitFor({ timeout: 5000 }).catch(() => {});
+ok(await page.locator(".px-viewer, .px-stage").first().isVisible(), "a photo at the foot of the library opens");
+for (let i = 0; i < 5; i++) await page.keyboard.press("ArrowLeft");
+await page.waitForTimeout(300);
+ok(await page.locator(".px-viewer, .px-stage").first().isVisible(), "and steps on through the photos before it");
+
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/photos-show.mjs b/.uiverify/photos-show.mjs
index d25468e..a03344e 100644
--- a/.uiverify/photos-show.mjs
+++ b/.uiverify/photos-show.mjs
@@ -6,6 +6,14 @@ 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 });
+// Real pictures (a flat colour each), so each photo is fetched and decoded as in the app: the
+// show passes over a picture that cannot be had.
+await ctx.addInitScript(() => { window.__picBase = "http://pics.test"; });
+await ctx.route("http://pics.test/**", (route) => {
+ const id = /pic%2F([^%]+)%2F/.exec(route.request().url())?.[1] ?? "x";
+ const hue = [...id].reduce((h, c) => h + c.charCodeAt(0) * 37, 0) % 360;
+ return route.fulfill({ contentType: "image/svg+xml", body: `<svg xmlns="http://www.w3.org/2000/svg" width="1536" height="1152"><rect width="1536" height="1152" fill="hsl(${hue},60%,50%)"/></svg>` });
+});
const page = await ctx.newPage();
page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });
await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
@@ -24,33 +32,39 @@ const fills = await page.locator(".px-show").evaluate((el) => {
return r.left === 0 && r.top === 0 && Math.round(r.width) === innerWidth && Math.round(r.height) === innerHeight;
});
ok(fills, "it fills the whole window, not a box inside the screen");
-await page.waitForTimeout(4400);
+// Each photo holds 4 s, then dissolves into the next over 0.8 s.
+await page.waitForTimeout(5200);
ok((await count()) === "3 of 5", `and goes on by itself "${await count()}"`);
await page.keyboard.press(" ");
-await page.waitForTimeout(4400);
+await page.waitForTimeout(5200);
ok((await count()) === "3 of 5" && (await page.getByRole("button", { name: "Play" }).count()) === 1, "Space pauses it");
-// A step waits for the next picture to be decoded — never half shown — so a moment passes.
+// A step waits for the next picture to be decoded — never half shown — then dissolves in.
await page.keyboard.press("ArrowRight");
-await page.waitForTimeout(150);
+await page.waitForTimeout(1000);
ok((await count()) === "4 of 5", "the right arrow steps on");
await page.keyboard.press("ArrowLeft");
-await page.waitForTimeout(150);
+await page.waitForTimeout(1000);
await page.keyboard.press("ArrowLeft");
-await page.waitForTimeout(150);
+await page.waitForTimeout(1000);
ok((await count()) === "2 of 5", "and the left back");
// The next dissolves in over the one leaving (drawn frame by frame by the page, never the
-// compositor's), the leaving one still beneath it, then gone.
-await page.keyboard.press("ArrowRight");
-await page.waitForTimeout(250);
-const mid = await page.evaluate(() => {
- const a = document.querySelector(".px-slide:not(.is-leaving)"), l = document.querySelector(".px-slide.is-leaving");
- return { arriving: Number(getComputedStyle(a).opacity), leaving: l ? Number(getComputedStyle(l).opacity) : -1, engine: document.querySelector(".px-show").getAnimations({ subtree: true }).length };
+// compositor's), the leaving one still whole beneath it, then gone.
+const layers = () => page.evaluate(() => {
+ const ls = [...document.querySelectorAll(".px-slide")].sort((a, b) => +b.style.zIndex - +a.style.zIndex);
+ return { arriving: Number(getComputedStyle(ls[0]).opacity), leaving: Number(getComputedStyle(ls[1]).opacity), engine: document.querySelector(".px-show").getAnimations({ subtree: true }).length };
});
-await page.waitForTimeout(900);
-ok(mid.arriving > 0 && mid.arriving < 1 && mid.leaving === 1 && mid.engine === 0 && (await page.locator(".px-slide.is-leaving").count()) === 0,
- `the next dissolves in over the one leaving, none of it the engine's, then the old one goes ${JSON.stringify(mid)}`);
+await page.keyboard.press("ArrowRight");
+let mid = await layers();
+for (let i = 0; i < 40 && !(mid.arriving > 0 && mid.arriving < 1); i++) {
+ await page.waitForTimeout(20);
+ mid = await layers();
+}
+await page.waitForTimeout(1000);
+const after = await layers();
+ok(mid.arriving > 0 && mid.arriving < 1 && mid.leaving > 0.9 && mid.engine === 0 && after.arriving === 1 && after.leaving === 0,
+ `the next dissolves in over the one leaving, none of it the engine's, then the old one goes ${JSON.stringify({ mid, after })}`);
await page.keyboard.press("ArrowLeft");
-await page.waitForTimeout(150);
+await page.waitForTimeout(1000);
await page.keyboard.press("Escape");
await page.waitForTimeout(200);
ok((await page.locator(".px-show").count()) === 0 && (await page.locator(".px-tile").count()) === 5, "Escape ends it, the library as it was");
diff --git a/.uiverify/photos-slideshow.mjs b/.uiverify/photos-slideshow.mjs
new file mode 100644
index 0000000..405494f
--- /dev/null
+++ b/.uiverify/photos-slideshow.mjs
@@ -0,0 +1,172 @@
+// The slideshow, as Photos plays one: each photo whole on black, dissolving into the next with
+// no black or empty frame between them; the next made the size of the screen and decoded before
+// it shows; a video shows its picture, then plays, then the show moves on; Space, the arrows and
+// Escape; reduced motion cuts.
+//
+// The proof of "no black frame" is taken from the screen itself: during each dissolve the page
+// is captured frame after frame and the middle of the screen — where both photos lie — must
+// always show a photo's colour (or a blend of the two), never black.
+import http from "node:http";
+import fs from "node:fs";
+import { createRequire } from "node:module";
+import { engine, engineName } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const { PNG } = createRequire(import.meta.url)("playwright-core/lib/utilsBundle");
+
+const clip = new URL("./clip.webm", import.meta.url);
+const len = fs.statSync(clip).size;
+const films = [];
+const server = http.createServer((req, res) => {
+ films.push(req.url);
+ const m = /bytes=(\d*)-(\d*)/.exec(req.headers.range ?? "");
+ const f = m && m[1] ? +m[1] : 0, l = m && m[2] ? Math.min(+m[2], len - 1) : len - 1;
+ res.writeHead(m ? 206 : 200, { "Content-Type": "video/webm", "Accept-Ranges": "bytes", "Content-Length": l - f + 1, "Content-Range": `bytes ${f}-${l}/${len}` });
+ fs.createReadStream(clip, { start: f, end: l }).pipe(res);
+});
+await new Promise((r) => server.listen(0, "127.0.0.1", r));
+const base = `http://127.0.0.1:${server.address().port}/s3cret`;
+
+// Every photo a flat colour of its own, at the size asked for (4:3, as the stub's photos are).
+const COLOURS = { p1: [220, 40, 40], p2: [40, 180, 60], p3: [40, 80, 220], p4: [230, 200, 30], p5: [200, 60, 200] };
+const asked = [];
+const PICS = "http://pics.test";
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+
+async function open(reduced) {
+ const ctx = await b.newContext({ viewport: { width: 1280, height: 800 }, reducedMotion: reduced ? "reduce" : "no-preference" });
+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });
+ await ctx.addInitScript(([v, pics]) => { window.__videoBase = v; window.__picBase = pics; }, [base, PICS]);
+ await ctx.route(`${PICS}/**`, async (route) => {
+ const path = decodeURIComponent(route.request().url().slice(PICS.length + 1));
+ asked.push(path);
+ const [, id, size] = /pic\/([^/]+)\/(\w+)/.exec(path) ?? [];
+ const c = COLOURS[id] ?? [128, 128, 128];
+ const long = /^fit(\d+)/.test(size) ? +size.slice(3) : 512;
+ // A slow picture now and then, as one made from the network is: the show waits for it.
+ if (id === "p4" && size.startsWith("fit") && long > 1000) await new Promise((r) => setTimeout(r, 700));
+ const w = long, h = Math.round((long * 3) / 4);
+ await route.fulfill({ contentType: "image/svg+xml", body: `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}"><rect width="${w}" height="${h}" fill="rgb(${c.join(",")})"/></svg>` });
+ });
+ const page = await ctx.newPage();
+ page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });
+ await page.goto(process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
+ await openScreen(page, "Photos");
+ await page.waitForTimeout(400);
+ await page.locator('.px-tile[data-id="p1"]').dispatchEvent("dblclick");
+ await page.waitForTimeout(500);
+ await page.getByRole("button", { name: "Start Slideshow" }).click();
+ return { ctx, page };
+}
+
+/** The colour in the middle of the screen, captured as composited. */
+async function middle(page) {
+ const png = PNG.sync.read(await page.screenshot({ clip: { x: 620, y: 380, width: 40, height: 40 } }));
+ let r = 0, g = 0, bl = 0;
+ for (let i = 0; i < png.data.length; i += 4) { r += png.data[i]; g += png.data[i + 1]; bl += png.data[i + 2]; }
+ const n = png.data.length / 4;
+ return [r / n, g / n, bl / n];
+}
+const count = (page) => page.locator(".px-show-count").innerText();
+
+const { ctx, page } = await open(false);
+await page.waitForFunction(() => document.querySelector(".px-show-count")?.textContent?.startsWith("1 of"), null, { timeout: 5000 });
+await page.waitForTimeout(300);
+// Two layers, made once: marked now, and the same two elements must still be there later.
+await page.evaluate(() => document.querySelectorAll(".px-slide").forEach((l, i) => (l.dataset.mark = String(i))));
+ok((await page.locator(".px-slide").count()) === 2, "two layers take turns");
+const first = await page.evaluate(() => {
+ const l = [...document.querySelectorAll(".px-slide")].find((x) => x.style.opacity === "1");
+ const img = l?.querySelector("img");
+ return { src: decodeURIComponent(img?.src ?? ""), w: img?.naturalWidth, dpr: devicePixelRatio, W: innerWidth, H: innerHeight };
+});
+const step = +(/fit(\d+)/.exec(first.src)?.[1] ?? 0);
+ok(/p1\/fit/.test(first.src) && step >= Math.min(first.W, (first.H * 4) / 3) * first.dpr, `the photo is made the size of the screen, never smaller (${first.src.split("/").pop()} for ${first.W}×${first.H} at ${first.dpr}×)`);
+
+// Each frame of the dissolve into the next photo, as the page sets it: the layers' opacities
+// and whether the picture of each is decoded. The screen behind is never left uncovered.
+const watch = () => page.evaluate(() => {
+ window.__frames = [];
+ const tick = () => {
+ const ls = [...document.querySelectorAll(".px-slide")].map((l) => ({ o: +l.style.opacity, z: +l.style.zIndex, ready: l.querySelector("img").complete && l.querySelector("img").naturalWidth > 0 }));
+ window.__frames.push(ls);
+ if (window.__frames.length < 600) requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+});
+await watch();
+// Captured from the screen while it changes: never black in the middle, where both photos are.
+const shots = [];
+const t0 = Date.now();
+while (Date.now() - t0 < 5200 && (await count(page)).startsWith("1 of")) shots.push(await middle(page));
+for (let i = 0; i < 8; i++) shots.push(await middle(page));
+const black = shots.filter(([r, g, bl]) => r + g + bl < 60);
+ok(shots.length > 8 && black.length === 0, `no black frame on the screen as it moves to the next (${shots.length} frames captured, ${black.length} black)`);
+ok(/^2 of/.test(await count(page)), "on to the next by itself");
+const frames = await page.evaluate(() => window.__frames);
+const covered = frames.every((ls) => {
+ const shown = ls.filter((l) => l.o > 0);
+ // Whatever shows is decoded, and together the layers cover the screen: never a dip.
+ const cover = 1 - shown.reduce((k, l) => k * (1 - l.o), 1);
+ return shown.every((l) => l.ready) && cover >= 0.9;
+});
+const mid = frames.filter((ls) => ls.some((l) => l.o > 0.05 && l.o < 0.95)).length;
+ok(covered, `every frame of the dissolve shows decoded pictures covering the screen (${frames.length} frames)`);
+ok(mid >= 5, `and it dissolves over several frames, not a cut (${mid} in between)`);
+ok(await page.evaluate(() => [...document.querySelectorAll(".px-slide")].every((l) => l.dataset.mark !== undefined)), "the same two layers, never torn down and made again");
+
+// The video: its picture first, then the film from the app's server over it, then on.
+await page.waitForFunction(() => document.querySelector(".px-show-count")?.textContent?.startsWith("3 of"), null, { timeout: 9000 });
+const film = await page.waitForFunction(() => {
+ const v = [...document.querySelectorAll(".px-slide video")].find((x) => x.getAttribute("src"));
+ return v && { src: v.getAttribute("src"), o: v.style.opacity, t: v.currentTime, poster: decodeURIComponent(v.closest(".px-slide").querySelector("img").src) };
+}, null, { timeout: 5000 }).then((h) => h.jsonValue());
+ok(film.src === `${base}/p3/video` && /p3\/fit/.test(film.poster), `a video shows its picture and plays its film from the app's server ${film.src}`);
+const shownFilm = await page.waitForFunction(() => {
+ const v = [...document.querySelectorAll(".px-slide video")].find((x) => x.getAttribute("src"));
+ return v && v.style.opacity === "1" && v.currentTime > 0 ? v.currentTime : null;
+}, null, { timeout: 6000 }).then((h) => h.jsonValue()).catch(() => null);
+if (shownFilm === null && engineName !== "chromium") {
+ // An engine with no decoder for the clip: its picture stands its time instead.
+ ok(true, "this engine cannot play the clip: its picture stands in");
+} else ok(shownFilm > 0, `the film is drawn over its picture only once it is playing (at ${shownFilm?.toFixed?.(2)}s)`);
+await page.waitForFunction(() => document.querySelector(".px-show-count")?.textContent?.startsWith("4 of"), null, { timeout: 12000 });
+ok(true, "when the film ends the show moves on");
+
+// The keys: Space pauses (it stays), the arrows step, Escape ends.
+await page.keyboard.press(" ");
+await page.waitForTimeout(300);
+ok((await page.getByRole("button", { name: "Play" }).count()) === 1, "Space pauses it");
+const held = await count(page);
+await page.waitForTimeout(4600);
+ok((await count(page)) === held, `paused, it stays (${held})`);
+await page.keyboard.press("ArrowRight");
+await page.waitForFunction(() => document.querySelector(".px-show-count")?.textContent?.startsWith("5 of"), null, { timeout: 4000 });
+ok(true, "→ steps to the next");
+await page.keyboard.press("ArrowLeft");
+await page.waitForFunction(() => document.querySelector(".px-show-count")?.textContent?.startsWith("4 of"), null, { timeout: 4000 });
+ok(true, "← steps back");
+await page.keyboard.press("Escape");
+await page.waitForTimeout(300);
+ok((await page.locator(".px-show").count()) === 0, "Escape ends it");
+await ctx.close();
+
+// Reduced motion: the change is a cut — no frame in between.
+const r = await open(true);
+await r.page.waitForFunction(() => document.querySelector(".px-show-count")?.textContent?.startsWith("1 of"), null, { timeout: 5000 });
+await r.page.evaluate(() => {
+ window.__frames = [];
+ const tick = () => { window.__frames.push([...document.querySelectorAll(".px-slide")].map((l) => +l.style.opacity)); if (window.__frames.length < 400) requestAnimationFrame(tick); };
+ requestAnimationFrame(tick);
+});
+await r.page.keyboard.press("ArrowRight");
+await r.page.waitForFunction(() => document.querySelector(".px-show-count")?.textContent?.startsWith("2 of"), null, { timeout: 4000 });
+await r.page.waitForTimeout(300);
+const between = await r.page.evaluate(() => window.__frames.filter((f) => f.some((o) => o > 0.02 && o < 0.98)).length);
+ok(between === 0, `with reduced motion, a cut (${between} frames in between)`);
+await r.ctx.close();
+
+await b.close();
+server.close();
+process.exitCode = failures ? 1 : (process.exitCode ?? 0);
diff --git a/.uiverify/photos-video.mjs b/.uiverify/photos-video.mjs
index 2e5ead7..e59334d 100644
--- a/.uiverify/photos-video.mjs
+++ b/.uiverify/photos-video.mjs
@@ -99,6 +99,21 @@ await p2.waitForTimeout(400);
await p2.locator('.px-tile[data-id="p3"]').dblclick();
await p2.waitForTimeout(600);
ok((await p2.locator(".px-stage video").count()) === 0 && (await p2.locator(".px-stage button.px-video").count()) === 1, "without the server, the still and the system's player");
+// A video this computer cannot play: a still, and words that say why and what fixes it — never
+// a black box.
+const p3 = await ctx.newPage();
+await p3.addInitScript(() => {
+ window.__videoBase = "http://127.0.0.1:9/none";
+ window.__videoSupport = { h264: false, hevc: false, missing: ["gst-libav"] };
+});
+await p3.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await openScreen(p3, "Photos");
+await p3.waitForTimeout(400);
+await p3.locator('.px-tile[data-id="p3"]').dblclick();
+await p3.waitForTimeout(2500);
+const note = await p3.locator(".px-video-note").innerText().catch(() => "");
+ok((await p3.locator(".px-stage button.px-video").count()) === 1 && /gst-libav/.test(note) && /video player/.test(note),
+ `one this computer cannot play says why, and plays in the system's player "${note}"`);
await b.close();
server.close();
process.exitCode = failures ? 1 : (process.exitCode ?? 0);
diff --git a/.uiverify/photos-viewer-frames.mjs b/.uiverify/photos-viewer-frames.mjs
new file mode 100644
index 0000000..3e8f07f
--- /dev/null
+++ b/.uiverify/photos-viewer-frames.mjs
@@ -0,0 +1,147 @@
+// The viewer never shows a black or empty frame: opening a photo, stepping to the next and back
+// (photos and a video among them), and a Live Photo playing and ending. Each is captured from
+// the screen frame after frame; the middle of the stage must always show the photo's colour —
+// its tile's picture, the one before it, or itself — never the stage's bare backdrop or black.
+//
+// And a Live Photo's moving part lies exactly over its still: the still upright in a box of its
+// own shape (Apple records the sensor's sides, 4032 × 3024, for a photo shown portrait), the film
+// turned a quarter as its file says, and drawn larger by its margin (clean aperture) so only what
+// the still shows is seen — clipped to the still's box, never a smaller box inside it.
+import http from "node:http";
+import fs from "node:fs";
+import { createRequire } from "node:module";
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const { PNG } = createRequire(import.meta.url)("playwright-core/lib/utilsBundle");
+
+const clip = new URL("./clip.webm", import.meta.url);
+const len = fs.statSync(clip).size;
+const server = http.createServer((req, res) => {
+ const m = /bytes=(\d*)-(\d*)/.exec(req.headers.range ?? "");
+ const f = m && m[1] ? +m[1] : 0, l = m && m[2] ? Math.min(+m[2], len - 1) : len - 1;
+ res.writeHead(m ? 206 : 200, { "Content-Type": "video/webm", "Accept-Ranges": "bytes", "Content-Length": l - f + 1, "Content-Range": `bytes ${f}-${l}/${len}` });
+ fs.createReadStream(clip, { start: f, end: l }).pipe(res);
+});
+await new Promise((r) => server.listen(0, "127.0.0.1", r));
+const base = `http://127.0.0.1:${server.address().port}/s3cret`;
+
+const COLOURS = { p1: [220, 40, 40], p2: [40, 180, 60], p3: [40, 80, 220], p4: [230, 200, 30], p5: [200, 60, 200] };
+const PICS = "http://pics.test";
+const b = await engine.launch();
+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });
+await ctx.addInitScript(([v, pics]) => {
+ window.__videoBase = v;
+ window.__picBase = pics;
+ // p4: a Live Photo shown portrait though Apple records it 4032 × 3024; its film a quarter turn
+ // with a margin round it, as his are.
+ window.__photoExtra = { p4: { kind: "live" } };
+ window.__turn = [0, 1, -1, 0];
+ window.__zoom = 960 / 872;
+}, [base, PICS]);
+await ctx.route(`${PICS}/**`, async (route) => {
+ const path = decodeURIComponent(route.request().url().slice(PICS.length + 1));
+ const [, id, size] = /pic\/([^/]+)\/(\w+)/.exec(path) ?? [];
+ const c = COLOURS[id] ?? [128, 128, 128];
+ const long = /^fit(\d+)/.test(size) ? +size.slice(3) : 512;
+ // The viewer's pictures are slow to come, as ones made from the network are: what stands in
+ // meanwhile is what this proves.
+ if (/^fit/.test(size) && long > 700) await new Promise((r) => setTimeout(r, 400));
+ const portrait = id === "p4";
+ const [w, h] = portrait ? [Math.round((long * 3) / 4), long] : [long, Math.round((long * 3) / 4)];
+ await route.fulfill({ contentType: "image/svg+xml", body: `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}"><rect width="${w}" height="${h}" fill="rgb(${c.join(",")})"/></svg>` });
+});
+const page = await ctx.newPage();
+page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });
+await page.goto(process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
+await openScreen(page, "Photos");
+await page.waitForTimeout(800);
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+
+const backdrop = async () => page.evaluate(() => {
+ const m = /\d+(\.\d+)?/g;
+ return (getComputedStyle(document.querySelector(".px-backdrop") ?? document.body).backgroundColor.match(m) ?? []).slice(0, 3).map(Number);
+});
+const near = (a, c, d = 40) => Math.abs(a[0] - c[0]) + Math.abs(a[1] - c[1]) + Math.abs(a[2] - c[2]) < d;
+/** Frames of the stage's middle while `act` runs and for `ms` after. */
+async function capture(act, ms) {
+ const frames = [];
+ const box = await page.evaluate(() => {
+ const s = document.querySelector(".px-stage")?.getBoundingClientRect();
+ return s ? { x: s.left + s.width / 2 - 15, y: s.top + s.height / 2 - 15 } : { x: 625, y: 385 };
+ });
+ const run = act();
+ const t0 = Date.now();
+ while (Date.now() - t0 < ms) {
+ const png = PNG.sync.read(await page.screenshot({ clip: { x: box.x, y: box.y, width: 30, height: 30 } }));
+ let r = 0, g = 0, bl = 0;
+ for (let i = 0; i < png.data.length; i += 4) { r += png.data[i]; g += png.data[i + 1]; bl += png.data[i + 2]; }
+ const n = png.data.length / 4;
+ frames.push([r / n, g / n, bl / n]);
+ }
+ await run;
+ return frames;
+}
+const judge = (frames, back, what) => {
+ const black = frames.filter((c) => c[0] + c[1] + c[2] < 45).length;
+ const bare = frames.filter((c) => near(c, back, 12)).length;
+ ok(frames.length >= 5 && black === 0 && bare === 0, `${what}: no black or empty frame (${frames.length} frames, ${black} black, ${bare} bare backdrop)`);
+};
+
+// Opening: the tile's own picture stands in until the sharp one is decoded.
+let frames = await capture(() => page.locator('.px-tile[data-id="p1"]').dispatchEvent("dblclick"), 1400);
+const back = await backdrop();
+// The first frames may be the grid itself (the click not yet taken); judged from the viewer on.
+const opened = frames.findIndex((c) => near(c, COLOURS.p1, 60));
+judge(frames.slice(Math.max(0, opened)), back, "opening a photo");
+// Stepping on and back, a video among them.
+for (const [key, label] of [["ArrowRight", "to the next photo"], ["ArrowRight", "to a video"], ["ArrowRight", "from a video to a photo"], ["ArrowLeft", "back to the video"], ["ArrowLeft", "back to a photo"]]) {
+ frames = await capture(() => page.keyboard.press(key), 1100);
+ judge(frames, back, `stepping ${label}`);
+}
+// The video's own picture stands until a frame of the film is here; the film is never black.
+await page.evaluate(() => {
+ // Each frame from the step on: whether the film is drawn yet, and whether its picture is there.
+ window.__seen = [];
+ const tick = () => {
+ const v = document.querySelector(".px-stage video");
+ if (v) window.__seen.push({ o: v.style.opacity, t: v.currentTime, poster: !!document.querySelector(".px-player-poster") && decodeURIComponent(document.querySelector(".px-player-poster").src).includes("p3/fit") });
+ if (window.__seen.length < 120) requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+});
+await page.keyboard.press("ArrowRight");
+await page.waitForTimeout(1500);
+const seen = await page.evaluate(() => window.__seen);
+const poster = { first: seen[0], beforeFilm: seen.filter((f) => f.o !== "1").every((f) => f.poster), filmOnlyPlaying: seen.filter((f) => f.o === "1").every((f) => f.t > 0) };
+ok(seen.length > 0 && poster.first?.poster && poster.beforeFilm && poster.filmOnlyPlaying, `a video shows its own picture until a frame of its film is here ${JSON.stringify(poster)}`);
+
+// The Live Photo.
+await page.keyboard.press("Escape");
+await page.waitForTimeout(500);
+await page.locator('.px-tile[data-id="p4"]').dispatchEvent("dblclick");
+await page.waitForTimeout(1500);
+const live = page.getByRole("button", { name: "Play Live Photo" });
+frames = await capture(() => live.click(), 2500);
+judge(frames, back, "playing a Live Photo");
+const fit = await page.evaluate(() => {
+ const still = document.querySelector(".px-pan .px-shown").getBoundingClientRect();
+ const frame = document.querySelector(".px-live-frame")?.getBoundingClientRect();
+ const v = document.querySelector("video.px-live");
+ const r = v?.getBoundingClientRect();
+ return v && { still: [still.left, still.top, still.width, still.height].map(Math.round), frame: [frame.left, frame.top, frame.width, frame.height].map(Math.round), film: [r.left, r.top, r.width, r.height].map(Math.round), t: getComputedStyle(v).transform };
+});
+ok(fit && fit.still[3] > fit.still[2], `the still shows upright, portrait, though Apple records it landscape ${JSON.stringify(fit?.still)}`);
+ok(fit && fit.frame.every((x, i) => Math.abs(x - fit.still[i]) <= 1), `the moving part is clipped to the still's own box ${JSON.stringify(fit?.frame)}`);
+const z = 960 / 872;
+ok(fit && Math.abs(fit.film[2] - fit.still[2] * z) <= 2 && Math.abs(fit.film[3] - fit.still[3] * z) <= 2
+ && Math.abs(fit.film[0] + fit.film[2] / 2 - (fit.still[0] + fit.still[2] / 2)) <= 1 && Math.abs(fit.film[1] + fit.film[3] / 2 - (fit.still[1] + fit.still[3] / 2)) <= 1,
+ `turned and drawn its margin larger, centred on the still — never a smaller box (film ${JSON.stringify(fit?.film)}, ${fit?.t})`);
+// It ends: the still again, with nothing in between.
+frames = await capture(() => page.waitForSelector("video.px-live", { state: "detached", timeout: 9000 }), 600);
+judge(frames, back, "a Live Photo ending");
+
+await b.close();
+server.close();
+process.exitCode = failures ? 1 : (process.exitCode ?? 0);
diff --git a/.uiverify/photos.mjs b/.uiverify/photos.mjs
index cbb0491..f5c993f 100644
--- a/.uiverify/photos.mjs
+++ b/.uiverify/photos.mjs
@@ -7,7 +7,7 @@ const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });
await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });
const page = await ctx.newPage();
page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });
-await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await page.goto(process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
await openScreen(page, "Photos");
await page.waitForTimeout(400);
let failures = 0;
diff --git a/.uiverify/readme-shots.mjs b/.uiverify/readme-shots.mjs
index 6429078..82ea616 100644
--- a/.uiverify/readme-shots.mjs
+++ b/.uiverify/readme-shots.mjs
@@ -5,7 +5,8 @@
// node .uiverify/readme-shots.mjs notes hero only those scenes
//
// It builds the interface and previews it on PORT (4220) unless something already answers
-// there. Needs ImageMagick (`magick`) and ffmpeg. Optional: the four Unsplash pictures named
+// there. Needs ImageMagick (`magick`) and ffmpeg. PNGs are optimised with pngquant and oxipng
+// when installed, or the same engines through `uv`. Optional: the four Unsplash pictures named
// in UNSPLASH below; without them, drawn pictures take their places.
import { spawn, execFileSync } from "node:child_process";
import fs from "node:fs";
@@ -149,6 +150,12 @@ const SCENES = {
photos: async (page) => {
await page.locator(".nav-item", { hasText: "Photos" }).click();
await page.waitForTimeout(1800);
+ // Every tile in view drawn, not a grey placeholder still waiting on its picture.
+ await page.waitForFunction(() => [...document.querySelectorAll("img")].every((i) => {
+ const r = i.getBoundingClientRect();
+ return r.bottom < 0 || r.top > innerHeight || (i.complete && i.naturalWidth > 0);
+ }), null, { timeout: 15000 }).catch(() => console.log("photos: some tiles still loading"));
+ await page.waitForTimeout(5000);
},
settings: async (page) => {
await page.locator(".sidebar-account").click();
@@ -196,12 +203,27 @@ async function sizeOf(png) {
return { w, h };
}
-/** WebP for the README (2048 px wide) and a smaller PNG for anything that can't show WebP. */
+/** A PNG for the README, 1600 px wide (sharp at the README's 880), stripped and optimised. */
function publish(framed, name) {
- const webp = path.join(OUT, `${name}.webp`), png = path.join(OUT, `${name}.png`);
- sh("magick", [framed, "-strip", "-resize", "2048x", "-quality", "86", "-define", "webp:method=6", webp]);
- sh("magick", [framed, "-strip", "-resize", "1280x", "-define", "png:compression-level=9", "-colors", "256", "-dither", "None", `PNG8:${png}`]);
- for (const f of [webp, png]) console.log(`${path.relative(ROOT, f)} ${Math.round(fs.statSync(f).size / 1024)} KB`);
+ const png = path.join(OUT, `${name}.png`);
+ sh("magick", [framed, "-strip", "-resize", "1600x", "-define", "png:compression-level=9", `PNG24:${png}`]);
+ optimise(png);
+ console.log(`${path.relative(ROOT, png)} ${Math.round(fs.statSync(png).size / 1024)} KB`);
+}
+
+const has = (cmd) => { try { execFileSync("sh", ["-c", `command -v ${cmd}`], { stdio: "ignore" }); return true; } catch { return false; } };
+/** pngquant then oxipng when installed; otherwise the same two engines (libimagequant and
+ * oxipng) through `uv`, in a throwaway environment; otherwise the PNG stays as written. */
+function optimise(png) {
+ if (has("pngquant")) { sh("pngquant", ["--force", "--skip-if-larger", "--quality", "80-95", "--strip", "--output", png, png]); if (has("oxipng")) sh("oxipng", ["-o", "4", "--strip", "all", png]); return; }
+ if (!has("uv")) return;
+ const py = `import sys, imagequant, oxipng
+from PIL import Image
+p = sys.argv[1]
+q = imagequant.quantize_pil_image(Image.open(p).convert("RGBA"), dithering_level=1.0, max_colors=256, min_quality=80, max_quality=95)
+q.save(p, optimize=True)
+oxipng.optimize(p, level=4, strip=oxipng.StripChunks.all())`;
+ sh("uv", ["run", "--quiet", "--python", "3.12", "--no-project", "--with", "imagequant", "--with", "pillow", "--with", "pyoxipng", "python", "-I", "-c", py, png]);
}
// ---- Stills.
diff --git a/.uiverify/reminder-quick.test.mjs b/.uiverify/reminder-quick.test.mjs
new file mode 100644
index 0000000..a078ef0
--- /dev/null
+++ b/.uiverify/reminder-quick.test.mjs
@@ -0,0 +1,48 @@
+// A reminder typed in one line: day, time, repeat and priority read out; everything else —
+// including words that only look like dates — stays the title.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { parseReminder, understood } from "../src/screens/reminderQuick.ts";
+
+const now = new Date(2026, 9, 22, 10, 0); // Thursday
+const local = (y, m, d, h = 0, min = 0) => Math.floor(new Date(y, m, d, h, min).getTime() / 1000);
+
+test("a day and a time make it due then", () => {
+ const q = parseReminder("Call mom tomorrow 6pm", now, true);
+ assert.deepEqual([q.title, q.dueAt, q.allDay, q.repeat, q.priority], ["Call mom", local(2026, 9, 23, 18), false, null, 0]);
+});
+
+test("a day alone is all day", () => {
+ const q = parseReminder("Submit report friday", now, true);
+ assert.deepEqual([q.title, q.dueAt, q.allDay], ["Submit report", local(2026, 9, 23), true]);
+});
+
+test("a repeat maps to Apple's numbering, starting today when no day is named", () => {
+ assert.deepEqual(parseReminder("Water plants daily", now, true).repeat, { frequency: 0, interval: 1 });
+ const gym = parseReminder("Gym every Monday 7am", now, true);
+ assert.deepEqual([gym.title, gym.repeat, gym.dueAt], ["Gym", { frequency: 1, interval: 1 }, local(2026, 9, 26, 7)]);
+ const water = parseReminder("Water plants daily", now, true);
+ assert.deepEqual([water.dueAt, water.allDay], [local(2026, 9, 22), true]);
+});
+
+test("! marks priority, leading or trailing, and goes from the title", () => {
+ assert.deepEqual([parseReminder("!!! Pay rent", now, true).priority, parseReminder("!!! Pay rent", now, true).title], [1, "Pay rent"]);
+ assert.equal(parseReminder("Pay rent !!", now, true).priority, 5);
+ assert.equal(parseReminder("! Pay rent", now, true).priority, 9);
+ assert.equal(parseReminder("Wow!", now, true).priority, 0, "a ! inside a word is just a !");
+ assert.equal(parseReminder("Wow!", now, true).title, "Wow!");
+});
+
+test("words that only look like dates stay the title", () => {
+ for (const t of ["Call May", "Read 20 pages", "Buy milk", "Email Sunday school", "Book: March of the Penguins"]) {
+ const q = parseReminder(t, now, true);
+ if (q.dueAt === null) assert.equal(q.title, t);
+ }
+ assert.equal(understood(parseReminder("Buy milk", now, true)), false);
+ assert.equal(understood(parseReminder("Call May", now, true)), false);
+});
+
+test("a place is kept in the title", () => {
+ const q = parseReminder("Pick up parcel at the post office tomorrow", now, true);
+ assert.match(q.title, /post office/);
+});
diff --git a/.uiverify/reminders-add-done.mjs b/.uiverify/reminders-add-done.mjs
index 1e72dae..0270742 100644
--- a/.uiverify/reminders-add-done.mjs
+++ b/.uiverify/reminders-add-done.mjs
@@ -11,7 +11,7 @@ await ctx.addInitScript(() => {
wrap(); document.addEventListener("DOMContentLoaded", wrap);
});
const page = await ctx.newPage();
-await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await page.goto(process.env.BASE ?? "http://localhost:4173", { waitUntil: "networkidle" });
await openScreen(page, "Reminders");
await page.locator(".rx-tile", { hasText: "Today" }).click();
await page.waitForTimeout(300);
diff --git a/.uiverify/reminders-detail-writes.mjs b/.uiverify/reminders-detail-writes.mjs
index 5749f2b..9988314 100644
--- a/.uiverify/reminders-detail-writes.mjs
+++ b/.uiverify/reminders-detail-writes.mjs
@@ -48,8 +48,8 @@ await url.press("Enter");
await page.waitForTimeout(200);
ok((await writes()).some((w) => w.cmd === "reminder_url_set" && w.url === "https://example.com/parcel"), "a link is saved");
// Early alert.
-await page.getByRole("button", { name: /Early alert for Pick up the parcel/ }).click();
-await page.locator(".picker-menu li", { hasText: "15 minutes early" }).click();
+await page.getByRole("button", { name: /Early reminder for Pick up the parcel/ }).click();
+await page.locator(".picker-menu li", { hasText: "15 minutes before" }).click();
await page.waitForTimeout(200);
ok((await writes()).some((w) => w.cmd === "reminder_early_alert_set" && w.count === 15 && w.unit === 0), "an early alert is set");
// Sections: move, make, rename.
diff --git a/.uiverify/reminders-instant.mjs b/.uiverify/reminders-instant.mjs
index 52dcb5f..04a8be2 100644
--- a/.uiverify/reminders-instant.mjs
+++ b/.uiverify/reminders-instant.mjs
@@ -20,7 +20,7 @@ await ctx.addInitScript(() => {
wrap(); document.addEventListener("DOMContentLoaded", wrap);
});
const page = await ctx.newPage();
-await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await page.goto(process.env.BASE ?? "http://localhost:4173", { waitUntil: "networkidle" });
await openScreen(page, "Reminders");
await page.locator(".rx-list", { hasText: "Daily" }).first().click();
await page.waitForTimeout(400);
diff --git a/.uiverify/reminders-keys-after-photos.mjs b/.uiverify/reminders-keys-after-photos.mjs
new file mode 100644
index 0000000..a690b33
--- /dev/null
+++ b/.uiverify/reminders-keys-after-photos.mjs
@@ -0,0 +1,32 @@
+// Reminders' keys after Photos has been opened. Photos keeps its grid — a listbox — mounted
+// once visited, and Reminders took any listbox on the page for an open menu, so Ctrl+N did
+// nothing until the app restarted. It now asks overlayOpen(), which knows a screen's own list.
+//
+// BASE=http://localhost:4173 ENGINE=webkit node .uiverify/reminders-keys-after-photos.mjs
+import { engine, engineName } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const BASE = process.env.BASE ?? "http://localhost:4173";
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${engineName} ${m}`); if (!p) failures++; };
+
+const ctx = await b.newContext({ viewport: { width: 1280, height: 820 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, remindersFixture: true });
+const page = await ctx.newPage();
+page.on("pageerror", (e) => ok(false, `page error: ${e.message}`));
+await page.goto(BASE, { waitUntil: "networkidle" });
+
+await openScreen(page, "Photos");
+await page.waitForTimeout(500);
+ok((await page.locator('[role="listbox"]').count()) > 0, "Photos' grid is on the page");
+await openScreen(page, "Reminders");
+await page.waitForTimeout(400);
+await page.locator(".rx-row").first().click();
+await page.keyboard.press("Escape");
+await page.keyboard.press("Control+n");
+await page.waitForTimeout(300);
+const focused = await page.evaluate(() => !!document.activeElement?.closest(".rx-add, .rx-row"));
+ok(focused, "Ctrl+N still starts a new reminder after Photos was opened");
+
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/reminders-parity.mjs b/.uiverify/reminders-parity.mjs
new file mode 100644
index 0000000..37f73a5
--- /dev/null
+++ b/.uiverify/reminders-parity.mjs
@@ -0,0 +1,156 @@
+// Parity with the iPhone's Details screen, on a reminder shaped like the founder's own "Skykeep
+// Test": New York 11:00, daily, Urgent, three tags, flagged, Medium, Home arriving, When
+// Messaging. Every one shows; the phone's Repeat menu is there in its order; Custom, End Repeat,
+// time, flag and priority each send what the phone would. node .uiverify/reminders-parity.mjs [png]
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const b = await engine.launch();
+const ctx = await b.newContext({ viewport: { width: 1300, height: 900 }, colorScheme: "dark" });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, remindersFixture: true });
+const DUE = 1792681200; // 22 Oct 2026, 11:00 in New York (15:00 UTC)
+await ctx.addInitScript((due) => {
+ window.__extraReminders = [{ guid: "sk", listGuid: "l1", title: "Skykeep Test", notes: "Parity", dueAt: due, allDay: false,
+ timezone: "America/New_York", completedAt: null, priority: 5, flagged: true, parentGuid: null, etag: null,
+ recurFrequency: 0, recurInterval: 1 }];
+ window.__tagMap = { sk: ["Skykeep", "Tags", "Testing"] };
+ window.__details = { sk: { url: "https://example.com", otherAttachments: 2, images: ["Attachment/A1", "Attachment/A2"] } };
+ window.__marks = { sk: { urgent: true, location: { title: "Alex\u2019s Home", proximity: "arriving", kind: "Location" },
+ messaging: "Alex Rivera", url: "https://www.google.com/" } };
+ window.__more = { sk: { timeZone: "America/New_York", urgent: true,
+ location: { title: "Alex’s Home", proximity: "arriving", kind: "Location" },
+ messaging: { name: "Alex Rivera", handles: ["[email protected]"] } } };
+}, DUE);
+const page = await ctx.newPage();
+page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });
+await page.goto(process.env.BASE ?? "http://localhost:4310", { waitUntil: "networkidle" });
+await openScreen(page, "Reminders");
+await page.locator(".rx-list", { hasText: "Daily" }).click();
+await page.waitForTimeout(300);
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+await page.getByRole("button", { name: "Details for Skykeep Test" }).click();
+await page.waitForTimeout(400);
+const panel = page.getByRole("group", { name: "Info for Skykeep Test" });
+const text = await panel.innerText();
+// The row, as the phone's list shows it.
+const rowText = (await page.locator(".rx-row", { has: page.getByLabel("Rename Skykeep Test") }).innerText()).replace(/\n/g, " ");
+ok(/\(11:00\s?AM GMT-4\)/.test(rowText), `the row adds New York's clock (${rowText.slice(0, 80)})`);
+ok((await page.getByRole("img", { name: "Urgent" }).count()) === 1, "the row carries the Urgent alarm");
+ok(rowText.includes("Arriving:") && rowText.includes("Alex’s Home"), "a place chip: Arriving: Alex's Home");
+ok(rowText.includes("Messaging:") && rowText.includes("Alex Rivera"), "a person chip: Messaging: Alex Rivera");
+ok(rowText.includes("google.com") && !rowText.includes("www."), "a link chip: google.com");
+const field = (label) => panel.locator(".rx-field", { has: page.locator(`span:text-is("${label}")`) }).first();
+
+ok((await page.getByLabel("Time of day for Skykeep Test").inputValue()).replace(/\s/g, "").match(/^11:00(AM)?$/i) !== null,
+ `the time is New York's 11:00, not this computer's (${await page.getByLabel("Time of day for Skykeep Test").inputValue()})`);
+ok(/New York\s*GMT−4/.test(await field("Time Zone").innerText()), `Time Zone: New York, GMT−4 (${(await field("Time Zone").innerText()).replace(/\n/g, " ")})`);
+ok(/Urgent\s*On/.test(text) && text.includes("even in a Focus or on silent"), "Urgent is shown on, with what it does");
+ok((await page.getByLabel("Repeat for Skykeep Test", { exact: true }).innerText()).includes("Daily"), "Repeat: Daily");
+ok(/End Repeat\s*Never/.test(text), "End Repeat: Never");
+ok(["#Skykeep", "#Tags", "#Testing"].every((t) => text.includes(t)), "all three tags");
+ok((await page.getByRole("switch", { name: "Flag for Skykeep Test" }).isChecked()) === true, "Flag is on");
+ok((await page.getByLabel("Priority for Skykeep Test").innerText()).includes("Medium"), "Priority: Medium");
+ok(/Location\s*Alex’s Home\s*Arriving/.test(text), `Location: Alex's Home, Arriving`);
+ok(/When Messaging\s*Alex Rivera/.test(text), "When Messaging: the person, by name");
+ok((await page.locator(".rx-images .rx-image").count()) === 2, "its two pictures are shown");
+ok(!/…/.test(text), "no trailing ellipsis anywhere in the panel");
+
+// The phone's Repeat menu, in its order, with the rules chosen on the phone greyed.
+await page.getByLabel("Repeat for Skykeep Test", { exact: true }).click();
+await page.waitForTimeout(150);
+const menu = page.getByRole("listbox", { name: "Repeat for Skykeep Test", exact: true });
+const labels = (await menu.getByRole("option").allInnerTexts()).map((t) => t.replace(/✓/g, "").trim());
+ok(JSON.stringify(labels) === JSON.stringify(["Never", "Hourly", "Daily", "Weekdays", "Weekends", "Weekly", "Biweekly", "Monthly", "Every 3 Months", "Every 6 Months", "Yearly", "Custom"]),
+ `the phone's Repeat menu, in its order (${labels.join(", ")})`);
+ok((await menu.locator("li.has-divider").count()) === 2, "Never and Custom set apart, as on the phone");
+await menu.getByRole("option", { name: "Weekdays" }).click();
+await page.waitForTimeout(300);
+const last = () => page.evaluate(() => (window.__repeats ?? []).at(-1));
+let sent = await last();
+ok(sent?.repeat?.frequency === 1 && sent?.repeat?.interval === 1 && JSON.stringify(sent?.daysOfWeek) === "[2,3,4,5,6]", `Weekdays is weekly on Monday to Friday, as the phone writes it (${JSON.stringify(sent)})`);
+ok((await page.locator(".rx-row", { has: page.getByLabel("Rename Skykeep Test") }).locator(".rx-repeat").innerText()).includes("Weekdays"), "and the row says Weekdays");
+await page.getByLabel("Repeat for Skykeep Test", { exact: true }).click();
+await page.getByRole("option", { name: "Weekends" }).click();
+await page.waitForTimeout(300);
+sent = await last();
+ok(JSON.stringify(sent?.daysOfWeek) === "[1,7]", "Weekends is Saturday and Sunday");
+ok((await page.getByLabel("Repeat for Skykeep Test", { exact: true }).innerText()).includes("Weekends"), "and the menu shows it");
+await page.getByLabel("Repeat for Skykeep Test", { exact: true }).click();
+await page.getByRole("option", { name: "Every 3 Months" }).click();
+await page.waitForTimeout(300);
+sent = await last();
+ok(sent?.repeat?.frequency === 2 && sent?.repeat?.interval === 3 && sent?.endAt === null && sent?.daysOfWeek.length === 0, `Every 3 Months is monthly, every 3 (${JSON.stringify(sent)})`);
+ok((await page.getByLabel("Repeat for Skykeep Test", { exact: true }).innerText()).includes("Every 3 Months"), "and the menu shows it at once");
+
+// Custom: Frequency and Every, then the days it falls on.
+await page.getByLabel("Repeat for Skykeep Test", { exact: true }).click();
+await page.getByRole("option", { name: "Custom" }).click();
+await page.waitForTimeout(200);
+const custom = page.getByRole("group", { name: "Custom repeat for Skykeep Test" });
+ok(await custom.isVisible(), "Custom opens its Frequency and Every");
+ok((await page.getByLabel("Frequency for Skykeep Test").innerText()).includes("Monthly"), "with the rule as it stands: Monthly");
+ok((await custom.locator(".rx-day.is-on").innerText()).trim() === "22", "on day 22, the day it is due");
+await page.getByLabel("Frequency for Skykeep Test").click();
+const freqs = (await page.getByRole("listbox", { name: "Frequency for Skykeep Test" }).getByRole("option").allInnerTexts()).map((t) => t.replace(/✓/g, "").trim());
+ok(JSON.stringify(freqs) === JSON.stringify(["Hourly", "Daily", "Weekly", "Monthly", "Yearly"]), `Frequency offers the phone's five (${freqs.join(", ")})`);
+await page.getByRole("option", { name: "Weekly" }).click();
+await page.waitForTimeout(250);
+sent = await last();
+ok(sent?.repeat?.frequency === 1 && sent?.repeat?.interval === 3, `Weekly keeps every 3 (${JSON.stringify(sent?.repeat)})`);
+ok((await custom.locator(".rx-day.is-on").getAttribute("aria-label")) === "Thursday", "weekly falls on Thursday, the 22nd's weekday in New York");
+// Monday, Wednesday, Friday, chosen in Custom.
+for (const day of ["Monday", "Wednesday", "Friday", "Thursday"]) {
+ await custom.getByRole("button", { name: day }).click();
+ await page.waitForTimeout(200);
+}
+sent = await last();
+ok(JSON.stringify(sent?.daysOfWeek) === "[2,4,6]" && sent?.repeat?.interval === 3, `Monday, Wednesday and Friday, every 3 weeks (${JSON.stringify(sent)})`);
+ok((await custom.innerText()).includes("on Monday, Wednesday and Friday"), "and says so");
+await custom.getByRole("button", { name: "More" }).click();
+await page.waitForTimeout(250);
+sent = await last();
+ok(sent?.repeat?.interval === 4, `+ makes it every 4 (${sent?.repeat?.interval})`);
+ok((await custom.innerText()).includes("Repeats every 4 weeks on Monday, Wednesday and Friday."), "and says so, keeping the days");
+
+// End Repeat: On Date sends an end after the due date; Never takes it off.
+await page.getByLabel("End repeat for Skykeep Test").click();
+await page.getByRole("option", { name: "On Date" }).click();
+await page.waitForTimeout(250);
+sent = await last();
+ok(sent?.endAt > DUE && sent?.repeat?.frequency === 1 && JSON.stringify(sent?.daysOfWeek) === "[2,4,6]", `On Date ends it after the day it is due (${sent?.endAt && new Date(sent.endAt * 1000).toISOString()})`);
+ok(await page.getByLabel("End repeat date for Skykeep Test").isVisible(), "with the date to change");
+await page.getByLabel("End repeat for Skykeep Test").click();
+await page.getByRole("option", { name: "Never" }).click();
+await page.waitForTimeout(250);
+sent = await last();
+ok(sent?.endAt === null && sent?.repeat?.interval === 4, "Never takes the end off and keeps the repeat");
+
+// The time is read and written on New York's clock.
+const time = page.getByLabel("Time of day for Skykeep Test");
+await time.fill("10:30 AM");
+await time.press("Enter");
+await page.waitForTimeout(300);
+const edit = await page.evaluate(() => (window.__edits ?? []).filter((e) => "dueAt" in e).at(-1));
+ok(edit?.dueAt === DUE - 1800 && edit?.allDay === false, `10:30 is New York's 10:30 (${edit && new Date(edit.dueAt * 1000).toISOString()})`);
+
+// Flag and priority.
+await page.getByRole("switch", { name: "Flag for Skykeep Test" }).click({ force: true });
+await page.waitForTimeout(250);
+ok((await page.evaluate(() => (window.__edits ?? []).some((e) => e.flagged === false))), "the Flag switch unflags it");
+await page.getByLabel("Priority for Skykeep Test").click();
+await page.getByRole("option", { name: "Low" }).click();
+await page.waitForTimeout(250);
+ok((await page.evaluate(() => (window.__edits ?? []).some((e) => e.priority === 9))), "Low is Apple's 9");
+
+// A rule whose days were chosen on the phone: shown as Custom, its days left to the phone.
+await page.evaluate(() => { window.__more.sk.repeat = { frequency: 1, interval: 1, endAt: null, occurrenceCount: 0, other: ["DaysOfTheWeek"] }; window.__extraReminders[0].recurInterval = 1; });
+await page.getByRole("button", { name: "Close details for Skykeep Test" }).click();
+await page.getByRole("button", { name: "Details for Skykeep Test" }).click();
+await page.waitForTimeout(400);
+ok((await page.getByLabel("Repeat for Skykeep Test", { exact: true }).innerText()).includes("Custom"), "a rule with days chosen on the phone reads Custom");
+ok((await page.getByRole("group", { name: "Custom repeat for Skykeep Test" }).innerText()).includes("on the days chosen on your iPhone"), "and says where its days were chosen");
+
+if (process.argv[2]) await page.screenshot({ path: process.argv[2] });
+console.log(failures ? `${failures} failed` : "all passed");
+process.exitCode = failures ? 1 : process.exitCode;
+await b.close();
diff --git a/.uiverify/reminders-quick-add.mjs b/.uiverify/reminders-quick-add.mjs
new file mode 100644
index 0000000..22955ed
--- /dev/null
+++ b/.uiverify/reminders-quick-add.mjs
@@ -0,0 +1,53 @@
+// A reminder typed in one line: what was understood shows before Return, and Return saves the
+// title with its day, time, priority and repeat — or, after Add as Typed, the line exactly as
+// it was typed. A plain line shows nothing extra.
+//
+// BASE=http://localhost:4173 ENGINE=webkit node .uiverify/reminders-quick-add.mjs
+import { engine, engineName } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const BASE = process.env.BASE ?? "http://localhost:4173";
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${engineName} ${m}`); if (!p) failures++; };
+
+const ctx = await b.newContext({ viewport: { width: 1300, height: 850 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, remindersFixture: true });
+const page = await ctx.newPage();
+page.on("pageerror", (e) => ok(false, `page error: ${e.message}`));
+await page.goto(BASE, { waitUntil: "networkidle" });
+await openScreen(page, "Reminders");
+await page.locator(".rx-side .rx-list").first().click().catch(() => {});
+await page.waitForTimeout(400);
+const field = page.locator(".rx-add input");
+await field.click();
+
+await field.fill("Buy milk");
+ok((await page.locator(".rx-add-understood").count()) === 0, "a plain line shows nothing extra");
+
+await field.fill("!! Call mom tomorrow 6pm daily");
+const reading = page.locator(".rx-add-understood .rx-add-reading");
+await reading.waitFor();
+const said = await reading.innerText();
+ok(/Tomorrow/.test(said) && /6:00/.test(said) && /Daily/.test(said) && /Medium priority/.test(said), `what was understood shows before Return "${said}"`);
+await field.press("Enter");
+await page.waitForTimeout(600);
+const created = await page.evaluate(() => window.__creates?.at(-1));
+const tomorrow6 = (() => { const d = new Date(); d.setDate(d.getDate() + 1); d.setHours(18, 0, 0, 0); return Math.floor(d.getTime() / 1000); })();
+ok(created?.title === "Call mom" && created?.dueAt === tomorrow6 && created?.allDay === false, `saved as "Call mom", due tomorrow 6 PM ${JSON.stringify(created)}`);
+const edits = await page.evaluate(() => window.__edits ?? []);
+ok(edits.some((e) => e.priority === 5), `and given medium priority ${JSON.stringify(edits)}`);
+const repeats = await page.evaluate(() => window.__repeats ?? []);
+ok(repeats.some((r) => r.repeat?.frequency === 0 && r.repeat?.interval === 1), `and set to repeat daily ${JSON.stringify(repeats)}`);
+ok((await field.inputValue()) === "", "the field is ready for the next one");
+
+await field.fill("Read chapter friday");
+await page.locator(".rx-add-understood").waitFor();
+await page.getByRole("button", { name: "Add as Typed" }).click();
+ok((await page.locator(".rx-add-understood").count()) === 0, "Add as Typed puts the reading away");
+await field.press("Enter");
+await page.waitForTimeout(600);
+const typed = await page.evaluate(() => window.__creates?.at(-1));
+ok(typed?.title === "Read chapter friday" && (typed?.dueAt ?? null) === null, `and the line is saved exactly as typed ${JSON.stringify(typed)}`);
+
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/reminders-repeat-end.mjs b/.uiverify/reminders-repeat-end.mjs
new file mode 100644
index 0000000..094022a
--- /dev/null
+++ b/.uiverify/reminders-repeat-end.mjs
@@ -0,0 +1,46 @@
+// End Repeat: ticking a repeating reminder for the last time before its end date completes it,
+// as the iPhone does — it leaves the list like any finished reminder and never comes back with
+// a date past its end. One with time left still rolls on. node .uiverify/reminders-repeat-end.mjs
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const b = await engine.launch();
+const ctx = await b.newContext({ viewport: { width: 1200, height: 800 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, remindersFixture: true });
+await ctx.addInitScript(() => {
+ const now = Math.floor(Date.now() / 1000);
+ const base = { listGuid: "l1", notes: null, allDay: false, completedAt: null, priority: 0, flagged: false, parentGuid: null, etag: null, recurFrequency: 0, recurInterval: 1 };
+ window.__extraReminders = [
+ { ...base, guid: "last", title: "Last antibiotic", dueAt: now + 3600 },
+ { ...base, guid: "more", title: "Take vitamins", dueAt: now + 3600 },
+ ];
+ // The backend's answer: "last" ends tonight, so its next would be past End Repeat.
+ window.__ending = ["last"];
+});
+const page = await ctx.newPage();
+page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });
+await page.goto(process.env.BASE ?? "http://localhost:4310", { waitUntil: "networkidle" });
+await openScreen(page, "Reminders");
+await page.locator(".rx-list", { hasText: "Daily" }).click();
+await page.waitForTimeout(400);
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+const row = (t) => page.locator(".rx-row", { has: page.getByLabel(`Rename ${t}`) });
+
+await row("Last antibiotic").locator(".rx-tick").click();
+await page.waitForTimeout(80);
+ok((await row("Last antibiotic").locator(".rx-tick").getAttribute("aria-checked")) === "true", "the last tick fills the circle at once");
+await page.waitForTimeout(1800);
+ok((await row("Last antibiotic").count()) === 0, "and it leaves the list, completed, like any finished reminder");
+const sent = await page.evaluate(() => window.__done ?? []);
+ok(sent.filter((d) => d.guid === "last").length === 1 && sent.find((d) => d.guid === "last").done === true, "one tick sent");
+await page.waitForTimeout(2000);
+ok((await row("Last antibiotic").count()) === 0, "and it never comes back with a date past its end");
+
+const before = await row("Take vitamins").innerText();
+await row("Take vitamins").locator(".rx-tick").click();
+await page.waitForTimeout(2600);
+ok((await row("Take vitamins").count()) === 1 && (await row("Take vitamins").locator(".rx-tick").getAttribute("aria-checked")) === "false", "one with time left still rolls on, open");
+ok((await row("Take vitamins").innerText()) !== before, "to its next date");
+console.log(failures ? `${failures} failed` : "all passed");
+process.exitCode = failures ? 1 : process.exitCode;
+await b.close();
diff --git a/.uiverify/reminders-repeat-tick.mjs b/.uiverify/reminders-repeat-tick.mjs
index 0c4c50c..cc05acf 100644
--- a/.uiverify/reminders-repeat-tick.mjs
+++ b/.uiverify/reminders-repeat-tick.mjs
@@ -13,7 +13,7 @@ await ctx.addInitScript(() => {
});
const page = await ctx.newPage();
page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });
-await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await page.goto(process.env.BASE ?? "http://localhost:4173", { waitUntil: "networkidle" });
await openScreen(page, "Reminders");
await page.locator(".rx-list", { hasText: "Daily" }).click();
await page.waitForTimeout(300);
diff --git a/.uiverify/reminders-sections.mjs b/.uiverify/reminders-sections.mjs
index f838257..0237e1f 100644
--- a/.uiverify/reminders-sections.mjs
+++ b/.uiverify/reminders-sections.mjs
@@ -45,17 +45,17 @@ ok(at("Return the library books") > at("## Errands") && at("Buy oat milk") < at(
ok(at("Fix the balcony light") > at("## At home"), "the last section holds its own");
ok(await page.locator(".rx-section.is-list-section").count() === 2, "two section headings");
-// The info panel names the section, read only while section writes are off.
+// The info panel names the section; section writes are on (proven on the iPhone).
await page.getByRole("button", { name: "Details for Buy oat milk" }).click();
await page.waitForTimeout(300);
const field = await page.locator(".rx-detail .rx-field", { hasText: "Section" }).innerText();
ok(field.includes("Errands"), `the info names its section ${JSON.stringify(field)}`);
-ok(await page.getByRole("button", { name: "Add Section" }).count() === 0, "no Add Section while section writes are off");
-// The row menu offers no section move while off.
+ok(await page.getByRole("button", { name: "Add Section" }).count() > 0, "Add Section is offered now section writes are on");
+// The row menu offers the move to a section.
await page.locator(".rx-row", { has: page.getByLabel("Rename Buy oat milk") }).click({ button: "right", position: { x: 300, y: 10 } });
await page.waitForTimeout(200);
const menu = await page.locator('[role="menu"] [role="menuitem"]').allInnerTexts();
-ok(!menu.some((m) => m.includes("Move to Section")), `no Move to Section while off ${JSON.stringify(menu)}`);
+ok(menu.some((m) => m.includes("Move to Section")), `Move to Section is offered ${JSON.stringify(menu)}`);
await page.keyboard.press("Escape");
// Smart views gather from every list and do not use a list's sections.
diff --git a/.uiverify/reminders-tags.mjs b/.uiverify/reminders-tags.mjs
index 7770ebe..f1b34b4 100644
--- a/.uiverify/reminders-tags.mjs
+++ b/.uiverify/reminders-tags.mjs
@@ -33,7 +33,7 @@ const shown = await page.locator(".rx-row .rx-title").evaluateAll((els) => els.m
ok(heading === "#home", `tapping a tag opens it ${heading}`);
ok(JSON.stringify(shown) === JSON.stringify(["Pick up the parcel", "Plan tomorrow"]), `and shows only what carries it ${JSON.stringify(shown)}`);
ok(await page.locator('.rx-tag-chip[aria-current="true"]', { hasText: "#home" }).count() === 1, "the open tag is marked in the sidebar");
-ok(await page.locator(".rx-add").count() === 0, "a tag view has no add field while tag writes are off");
+ok(await page.locator(".rx-add").count() === 1, "a tag view has its add field now tag writes are on");
// A chip on a row opens its tag too.
await row("Pick up the parcel").locator(".rx-meta .rx-tag", { hasText: "#errands" }).click();
await page.waitForTimeout(300);
@@ -57,19 +57,21 @@ await page.waitForTimeout(300);
await page.getByRole("button", { name: "Details for Pick up the parcel" }).click();
await page.waitForTimeout(300);
const panel = page.locator(".rx-detail");
-const early = await panel.locator(".rx-field", { hasText: "Early alert" }).innerText().catch(() => "");
-ok(early.includes("30 minutes early"), `the info shows the early alert ${JSON.stringify(early)}`);
-const link = panel.locator("a.rx-url");
-ok((await link.getAttribute("href")) === "https://www.apple.com/shop/order", "and the link, ready to open");
-ok((await link.innerText()) === "www.apple.com/shop/order", `shown without its scheme ${await link.innerText()}`);
+const early = await panel.locator(".rx-field", { hasText: "Early Reminder" }).innerText().catch(() => "");
+ok(early.includes("30 minutes before"), `the info shows the early alert ${JSON.stringify(early)}`);
+// Links can be changed (proven on the iPhone): the field holds it, Open opens it.
+const field = panel.getByLabel("URL for Pick up the parcel");
+ok((await field.inputValue()) === "https://www.apple.com/shop/order", "the link is in its field");
+ok((await panel.locator("a.rx-url-open").getAttribute("href")) === "https://www.apple.com/shop/order", "and Open opens it");
const tagsField = await panel.locator(".rx-tag-field .rx-tag-name").allInnerTexts();
ok(JSON.stringify(tagsField) === JSON.stringify(["#errands", "#home"]), `and its tags ${JSON.stringify(tagsField)}`);
-ok(await panel.locator(".rx-tag-remove, .rx-tag-input, input[type=url]").count() === 0, "no tag or link controls while those writes are off");
+ok(await panel.locator("input[type=url]").count() === 1, "the link can be changed now link writes are on");
// A reminder with none of these shows no empty rows for them.
await page.getByRole("button", { name: "Details for Plan tomorrow" }).click();
await page.waitForTimeout(300);
-ok(await page.locator(".rx-detail .rx-field", { hasText: "Early alert" }).count() === 0, "no Early alert row where there is none");
-ok(await page.locator(".rx-detail a.rx-url").count() === 0, "no URL row where there is none");
+// Early alerts can be set (proven on the iPhone): the row is there, at None, as on the phone.
+ok(/None/.test(await page.locator(".rx-detail .rx-field", { hasText: "Early Reminder" }).innerText().catch(() => "")), "an Early Reminder row at None where there is none");
+ok(await page.locator(".rx-detail a.rx-url-open").count() === 0, "no Open where there is no link");
ok(await page.locator(".rx-detail").count() === 1, "one info panel open at a time");
// Rules not read here are said, once.
diff --git a/.uiverify/search-perf.mjs b/.uiverify/search-perf.mjs
index e066dbf..7b80379 100644
--- a/.uiverify/search-perf.mjs
+++ b/.uiverify/search-perf.mjs
@@ -54,7 +54,7 @@ for (const word of ["marlowe", "zoya", "curtains"]) {
await field.fill("marlowe");
await page.waitForTimeout(400);
const panel = page.getByRole("listbox", { name: "Found" });
-const more = panel.getByRole("button", { name: /^Show all \d+ in Contacts/ });
+const more = panel.getByRole("option", { name: /^Show all \d+ in Contacts/ });
const t0 = Date.now();
await more.click();
await page.waitForFunction(() => document.querySelectorAll('#gsearch-results [role="option"]').length > 20);
diff --git a/.uiverify/settings-photo-cache.mjs b/.uiverify/settings-photo-cache.mjs
new file mode 100644
index 0000000..4432e29
--- /dev/null
+++ b/.uiverify/settings-photo-cache.mjs
@@ -0,0 +1,69 @@
+// Settings' Photos Cache: what the originals and previews take against the cap; the cap is a
+// ruler of the sizes offered, moved by the keys or a click on a size, sent once the hand stops;
+// a lower cap's trim reports back and the figure follows; Clear Cache lets go of them and says
+// how much; a disk short of space says the cap is held lower for now.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub } from "./stub.mjs";
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+const open = async (init) => {
+ const ctx = await b.newContext({ viewport: { width: 1180, height: 820 } });
+ if (init) await ctx.addInitScript(init);
+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });
+ const page = await ctx.newPage();
+ page.on("pageerror", (e) => ok(false, `page error: ${e.message}`));
+ await page.goto(process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
+ await page.locator(".sidebar-account").click();
+ await page.waitForSelector(".settings");
+ await page.locator(".settings-group[aria-label='Photos Cache']").waitFor();
+ return { ctx, page };
+};
+const heading = (page) => page.locator(".settings-heading", { hasText: "Photos Cache" }).innerText();
+
+{
+ const { ctx, page } = await open();
+ ok(/1\.8 GB of 2 GB/.test(await heading(page)), `the cache's use against its cap is on its heading ${JSON.stringify(await heading(page))}`);
+ const meter = page.getByRole("meter", { name: "Photos cache used" });
+ ok(Number(await meter.getAttribute("aria-valuenow")) === 88, "the meter fills to the share of the cap used");
+ const slider = page.getByLabel("Keep up to");
+ ok((await slider.getAttribute("aria-valuetext")) === "2 GB", "the ruler rests on the cap chosen, said in words");
+ // Two steps down by the keys: shown at once, sent once, after the hand stops.
+ await slider.focus();
+ await page.keyboard.press("ArrowLeft");
+ await page.keyboard.press("ArrowLeft");
+ ok(/of 512 MB/.test(await heading(page)) && (await page.evaluate(() => window.__capSets?.length ?? 0)) === 0, "the cap moves at once, nothing sent while it moves");
+ await page.waitForTimeout(500);
+ ok(JSON.stringify(await page.evaluate(() => window.__capSets)) === JSON.stringify([512 * 1024 ** 2]), "then the cap is sent, once");
+ await page.waitForTimeout(300);
+ ok(/^Photos Cache\s*461 MB of 512 MB$/.test((await heading(page)).trim()), `the trim a lower cap starts reports back ${JSON.stringify(await heading(page))}`);
+ // A size under the ruler, clicked.
+ await page.locator(".cap-ruler-stops button", { hasText: "10 GB" }).click();
+ await page.waitForTimeout(500);
+ ok((await page.evaluate(() => window.__capSets.at(-1))) === 10 * 1024 ** 3 && (await slider.getAttribute("aria-valuetext")) === "10 GB", "a size under the ruler sets it");
+ // Clear Cache.
+ const clear = page.getByRole("button", { name: "Clear Cache" });
+ ok(!(await clear.isDisabled()), "with something cached, Clear Cache is offered");
+ await clear.click();
+ await page.waitForTimeout(200);
+ const row = await page.locator(".settings-row", { hasText: "Clear Cache" }).innerText();
+ ok((await page.evaluate(() => window.__cacheCleared)) === 1 && /Cleared 461 MB/.test(row), `Clear Cache asks once and says what it freed ${JSON.stringify(row)}`);
+ ok(await clear.isDisabled(), "and rests with nothing left");
+ const labels = await page.locator(".settings button").allInnerTexts();
+ ok(!labels.some((l) => /…|\.\.\./.test(l)), "no button label trails off");
+ await ctx.close();
+}
+{
+ // A disk short of space: said plainly, and true.
+ const { ctx, page } = await open(() => {
+ window.__cache = { used: 900_000_000, cap: 5 * 1024 ** 3, limit: 1_200_000_000, thumbnails: 1, steps: [512 * 1024 ** 2, 1024 ** 3, 2 * 1024 ** 3, 5 * 1024 ** 3] };
+ window.__cacheClearFail = "The photo cache could not be read.";
+ });
+ ok((await page.locator(".settings-group[aria-label='Photos Cache']").innerText()).includes("Using up to 1.1 GB for now, to leave room on this disk."), "a disk short of space says the cap is held lower for now");
+ await page.getByRole("button", { name: "Clear Cache" }).click();
+ await page.waitForTimeout(200);
+ ok((await page.locator(".toast.is-error").innerText()).includes("could not be read"), "a failed clear says why");
+ await ctx.close();
+}
+await b.close();
+process.exitCode = failures ? 1 : (process.exitCode ?? 0);
diff --git a/.uiverify/settings.mjs b/.uiverify/settings.mjs
index 671cf72..cb38a5d 100644
--- a/.uiverify/settings.mjs
+++ b/.uiverify/settings.mjs
@@ -8,7 +8,7 @@ const b = await engine.launch();
const ctx = await b.newContext({ viewport: { width: 1180, height: 820 } });
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 page.goto(process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
await page.waitForTimeout(400);
let failures = 0;
const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
@@ -96,7 +96,7 @@ ok((await page.locator(".sidebar-account .account-avatar").innerText()).trim() =
await c2.addInitScript(() => { window.__webAccess = false; });
await c2.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, remindersFixture: true });
const p2 = await c2.newPage();
- await p2.goto("http://localhost:4173", { waitUntil: "networkidle" });
+ await p2.goto(process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
await p2.waitForTimeout(500);
ok(await p2.getByText("Access iCloud Data on the Web").first().isVisible(), "web access off says how to turn it on, instead of failing screen by screen");
await c2.close();
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index 6abd507..a8d197d 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -11,7 +11,7 @@ export const SERVICES = ["account","archivews","calendar","ckdatabasews","ckdevi
value it needs must arrive through the single argument. */
/* Fixture events, so the agenda's rendering is verified without inventing rows in anyone's
real library. Times are unix seconds relative to now. */
-export function installStub({ screen, services, twoFactor, calendarFixture, notesFixture, contactsFixture, driveFixture, remindersFixture, demoFixture }) {
+export function installStub({ screen, services, twoFactor, calendarFixture, notesFixture, contactsFixture, driveFixture, remindersFixture, demoFixture, extraEvents = [] }) {
const HOUR = 3600, DAY = 86400;
// Today at 9 in the morning, on this machine's clock. Counted from UTC's midnight it was
// yesterday for the first hours after local midnight in a zone east of UTC — and the
@@ -42,6 +42,11 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
{ guid: "quince:holidays:diwali:2026", calendarGuid: "quince:holidays", title: "Diwali",
location: null, startsAt: localDay(5), endsAt: localDay(6), allDay: true,
timezone: null, url: null, notes: null, etag: null },
+ // A suite's own events, placed `day`/`hour` from today at 9 AM, with fields as given.
+ ...extraEvents.map(({ day = 0, hour = 0, length = 1, ...rest }) => ({
+ calendarGuid: "work", location: null, allDay: false, timezone: null, url: null, notes: null, etag: null,
+ startsAt: base + day * DAY + hour * HOUR, endsAt: base + day * DAY + (hour + length) * HOUR, ...rest,
+ })),
];
const dueReminders = !calendarFixture ? [] : [
{ guid: "r1", listGuid: "l1", title: "Water the plants", notes: null,
@@ -85,7 +90,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
{ guid: "c4", firstName: null, lastName: null, company: null, isCompany: false,
birthday: null, notes: null, etag: null,
methods: [{ kind: "phone", label: null, value: "+91 90000 11111" }] },
- ];
+ ].concat(contactsFixture ? (window.__contactsExtra ?? []) : []);
const driveItems = !driveFixture ? [] : [
{ drivewsid: "FOLDER::a", parentId: null, name: "Downloads", extension: null,
kind: "FOLDER", size: null, childCount: 3, createdAt: 1785000000,
@@ -232,6 +237,8 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
}
case "event_repeat": return String(args.guid).startsWith("SERIES__") ? { freq: "weekly", interval: 1, count: null } : null;
case "event_alerts": return args.guid === "e2" ? [15] : [];
+ // A test sets __guests[guid] to give an event its guests.
+ case "event_guests": return (window.__guests ?? {})[args.guid] ?? [];
case "event_save": (window.__eventSaves ??= []).push(args.draft); return "E-new";
case "event_delete": (window.__eventDeletes ??= []).push(args); return null;
case "calendar_sync": return { calendars: calendars.length, events: events.length };
@@ -248,10 +255,15 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
case "reminders_due_between": return calendarFixture ? dueReminders : [];
case "reminder_create":
// Kept, as Apple keeps it, with what the view implied.
- reminderItems.push({ guid: `made-${reminderItems.length}`, listGuid: args.listGuid, title: args.title,
- notes: null, dueAt: args.dueAt ?? null, allDay: args.allDay ?? false, completedAt: null, priority: 0,
- flagged: args.flagged ?? false, parentGuid: null, etag: null });
- return null;
+ {
+ const guid = `made-${reminderItems.length}`;
+ (window.__creates ??= []).push(args);
+ reminderItems.push({ guid, listGuid: args.listGuid, title: args.title,
+ notes: null, dueAt: args.dueAt ?? null, allDay: args.allDay ?? false, completedAt: null, priority: 0,
+ flagged: args.flagged ?? false, parentGuid: null, etag: null });
+ // Its new id, as the app's command answers.
+ return guid;
+ }
case "reminder_delete": return null;
case "reminder_set_done":
(window.__done ??= []).push(args);
@@ -260,14 +272,40 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
{
// A repeating one rolls on, as Apple rolls it: open again, a day (or its unit) on.
const r = (window.__extraReminders ?? []).find((x) => x.guid === args.guid);
- if (r && r.recurFrequency !== null && r.recurFrequency !== undefined && args.done) r.dueAt += 86400 * (r.recurInterval ?? 1);
+ // Its last time before End Repeat (__ending): completed, as Apple completes it.
+ const last = (window.__ending ?? []).includes(args.guid);
+ if (r && last && args.done) { r.completedAt = Math.floor(Date.now() / 1000); window.__ending = window.__ending.filter((g) => g !== args.guid); }
+ else if (r && r.recurFrequency !== null && r.recurFrequency !== undefined && args.done) r.dueAt += 86400 * (r.recurInterval ?? 1);
}
return null;
- case "reminder_set_repeat": return null;
+ case "reminder_set_repeat": {
+ (window.__repeats ??= []).push(args);
+ // Kept, as Apple keeps it: the rule on the reminder, and its end beside it.
+ const r = [...reminderItems, ...(window.__extraReminders ?? [])].find((x) => x.guid === args.guid);
+ if (r) { r.recurFrequency = args.repeat?.frequency ?? null; r.recurInterval = args.repeat?.interval ?? null; }
+ const more = (window.__more ??= {})[args.guid];
+ if (more) more.repeat = args.repeat ? { ...args.repeat, endAt: args.endAt ?? null, occurrenceCount: 0, daysOfWeek: args.daysOfWeek ?? [], other: [] } : null;
+ ((window.__marks ??= {})[args.guid] ??= {}).daysOfWeek = args.repeat ? (args.daysOfWeek ?? []) : [];
+ return null;
+ }
+ // The rest of a reminder's Details (reminders_cmds.rs reminder_more). A test sets
+ // __more[guid] to give one a place, a person, Urgent, a zone or a rule with chosen days.
+ case "reminders_ending": return window.__ending ?? [];
+ // Row marks (reminders_cmds.rs reminder_marks): a test sets __marks[guid].
+ case "reminder_marks":
+ return args.guids.filter((g) => (window.__marks ?? {})[g]).map((g) => ({ guid: g, daysOfWeek: [], urgent: false,
+ location: null, messaging: null, url: null, ...window.__marks[g] }));
+ case "reminder_more": {
+ const r = [...reminderItems, ...(window.__extraReminders ?? [])].find((x) => x.guid === args.guid);
+ const base = { guid: args.guid, repeat: r && r.recurFrequency != null ? { frequency: r.recurFrequency, interval: r.recurInterval ?? 1, endAt: null, occurrenceCount: 0,
+ daysOfWeek: (window.__marks ?? {})[args.guid]?.daysOfWeek ?? [], other: [] } : null,
+ timeZone: r?.timezone ?? null, urgent: false, location: null, messaging: null };
+ return { ...base, ...((window.__more ?? {})[args.guid] ?? {}) };
+ }
case "reminder_edit": {
(window.__edits ??= []).push(args.edit);
// Kept, as Apple keeps it, so the read after a write shows the write.
- const r = reminderItems.find((x) => x.guid === args.guid);
+ const r = [...reminderItems, ...(window.__extraReminders ?? [])].find((x) => x.guid === args.guid);
if (r) for (const [k, v] of Object.entries(args.edit)) if (k !== "listGuid") r[k] = v;
return null;
}
@@ -297,7 +335,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
const every = [...reminderItems, ...(window.__extraReminders ?? [])];
if (cmd === "reminder_detail") {
const extra = (window.__details ?? (remindersFixture ? { r2: { url: "https://www.apple.com/shop/order", earlyAlerts: [{ id: "a1", count: 30, unit: 0 }] } } : {}))[args.guid] ?? {};
- return { guid: args.guid, tags: tagMap[args.guid] ?? [], url: null, earlyAlerts: [], otherAttachments: 0, ...extra };
+ return { guid: args.guid, tags: tagMap[args.guid] ?? [], url: null, earlyAlerts: [], otherAttachments: 0, images: [], ...extra };
}
const open = (name) => every.filter((r) => !r.completedAt && (tagMap[r.guid] ?? []).some((t) => t.toLowerCase() === name.toLowerCase()));
if (cmd === "reminders_tagged") return open(args.name);
@@ -346,6 +384,16 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
return lines.map((l, i) => ({ length: l.length + (i < lines.length - 1 ? 1 : 0), style: i === 0 ? 0 : null, indent: 0,
checked: null, bold: false, italic: false, underline: false, strike: false, link: null, ...(i === 2 ? { quote: true } : {}) }));
}
+ if (args.guid === "nA") {
+ // Shaped like a real note made on a phone (text made generic): Apple's runs come in
+ // pieces — a word split in two, a sentence in five — that say nothing more than one
+ // run would. Eight attachments on their own lines, a sentence, then a ninth.
+ const plain = (length) => ({ length, style: null, indent: 0, checked: null, bold: false, italic: false, underline: false, strike: false, link: null });
+ const att = (id) => ({ ...plain(1), attachment: id });
+ const lines = [];
+ for (let i = 1; i <= 8; i++) lines.push(att(`A${i}`), plain(1));
+ return [plain(10), plain(1), plain(1), ...lines, plain(2), plain(10), plain(8), plain(5), plain(1), plain(1), att("A9")];
+ }
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 });
@@ -383,8 +431,18 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
}
// Adding files: off unless a test turns it on (`__attachOn`), as the backend's switch is.
case "note_attach_enabled": return Boolean(window.__attachOn);
+ // A picture of the file being added: a tiny generated PNG, or none (__attachPreview false).
+ case "note_attach_preview": {
+ if (window.__attachPreview === false) return new ArrayBuffer(0);
+ const c = document.createElement("canvas"); c.width = 8; c.height = 8;
+ const g = c.getContext("2d"); g.fillStyle = "#2f9bff"; g.fillRect(0, 0, 8, 8);
+ const blob = await new Promise((r) => c.toBlob(r, "image/png"));
+ return await blob.arrayBuffer();
+ }
case "note_attach_file": {
(window.__attaches ??= []).push(args);
+ // A slow upload, when a test asks for one.
+ if (window.__attachDelay) await new Promise((r) => setTimeout(r, window.__attachDelay));
const n = noteList.find((x) => x.guid === args.guid);
const base = args.base ?? n?.body ?? "";
const body = base.slice(0, args.atOffset) + "\uFFFC" + base.slice(args.atOffset);
@@ -446,6 +504,10 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
if (window.__linkNote && !noteList.some((n) => n.guid === "nL"))
noteList.unshift({ guid: "nL", folderGuid: "f1", title: "Links", snippet: "", body: "Links\nYashps://www.youtube.com/watch?v=5vVh0ZGx8aU\nRead https://example.org/a. Done",
locked: false, editable: true, pinned: false, createdAt: null, modifiedAt: 1789200000, etag: null });
+ // Opt-in: a note of pictures, files, a recording, a film and a table, as a phone makes one.
+ if (window.__attachNote && !noteList.some((n) => n.guid === "nA"))
+ noteList.unshift({ guid: "nA", folderGuid: "f1", title: "Attachments", snippet: "", body: `Attachments\n${"\uFFFC\n".repeat(8)}A few words to try it out \n\uFFFC`,
+ locked: false, editable: true, pinned: false, createdAt: null, modifiedAt: 1789500000, 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 });
@@ -455,13 +517,34 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
locked: true, editable: false, pinned: false, createdAt: null, modifiedAt: 1789400000, etag: null });
return !notesFixture ? [] : noteList.map((n) => ({ ...n }));
case "note_attachment_info":
+ if (/^A\d$/.test(String(args.id))) {
+ (window.__infoAsks ??= []).push(args.id);
+ // `__flakyInfo[id] = n`: the first n lookups of it fail, as one offline or mid-renewal does.
+ if (window.__flakyInfo?.[args.id] > 0) { window.__flakyInfo[args.id] -= 1; throw "Apple couldn’t be reached."; }
+ const A = {
+ A1: { uti: "com.apple.m4a-audio", kind: "audio", filename: "recording.m4a", size: 48200 },
+ A2: { uti: "public.json", kind: "file", filename: "servers.json", size: 2100 },
+ A3: { uti: "com.apple.quicktime-movie", kind: "video", filename: "IMG_0001.mov", size: 8_400_000, width: 1080, height: 1920, hasPreview: true },
+ A4: { uti: "public.heic", kind: "image", filename: "IMG_0002.HEIC", width: 3024, height: 4032, size: 1_900_000, hasPreview: true },
+ A5: { uti: "public.heic", kind: "image", filename: "IMG_0003.HEIC", width: 4032, height: 3024, size: 2_100_000, hasPreview: true },
+ A6: { uti: "com.apple.paper.doc.pdf", kind: "document", filename: "Form.pdf", size: 120_000, hasPreview: true },
+ A7: { uti: "public.jpeg", kind: "image", filename: "IMG_0004.JPG", width: 1200, height: 800, size: 310_000, hasPreview: true },
+ A8: { uti: "com.apple.notes.table", kind: "table", size: 1116 },
+ A9: { uti: "public.png", kind: "image", filename: "new.png", width: 800, height: 600, size: 52_000, hasPreview: true },
+ }[args.id];
+ const info = { id: args.id, title: null, width: null, height: null, size: null, hasPreview: false, filename: null, ...A };
+ return window.__slowInfo ? new Promise((r) => setTimeout(() => r(info), window.__slowInfo)) : info;
+ }
if (args.id === "D1") return { id: "D1", uti: "com.apple.paper", kind: "drawing", filename: null, title: null, width: 768, height: 621, size: null, hasPreview: true };
if (args.id === "U1") return { id: "U1", uti: "com.apple.notes.table", kind: "table", filename: null, title: null, width: null, height: null, size: 1116, hasPreview: false };
+ // Any other id a table is drawn for (note_table answers it): a table, as the backend
+ // describes one (note_media.rs kind_of: com.apple.notes.table → "table").
+ if (!/^M[12]$/.test(String(args.id))) return { id: args.id, uti: "com.apple.notes.table", kind: "table", filename: null, title: null, width: null, height: null, size: 1116, hasPreview: false };
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 (/^[MDU]/.test(String(args.id))) return null; return (window.__table ??= [["Item", "Qty"], ["Milk", "2"], ["", ""]]).map((r) => r.slice());
+ case "note_table": if (/^[MDU]/.test(String(args.id)) || /^A[1-79]$/.test(String(args.id))) return null; return (window.__table ??= [["Item", "Qty"], ["Milk", "2"], ["", ""]]).map((r) => r.slice());
case "photos_list": case "photos_counts": {
const P = (id, takenAt, extra = {}) => ({ id, master: `m${id}`, takenAt, addedAt: takenAt, kind: "image",
width: 4032, height: 3024, duration: null, filename: `IMG_${id}.JPG`, size: 2400000, uti: "public.jpeg",
@@ -485,6 +568,41 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
if (window.__slowView === args.view) return new Promise((r) => setTimeout(() => r(answer), 600));
return answer;
}
+ // Paged: the index (ids, grouping dates, marks), the first page, and photos by id — each
+ // made from the same lists the whole-list commands answer, sorted as the backend sorts.
+ case "photos_index": case "photos_page": {
+ const self = window.__TAURI_INTERNALS__.invoke;
+ const src = args.source;
+ let list = src.view ? await self("photos_list", { view: src.view })
+ : src.album ? await self("photos_in_album", { album: src.album })
+ : src.query ? await self("photos_search", { query: src.query })
+ : await self("photos_burst", { burst: src.burst });
+ const sortable = src.view && src.view !== "rated" && src.view !== "recentlyDeleted";
+ const order = sortable ? args.order : null;
+ const key = (p) => (order?.by === "added" || (!order && src.view === "recents") ? (p.addedAt ?? p.takenAt) : p.takenAt);
+ if (order) list = [...list].sort((a, b) => (key(b) - key(a)) * (order.oldest ? -1 : 1) || (a.id < b.id ? -1 : 1));
+ if (cmd === "photos_page") return list.slice(args.offset, args.offset + args.limit);
+ (window.__indexReads ??= []).push(src);
+ // A large library's index takes a moment: a test can make it take one.
+ if (window.__indexDelay) await new Promise((r) => setTimeout(r, window.__indexDelay));
+ const taken = list.map((p) => p.takenAt);
+ return {
+ ids: list.map((p) => p.id),
+ keys: list.map(key),
+ marks: list.map((p) => (p.kind === "video" ? 1 : p.kind === "live" ? 2 : 0) | (p.favorite ? 4 : 0) | ((p.rating ?? 0) << 3)),
+ first: taken.length ? Math.min(...taken) : null,
+ last: taken.length ? Math.max(...taken) : null,
+ };
+ }
+ case "photos_get": {
+ (window.__gets ??= []).push(args.ids.length);
+ const all = window.__photos ?? [];
+ const burst = window.__burstShots ?? [];
+ // Made once per fixture: rebuilt per call, the stub's own work showed as the grid's.
+ if (window.__byIdOf?.all !== all || window.__byIdOf?.burst !== burst) window.__byIdOf = { all, burst, map: new Map([...burst, ...all].map((p) => [p.id, p])) };
+ const byId = window.__byIdOf.map;
+ return args.ids.map((id) => byId.get(id)).filter(Boolean).map((p) => ({ ...p }));
+ }
case "photos_prepare": (window.__prepared ??= []).push(args.shown); return null;
case "photos_shared_albums": return [...(window.__shared ??= [])];
case "photos_shared_create": {
@@ -503,7 +621,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
const pick = (window.__photos ?? []).find((p) => p.burst === args.burst);
if (!pick) return [];
const shot = (n) => ({ ...pick, id: `${pick.id}-s${n}`, burstPick: false, takenAt: pick.takenAt - 1 + n, filename: `IMG_burst_${n}.JPG` });
- return [shot(0), { ...pick }, shot(2)].map((p) => ({ ...p, burstCount: 3 }));
+ return (window.__burstShots = [shot(0), { ...pick }, shot(2)].map((p) => ({ ...p, burstCount: 3 })));
}
case "photos_albums": {
const albums = (window.__albums ??= [{ id: "AL1", name: "Trips", position: 0, changeTag: null, items: ["p4", "p2"] }]);
@@ -606,6 +724,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
}
case "photo_play": (window.__plays ??= []).push(args); return null;
case "video_base": return window.__videoBase ?? null;
+ case "video_support": return window.__videoSupport ?? { h264: true, hevc: true, missing: [] };
case "window_tint": (window.__tints ??= []).push(args.rgb.join(",")); return null;
case "window_fullscreen": (window.__fullscreen ??= []).push(args.on); return args.on;
case "photo_download": (window.__downloads ??= []).push(args); return `/home/test/Downloads/IMG_${args.id}.JPG`;
@@ -659,7 +778,46 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
}
case "contact_save": (window.__contactSaves ??= []).push(args); return "C-new";
case "contact_delete": (window.__contactDeletes ??= []).push(args); return null;
- case "contacts_list": return !contactsFixture ? [] : contactList;
+ case "contacts_list": return !contactsFixture ? [] : contactList.slice();
+ // Duplicates as contacts_merge.rs finds them, on the fixture: a shared number (its
+ // last ten digits), a shared email, or the same name.
+ case "contacts_duplicates": {
+ const keys = (c) => [
+ ...[c.firstName, c.middleName, c.lastName].filter(Boolean).join(" ").toLowerCase().trim() ? [`name:${[c.firstName, c.middleName, c.lastName].filter(Boolean).join(" ").toLowerCase().trim()}`] : [],
+ ...(c.methods ?? []).filter((m) => m.kind === "phone").map((m) => m.value.replace(/\D/g, "")).filter((d) => d.length >= 7).map((d) => `phone:${d.slice(-10)}`),
+ ...(c.methods ?? []).filter((m) => m.kind === "email").map((m) => `email:${m.value.trim().toLowerCase()}`),
+ ];
+ const groups = [];
+ for (const c of contactList) {
+ const mine = keys(c);
+ const g = groups.find((x) => x.keys.some((k) => mine.includes(k)));
+ if (g) { g.guids.push(c.guid); for (const k of mine) if (g.keys.includes(k)) g.shared.add(k.split(":")[0]); g.keys.push(...mine); }
+ else groups.push({ guids: [c.guid], keys: mine, shared: new Set() });
+ }
+ return groups.filter((g) => g.guids.length > 1).map((g) => ({ guids: g.guids, reasons: ["name", "phone", "email"].filter((r) => g.shared.has(r)) }));
+ }
+ case "contacts_merge": {
+ (window.__merges ??= []).push(args);
+ const cards = args.guids.map((id) => contactList.find((c) => c.guid === id)).filter(Boolean);
+ const kept = { ...cards[0], methods: [...cards[0].methods] };
+ for (const o of cards.slice(1)) {
+ for (const k of ["firstName", "lastName", "company", "birthday", "jobTitle", "nickname"]) if (!kept[k] && o[k]) kept[k] = o[k];
+ const key = (m) => `${m.kind}:${m.kind === "phone" ? m.value.replace(/\D/g, "").slice(-10) : m.value.trim().toLowerCase()}`;
+ for (const m of o.methods) if (!kept.methods.some((x) => key(x) === key(m))) kept.methods.push(m);
+ if (o.notes && !(kept.notes ?? "").includes(o.notes)) kept.notes = kept.notes ? `${kept.notes}\n\n${o.notes}` : o.notes;
+ }
+ (window.__mergeUndo ??= {})[kept.guid] = contactList.slice();
+ contactList.splice(0, contactList.length, ...contactList.filter((c) => !args.guids.includes(c.guid) || c.guid === kept.guid).map((c) => (c.guid === kept.guid ? kept : c)));
+ return kept.guid;
+ }
+ case "contacts_merge_undo": {
+ (window.__mergeUndos ??= []).push(args);
+ const before = window.__mergeUndo?.[args.kept];
+ if (!before || window.__mergeSent) return false;
+ contactList.splice(0, contactList.length, ...before);
+ delete window.__mergeUndo[args.kept];
+ return true;
+ }
case "contact_me": return window.__me ?? (contactsFixture ? "c1" : null);
case "contact_set_me": await new Promise((r) => setTimeout(r, 600)); window.__me = args.guid; return null;
case "contacts_export": (window.__exports ??= []).push(args); return `/home/test/Downloads/${args.fileName}`;
@@ -674,6 +832,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
case "photos_folder_status": return window.__photosFolder ??= { on: false, path: "/home/test/iCloud Photos", problem: null };
case "photos_folder_set": return (window.__photosFolder = { on: args.on, path: "/home/test/iCloud Photos", problem: null });
case "photos_folder_open": (window.__opened ??= []).push("photos"); return null;
+ case "photo_video_zoom": return window.__zoom ?? 1;
case "photo_video_turn": (window.__turnAsks ??= []).push(args); return window.__turn ?? [1, 0, 0, 1];
case "contacts_import": (window.__imports ??= []).push(args); return window.__importAnswer ?? [2, 0, 0];
case "plugin:dialog|open": return window.__pick ?? null;
@@ -714,6 +873,23 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
window.__cleared = (window.__cleared ?? 0) + 1;
return (window.__local = { ...l, photos: l.photos - (l.clearable - l.notes - 3_000), notes: 0, drive: l.drive - 3_000, total: l.total - l.clearable, clearable: 0 });
}
+ // Photos Cache: a cap set lets the longest unseen go in the background, reported as an event.
+ case "photos_cache_status": case "photos_cache_set": case "photos_cache_clear": {
+ const GB = 1024 ** 3;
+ const c = (window.__cache ??= { used: 1_900_000_000, cap: 2 * GB, limit: 2 * GB, thumbnails: 160_000_000,
+ steps: [512 * 1024 ** 2, GB, 2 * GB, 5 * GB, 10 * GB, 20 * GB, 50 * GB] });
+ if (cmd === "photos_cache_set") {
+ (window.__capSets ??= []).push(args.bytes);
+ c.cap = c.limit = args.bytes;
+ if (c.used > c.cap) setTimeout(() => { c.used = Math.floor(c.cap * 0.9); window.__emit?.("quince://photo-cache", { ...c }); }, 100);
+ }
+ if (cmd === "photos_cache_clear") {
+ if (window.__cacheClearFail) throw window.__cacheClearFail;
+ window.__cacheCleared = (window.__cacheCleared ?? 0) + 1;
+ c.used = 0;
+ }
+ return { ...c };
+ }
case "alerts_shown": return window.__alertsShown ?? true;
case "diagnostics_save": (window.__diagnostics = (window.__diagnostics ?? 0) + 1); return "/home/user/Downloads/Skykeep 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 };
@@ -812,6 +988,11 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
case "account_unsent": return window.__unsent ?? { changes: 0, files: 0, photos: 0 };
// Changes waiting for Apple, and ones it refused: a test sets `window.__outbox`.
case "outbox_status": return window.__outbox ?? { waiting: [], refused: [] };
+ // The desktop's Increase Contrast, from the Settings portal (appearance.rs).
+ case "system_contrast": return window.__contrast ?? false;
+ // LC_TIME, LANG (appearance.rs): null leaves the engine's own language.
+ case "system_time_locale": return window.__timeLocale ?? null;
+ case "network_reach": return { apple: ["apple.com", "icloud.com", "icloud-content.com", "apple.com.cn", "icloud.com.cn", "icloud-content.com.cn"], subscribed: window.__reachSubscribed ?? [] };
case "outbox_resend": case "outbox_discard": {
(window.__outboxCalls ??= []).push([cmd, args.id]);
if (window.__outbox) window.__outbox = { ...window.__outbox, refused: window.__outbox.refused.filter((r) => r.id !== args.id) };
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
new file mode 100644
index 0000000..6537030
--- /dev/null
+++ b/ARCHITECTURE.md
@@ -0,0 +1,69 @@
+# Architecture
+
+How Skykeep is put together, in one page. Where each folder is lives in the
+[code map](.github/CONTRIBUTING.md#code-map); this page is how a change moves through them.
+
+## The shape
+
+```text
+ window (React, src/) the app (Tauri, src-tauri/src/) Apple
+ ─────────────────── ──────────────────────────────── ─────
+ screens read the library ──▶ commands ──▶ quince-core (SQLite)
+ a write is a command ──▶ outbox.rs: record + lay over library
+ worker sends, oldest first ──────────▶ iCloud services
+ push.rs / refresh.rs: changes in ◀──── push, polls
+```
+
+Five crates sit under the app:
+
+- **quince-auth** signs in (Apple's SRP and two-factor), keeps the session in the system keyring,
+ and builds every HTTP client. `apple_only()` refuses any host outside Apple's domains before a
+ connection exists; `listed_only()` reaches only the calendars you subscribed to.
+- **quince-icloud** speaks each service: CloudKit records for Notes, Reminders and Photos,
+ Apple's web APIs for Calendar, Contacts and Drive, and the push channel. It parses and writes;
+ it stores nothing.
+- **quince-core** is the library: one SQLite file, its migrations (`schema.rs`), the full-text
+ search index, the outbox queue, and export.
+- **quince-vfs** shows Drive and Photos as folders through FUSE (Linux).
+- **quince-media** decodes pictures, HEIC included, and makes thumbnails.
+
+## Reading
+
+Every screen reads the library, never Apple. A sync pass (`refresh.rs`) fetches what changed,
+stores it, then lays every change still waiting in the outbox back over what it stored, so a
+pass never shows an older version over an edit you made. Then the window hears
+`quince://synced` and the open screens read again. Push (`push.rs`) decides *when* a pass runs:
+Apple's push socket for Notes, Reminders and Photos; short polls for Calendar and Contacts,
+slower when no window is open or the computer is on its battery.
+
+## Writing
+
+A write is recorded and shown in one transaction, then sent behind the window:
+
+1. A command (`main.rs`, `contacts_cmds.rs`, …) calls `outbox::record_*`, which appends the
+ change to the queue and lays it over the library at once. Every view shows it.
+2. The worker in `outbox.rs` sends each service's queue in the order it was made. Taken: off the
+ queue, and one pass reads Apple's own version. Unreachable: kept and retried with a growing
+ wait, and at once when the network comes back. Refused for good: kept with what was typed,
+ and the window shows why, with Try Again and Discard.
+3. Every change is safe to send twice: a new record carries the name it was given here, and
+ edits are merges against the version they were made from.
+
+Card addresses, reminder ticks, note moves, event edits with their repeat scope: each is its
+own kind of change in the queue, with its own `lay` and `send`.
+
+## Windows and apps
+
+One process, one library. The whole-library window and each app's own window (Notes, Reminders,
+Calendar, Contacts, Drive, Photos; `apps.rs`) are webviews over the same commands. A screen
+once opened is kept mounted and inert while another is in front, so coming back is instant.
+
+## Where to look first
+
+| To change | Start in |
+|---|---|
+| What Apple sends or accepts | `crates/quince-icloud/src/<service>.rs` |
+| What is stored | `crates/quince-core/src/schema.rs`, then the service's file there |
+| How a write behaves offline | `src-tauri/src/outbox.rs` |
+| When syncing happens | `src-tauri/src/push.rs`, `refresh.rs` |
+| A screen | `src/screens/`, its types in `src/lib/ipc.ts`, its suite in `.uiverify/` |
diff --git a/Cargo.lock b/Cargo.lock
index d024d62..e0678c3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -103,6 +103,15 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
+[[package]]
+name = "arc-swap"
+version = "1.9.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "380962b3d93b99642e50b9febf72c071e97e8b32d86eae9cf4ef582bb960ae6e"
+dependencies = [
+ "rustversion",
+]
+
[[package]]
name = "assert-json-diff"
version = "2.0.2"
@@ -297,6 +306,12 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+[[package]]
+name = "base16ct"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf"
+
[[package]]
name = "base64"
version = "0.21.7"
@@ -315,6 +330,12 @@ version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
+[[package]]
+name = "base64ct"
+version = "1.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
+
[[package]]
name = "bit-set"
version = "0.8.0"
@@ -653,6 +674,12 @@ dependencies = [
"crossbeam-utils",
]
+[[package]]
+name = "const-oid"
+version = "0.9.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
+
[[package]]
name = "cookie"
version = "0.18.2"
@@ -786,12 +813,33 @@ dependencies = [
"crossbeam-utils",
]
+[[package]]
+name = "crossbeam-queue"
+version = "0.3.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae"
+dependencies = [
+ "crossbeam-utils",
+]
+
[[package]]
name = "crossbeam-utils"
version = "0.8.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
+[[package]]
+name = "crypto-bigint"
+version = "0.5.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76"
+dependencies = [
+ "generic-array",
+ "rand_core 0.6.4",
+ "subtle",
+ "zeroize",
+]
+
[[package]]
name = "crypto-common"
version = "0.1.7"
@@ -874,6 +922,12 @@ dependencies = [
"syn 3.0.5",
]
+[[package]]
+name = "data-encoding"
+version = "2.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
+
[[package]]
name = "dbus"
version = "0.9.12"
@@ -952,6 +1006,16 @@ dependencies = [
"thiserror 2.0.20",
]
+[[package]]
+name = "der"
+version = "0.7.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
+dependencies = [
+ "const-oid",
+ "zeroize",
+]
+
[[package]]
name = "deranged"
version = "0.5.8"
@@ -989,6 +1053,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
+ "const-oid",
"crypto-common",
"subtle",
]
@@ -1120,12 +1185,45 @@ version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
+[[package]]
+name = "ecdsa"
+version = "0.16.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca"
+dependencies = [
+ "der",
+ "digest",
+ "elliptic-curve",
+ "rfc6979",
+ "signature",
+ "spki",
+]
+
[[package]]
name = "either"
version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
+[[package]]
+name = "elliptic-curve"
+version = "0.13.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47"
+dependencies = [
+ "base16ct",
+ "crypto-bigint",
+ "digest",
+ "ff",
+ "generic-array",
+ "group",
+ "pkcs8",
+ "rand_core 0.6.4",
+ "sec1",
+ "subtle",
+ "zeroize",
+]
+
[[package]]
name = "embed-resource"
version = "3.0.11"
@@ -1270,6 +1368,16 @@ dependencies = [
"simd-adler32",
]
+[[package]]
+name = "ff"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393"
+dependencies = [
+ "rand_core 0.6.4",
+ "subtle",
+]
+
[[package]]
name = "field-offset"
version = "0.3.6"
@@ -1579,6 +1687,7 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
+ "zeroize",
]
[[package]]
@@ -1793,6 +1902,17 @@ dependencies = [
"system-deps 9.0.0",
]
+[[package]]
+name = "group"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63"
+dependencies = [
+ "ff",
+ "rand_core 0.6.4",
+ "subtle",
+]
+
[[package]]
name = "gstreamer"
version = "0.25.4"
@@ -2149,7 +2269,7 @@ dependencies = [
"tokio",
"tokio-rustls",
"tower-service",
- "webpki-roots",
+ "webpki-roots 1.0.10",
]
[[package]]
@@ -2596,6 +2716,26 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "ksni"
+version = "0.3.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1bcc1cb43797140f74b711f1c4a49f48a7a7429f211c5fb78264e7bcd1e99caf"
+dependencies = [
+ "arc-swap",
+ "async-executor",
+ "async-io",
+ "async-lock",
+ "crossbeam-queue",
+ "futures-channel",
+ "futures-lite",
+ "futures-util",
+ "pastey",
+ "serde",
+ "task-local",
+ "zbus 5.19.0",
+]
+
[[package]]
name = "kstring"
version = "2.0.5"
@@ -3310,6 +3450,18 @@ dependencies = [
"pin-project-lite",
]
+[[package]]
+name = "p256"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b"
+dependencies = [
+ "ecdsa",
+ "elliptic-curve",
+ "primeorder",
+ "sha2",
+]
+
[[package]]
name = "page_size"
version = "0.6.0"
@@ -3466,6 +3618,16 @@ dependencies = [
"futures-io",
]
+[[package]]
+name = "pkcs8"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
+dependencies = [
+ "der",
+ "spki",
+]
+
[[package]]
name = "pkg-config"
version = "0.3.34"
@@ -3582,6 +3744,15 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
+[[package]]
+name = "primeorder"
+version = "0.13.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6"
+dependencies = [
+ "elliptic-curve",
+]
+
[[package]]
name = "proc-macro-crate"
version = "1.3.1"
@@ -3691,6 +3862,7 @@ dependencies = [
"gtk",
"image",
"jiff",
+ "ksni",
"libc",
"notify-rust",
"quince-auth",
@@ -3712,6 +3884,8 @@ dependencies = [
"tempfile",
"tokio",
"uuid",
+ "webkit2gtk",
+ "wiremock",
"zbus 5.19.0",
]
@@ -3743,6 +3917,7 @@ dependencies = [
name = "quince-core"
version = "0.1.0"
dependencies = [
+ "base64 0.22.1",
"icu_normalizer",
"jiff",
"rusqlite",
@@ -3763,9 +3938,11 @@ dependencies = [
"flate2",
"futures-util",
"jiff",
+ "p256",
"pbkdf2",
"plist",
"quince-core",
+ "rand_core 0.6.4",
"reqwest 0.12.28",
"serde",
"serde_json",
@@ -3773,6 +3950,7 @@ dependencies = [
"sha2",
"thiserror 2.0.20",
"tokio",
+ "tokio-tungstenite",
"uuid",
"wiremock",
]
@@ -4108,7 +4286,7 @@ dependencies = [
"wasm-bindgen-futures",
"wasm-streams 0.4.2",
"web-sys",
- "webpki-roots",
+ "webpki-roots 1.0.10",
]
[[package]]
@@ -4157,6 +4335,16 @@ dependencies = [
"url",
]
+[[package]]
+name = "rfc6979"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2"
+dependencies = [
+ "hmac",
+ "subtle",
+]
+
[[package]]
name = "rfd"
version = "0.16.0"
@@ -4371,6 +4559,20 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+[[package]]
+name = "sec1"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc"
+dependencies = [
+ "base16ct",
+ "der",
+ "generic-array",
+ "pkcs8",
+ "subtle",
+ "zeroize",
+]
+
[[package]]
name = "secret-service"
version = "4.0.0"
@@ -4664,6 +4866,16 @@ dependencies = [
"libc",
]
+[[package]]
+name = "signature"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
+dependencies = [
+ "digest",
+ "rand_core 0.6.4",
+]
+
[[package]]
name = "simd-adler32"
version = "0.3.10"
@@ -4746,6 +4958,16 @@ dependencies = [
"system-deps 6.2.2",
]
+[[package]]
+name = "spki"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
+dependencies = [
+ "base64ct",
+ "der",
+]
+
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
@@ -4965,6 +5187,15 @@ version = "0.13.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
+[[package]]
+name = "task-local"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2972044a9e5e448a506a7ff6f0d03b566d8ef4cd6918a58fc59835a0f8666626"
+dependencies = [
+ "pin-project-lite",
+]
+
[[package]]
name = "tauri"
version = "2.12.5"
@@ -5456,6 +5687,22 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "tokio-tungstenite"
+version = "0.28.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d25a406cddcc431a75d3d9afc6a7c0f7428d4891dd973e4d54c56b46127bf857"
+dependencies = [
+ "futures-util",
+ "log",
+ "rustls",
+ "rustls-pki-types",
+ "tokio",
+ "tokio-rustls",
+ "tungstenite",
+ "webpki-roots 0.26.11",
+]
+
[[package]]
name = "tokio-util"
version = "0.7.19"
@@ -5675,6 +5922,25 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+[[package]]
+name = "tungstenite"
+version = "0.28.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8628dcc84e5a09eb3d8423d6cb682965dea9133204e8fb3efee74c2a0c259442"
+dependencies = [
+ "bytes",
+ "data-encoding",
+ "http",
+ "httparse",
+ "log",
+ "rand 0.9.5",
+ "rustls",
+ "rustls-pki-types",
+ "sha1",
+ "thiserror 2.0.20",
+ "utf-8",
+]
+
[[package]]
name = "typeid"
version = "1.0.3"
@@ -5757,6 +6023,12 @@ dependencies = [
"url",
]
+[[package]]
+name = "utf-8"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
+
[[package]]
name = "utf8_iter"
version = "1.0.4"
@@ -6004,6 +6276,15 @@ dependencies = [
"system-deps 6.2.2",
]
+[[package]]
+name = "webpki-roots"
+version = "0.26.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
+dependencies = [
+ "webpki-roots 1.0.10",
+]
+
[[package]]
name = "webpki-roots"
version = "1.0.10"
diff --git a/Cargo.toml b/Cargo.toml
index accf1fc..a9c08a3 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -11,7 +11,9 @@ license = "GPL-3.0-only"
anyhow = "1"
reqwest = { version = "0.12", features = ["json", "cookies", "gzip", "rustls-tls", "stream", "multipart"], default-features = false }
serde = { version = "1", features = ["derive"] }
-serde_json = "1"
+# Numbers read back exactly as written: Apple's records carry long decimals (Reminders' section
+# timestamps), and a save that re-wrote them a few digits off would change other records.
+serde_json = { version = "1", features = ["float_roundtrip"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
uuid = { version = "1", features = ["v4"] }
quince-media = { path = "crates/quince-media" }
@@ -30,3 +32,22 @@ opt-level = 1
[profile.dev.package."*"]
debug = false
opt-level = 3
+
+# What people install. Measured on the release binary (2026-10-22): the defaults left 16
+# codegen units per crate and no cross-crate inlining, and shipped the symbol table — about a
+# fifth of the binary, mapped into memory with it.
+# - opt-level 3: photos are decoded, resized and hashed in this process; size-tuned code
+# ("s"/"z") is slower exactly there.
+# - lto "thin" + one codegen unit: inlining across crates (serde, rusqlite, image, reqwest)
+# at a fraction of fat LTO's link time and memory, which on a small CI machine is the
+# difference between a build and an out-of-memory kill.
+# - strip: no symbol table on disk or in memory; a panic still says where in its message.
+# - panic stays "unwind": the library rolls a half-applied change back when one panics
+# (quince-core `atomically` catches the unwind), and a command that panics fails alone
+# instead of taking the app and its open windows down. "abort" would undo both.
+[profile.release]
+opt-level = 3
+lto = "thin"
+codegen-units = 1
+strip = "symbols"
+panic = "unwind"
diff --git a/README.md b/README.md
index 9541acb..a2329f6 100644
--- a/README.md
+++ b/README.md
@@ -1,625 +1,253 @@
<div align="center">
-<picture>
- <!-- The mark sits on a transparent background and reads on light and dark alike.
- To use a dedicated dark variant later, point the first srcset at docs/media/logo-dark.png. -->
- <source media="(prefers-color-scheme: dark)" srcset="packaging/icons/skykeep-1024.png">
- <source media="(prefers-color-scheme: light)" srcset="packaging/icons/skykeep-1024.png">
- <img src="packaging/icons/skykeep-1024.png" alt="Skykeep" width="140">
-</picture>
+<img src="packaging/icons/skykeep-1024.png" alt="Skykeep" width="128">
# Skykeep
-**Native iCloud apps for Linux and Windows.**
+**Your iCloud, at home on Linux and Windows.**
-Your Notes, Reminders, Calendar, Contacts, iCloud Drive and Photos as fast, native apps on your own computer.<br>
-Instant. Offline. Private. Open source.
+Notes, Reminders, Calendar, Contacts, Drive and Photos as fast desktop apps that stay in sync with your iPhone.
-[![License: GPL-3.0](https://img.shields.io/github/license/YashwanthKamireddi/Skykeep?color=2f6fd6)](LICENSE)
+[![License: GPL-3.0](https://img.shields.io/badge/license-GPL--3.0-2f6fd6)](LICENSE)
+[![Platforms](https://img.shields.io/badge/platforms-Linux%20%7C%20Windows%20(beta)-4a5568)](#install)
+[![Local-first](https://img.shields.io/badge/local--first-works%20offline-2f6fd6)](#privacy)
+[![Built with Rust and Tauri](https://img.shields.io/badge/built%20with-Rust%20%2B%20Tauri%202-b7410e)](#contributing)
+<!-- Dynamic badges: enable once the repository is public.
[![Latest release](https://img.shields.io/github/v/release/YashwanthKamireddi/Skykeep?include_prereleases&sort=semver&color=2f6fd6)](https://github.com/YashwanthKamireddi/Skykeep/releases)
[![Release build](https://img.shields.io/github/actions/workflow/status/YashwanthKamireddi/Skykeep/release.yml?label=release%20build)](https://github.com/YashwanthKamireddi/Skykeep/actions/workflows/release.yml)
-[![Windows build](https://img.shields.io/github/actions/workflow/status/YashwanthKamireddi/Skykeep/windows.yml?label=windows%20build)](https://github.com/YashwanthKamireddi/Skykeep/actions/workflows/windows.yml)
-<br>
-[![Platforms](https://img.shields.io/badge/platforms-Linux%20%7C%20Windows%20(beta)-4a5568)](#install)
-[![Rust](https://img.shields.io/badge/Rust-1.85%2B-b7410e?logo=rust&logoColor=white)](https://www.rust-lang.org)
-[![Tauri 2](https://img.shields.io/badge/Tauri-2-24c8db?logo=tauri&logoColor=white)](https://tauri.app)
[![Stars](https://img.shields.io/github/stars/YashwanthKamireddi/Skykeep?style=flat&color=e3b341)](https://github.com/YashwanthKamireddi/Skykeep/stargazers)
-<!-- Enable once published:
[![AUR](https://img.shields.io/aur/version/skykeep-git?logo=archlinux&label=AUR)](https://aur.archlinux.org/packages/skykeep-git)
[![Flathub](https://img.shields.io/flathub/v/io.github.yashwanthkamireddi.Skykeep?logo=flathub)](https://flathub.org/apps/io.github.yashwanthkamireddi.Skykeep)
-->
-[**Install**](#install) · [**Features**](#features) · [**Privacy**](#privacy-by-design) · [**FAQ**](#faq) · [**Build from source**](#build-from-source) · [**Contributing**](#contributing) · [**Roadmap**](#roadmap)
-
-</div>
+[Install](#install) · [Features](#features) · [Privacy](#privacy) · [FAQ](#faq) · [Contributing](#contributing)
<br>
-<div align="center">
- <!-- Hero: an edit on an iPhone shows up in Skykeep about a second later. See docs/media/README.md. -->
- <img src="docs/media/hero-sync.gif" alt="A note typed on an iPhone appears in Skykeep Notes on a Linux desktop about a second later" width="900">
+<picture>
+ <source media="(prefers-color-scheme: dark)" srcset="docs/media/notes-dark.png">
+ <img src="docs/media/notes-light.png" alt="Skykeep Notes showing a trip note with a picture, a checklist and a table" width="880">
+</picture>
+
</div>
-<br>
+## Six apps, one sign-in
<table>
<tr>
- <td width="50%">
+ <td width="50%" align="center">
<picture>
- <source media="(prefers-color-scheme: dark)" srcset="docs/media/notes-dark.png">
- <img src="docs/media/notes-light.png" alt="Skykeep Notes with a checklist, a table and a picture">
+ <source media="(prefers-color-scheme: dark)" srcset="docs/media/reminders-dark.png">
+ <img src="docs/media/reminders-light.png" alt="Skykeep Reminders showing Today with coloured lists, priorities and flags">
</picture>
- <p align="center"><b>Notes</b></p>
+ <b>Reminders</b>
</td>
- <td width="50%">
+ <td width="50%" align="center">
<picture>
- <source media="(prefers-color-scheme: dark)" srcset="docs/media/reminders-dark.png">
- <img src="docs/media/reminders-light.png" alt="Skykeep Reminders showing Today with a subtask and a flag">
+ <source media="(prefers-color-scheme: dark)" srcset="docs/media/calendar-dark.png">
+ <img src="docs/media/calendar-light.png" alt="Skykeep Calendar in week view with events from four calendars">
</picture>
- <p align="center"><b>Reminders</b></p>
+ <b>Calendar</b>
</td>
</tr>
<tr>
- <td width="50%">
+ <td width="50%" align="center">
<picture>
- <source media="(prefers-color-scheme: dark)" srcset="docs/media/calendar-dark.png">
- <img src="docs/media/calendar-light.png" alt="Skykeep Calendar in week view with reminders on the schedule">
+ <source media="(prefers-color-scheme: dark)" srcset="docs/media/contacts-dark.png">
+ <img src="docs/media/contacts-light.png" alt="Skykeep Contacts showing a contact card with phones, emails and an address">
</picture>
- <p align="center"><b>Calendar</b></p>
+ <b>Contacts</b>
</td>
- <td width="50%">
+ <td width="50%" align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/media/drive-dark.png">
- <img src="docs/media/drive-light.png" alt="Skykeep Drive beside the iCloud Drive folder in the file manager">
+ <img src="docs/media/drive-light.png" alt="Skykeep Drive showing a folder of pictures in grid view">
</picture>
- <p align="center"><b>iCloud Drive</b></p>
+ <b>iCloud Drive</b>
+ </td>
+ </tr>
+ <tr>
+ <td width="50%" align="center">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="docs/media/photos-dark.png">
+ <img src="docs/media/photos-light.png" alt="Skykeep Photos showing the library by month">
+ </picture>
+ <b>Photos</b> <sub>preview</sub>
+ </td>
+ <td width="50%" align="center">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="docs/media/settings-dark.png">
+ <img src="docs/media/settings-light.png" alt="Skykeep Settings showing the account, storage and when each app last synced">
+ </picture>
+ <b>Settings</b>
</td>
</tr>
</table>
-<details>
-<summary><b>More screenshots</b>: Contacts, Photos, Settings, sign-in</summary>
-<br>
-
-| | |
-|---|---|
-| <img src="docs/media/contacts-light.png" alt="Skykeep Contacts with a card and the lists sidebar"> | <img src="docs/media/photos-dark.png" alt="Skykeep Photos library by month (preview)"> |
-| **Contacts** | **Photos** (preview) |
-| <img src="docs/media/settings-light.png" alt="Skykeep Settings showing the account, storage and what the app talks to"> | <img src="docs/media/signin-light.png" alt="Signing in with an Apple Account and a two-factor code"> |
-| **Settings**: your account, storage and sync | **Sign-in**: Apple's own sign-in and two-factor code |
-
-</details>
-
----
-
-## Why Skykeep
-
-Your iPhone keeps your life in iCloud: the shopping list, the meeting notes, the birthdays, the files. Apple makes iCloud apps for its own devices, so on a Linux or Windows computer you've had a browser tab and a lot of waiting.
-
-**Skykeep brings your iCloud home.** It keeps a copy of your iCloud on your own computer, so every screen opens instantly, works without a connection, and stays in sync with your iPhone in both directions. The engine is written in Rust; it talks only to Apple; and the code is open for anyone to read.
-
-> *Sky* is the cloud, where your iCloud lives. A *keep* is the strongest tower of a castle, where precious things are kept. **Skykeep: your cloud, kept safe on your own computer.**
-
-## Highlights
-
-| | |
-|---|---|
-| **Six apps, one engine** | Notes, Reminders, Calendar, Contacts, Drive and Photos. Each opens as its own app; all share one sign-in and one sync. |
-| **Instant** | Your library lives on your disk. Screens open immediately, with no loading from the internet. |
-| **Works offline** | Read and edit without a connection. Changes are sent when you're back online. |
-| **Two-way sync** | Notes and Reminders arrive over Apple's push channel in about a second. Calendar and Contacts check for changes every few seconds while a window is open. |
-| **Private by design** | Your password never leaves your computer. No Skykeep account, no Skykeep server, no telemetry. The network layer can reach only Apple. |
-| **At home on your desktop** | Light and dark mode, system notifications with action buttons, a tray icon, quick capture, results in GNOME and KDE search, and `.ics` / `.vcf` files opened straight into Calendar and Contacts. |
-| **Your data, exportable** | Export Everything writes your whole library to Markdown, iCalendar, vCard, CSV and the original files, any time, offline. |
+<sub>Every screenshot uses an invented demo library.</sub>
## Features
-<details open>
-<summary><b>Notes</b></summary>
-<br>
-
-- Rich text: titles, headings, monospaced text, bold, italic, underline, strikethrough, and colours set on your phone.
-- Bulleted, dashed, numbered lists and checklists, typed as on the iPhone (`- `, `* `, `1. `, `[ ] `).
-- Pictures, drawings, scans, PDFs, recordings and files shown in place and opened in your own apps.
-- Tables shown as grids and kept up to date as they change on your phone.
-- Folders (new, rename, nest, delete), pinned notes, Recently Deleted and Recover.
-- Search within a folder or across every note.
-- Edits made on your phone at the same moment are **merged, not overwritten**.
-- Markdown export.
-
-*Coming soon:* editing tables, adding attachments, and opening locked notes.
-</details>
-
-<details>
-<summary><b>Reminders</b></summary>
-<br>
-
-- Lists with Apple's colours and glyphs, and groups of lists.
-- Today, Scheduled, Flagged and All, plus your smart lists.
-- Subtasks (Tab), due dates and all-day dates, repeating reminders, flags and priorities.
-- Alerts that ring on this computer, with **Complete** and **Snooze** buttons.
-- Drag to reorder; completing a repeating reminder works the way your phone does.
-- Tags and sections are shown.
-
-*Coming soon:* editing tags and sections.
-</details>
-
-<details>
-<summary><b>Calendar</b></summary>
-<br>
-
-- Day, Week, Month and Year views.
-- Drag or double-click to create; drag to move and resize; nudge with the keyboard.
-- Repeating events, with This Event, All Future Events and All Events.
-- Alerts, time zones, and your reminders on the schedule in their list's colour.
-- Birthdays and holidays.
-- Create, rename, recolour and delete calendars.
-- Subscribe to any public calendar by its `webcal://` or `https://` address.
-- Open `.ics` files straight into an import sheet.
-
-*Later:* invitations and RSVP.
-</details>
-
-<details>
-<summary><b>Contacts</b></summary>
-<br>
-
-- Every field: phones, emails, links, addresses, birthdays, notes, with Apple's own labels, and structured addresses.
-- Lists in a sidebar; add people by menu or by dragging.
-- Select several to add, remove, export or delete together.
-- Import from vCard, or from a CSV exported by Google Contacts or Outlook. Export to vCard.
-- My Card.
-</details>
-
-<details>
-<summary><b>iCloud Drive</b></summary>
-<br>
-
-- Browse in a list or grid with Apple's thumbnails; sort; Recents.
-- Upload files or whole folders by button or drag and drop, with per-file progress and cancel.
-- Download, rename, duplicate, Get Info, move by dialog or by dragging onto a folder.
-- Quick preview with Space; keep files on this computer for offline use.
-- Recently Deleted with Recover and Delete Now; your storage at a glance.
-- **On Linux, iCloud Drive as a real folder** in your file manager (`~/iCloud Drive`, via FUSE).
-</details>
-
-<details>
-<summary><b>Photos</b> <sub>(preview)</sub></summary>
-<br>
-
-> [!NOTE]
-> Photos is a **preview**: it is built and tested, and is waiting on testing against a large real-world library before it leaves preview.
-
-- Your whole library, edge to edge and by month, with zoom.
-- Favourites, Recents, Videos, Screenshots, Recently Deleted, your albums and shared albums.
-- A viewer with arrow keys, details, Favourite, Live Photos and videos.
-- Search, slideshow, upload, and download in original quality.
-</details>
-
-<details>
-<summary><b>Across every app</b></summary>
-<br>
-
-- **Global search** across notes, reminders, events, contacts, files and photos.
-- **Quick capture:** `skykeep --new note` or `skykeep --new reminder` opens a small capture window. Also in the launcher's right-click menu.
-- **Desktop search:** results appear in GNOME Shell search and KRunner.
-- **Tray icon** and system notifications with sounds and action buttons.
-- **Settings:** your account, iCloud storage, when each app last synced (with Sync Now), Automatic / Light / Dark, and alert switches.
-- **Accessibility:** Reduce Transparency and Increase Contrast are honoured, and every app is built to be driven from the keyboard.
-</details>
-
-## Privacy by design
-
-Skykeep asks for your Apple Account password, so it was built to deserve that trust, and it shows its work.
-
-- **Your password never leaves your computer.** Sign-in uses Apple's own SRP flow: Skykeep proves it knows your password without sending it. Your session lives in your system keyring (Secret Service on Linux, Credential Manager on Windows).
-- **It talks only to Apple, enforced in code.** Every network client is built by [`apple_only()`](crates/quince-auth/src/lib.rs), whose resolver refuses any host outside `apple.com`, `icloud.com` and `icloud-content.com`. A [test](crates/quince-auth/tests/apple_only.rs) holds it to that. The only other hosts it ever contacts are calendars you subscribe to yourself.
-- **No Skykeep servers.** No account, no telemetry, no analytics, no crash reporting, no update check.
-- **The window can't reach the network at all.** Its content security policy lets it talk only to Skykeep's own Rust core.
-- **Your data stays yours.** Everything lives in your private data folder, and Export Everything hands it to you in open formats.
-
-Read exactly what Skykeep talks to, what it keeps and where, in **[SECURITY.md](SECURITY.md)**.
-
-## How it works
-
-```mermaid
-flowchart LR
- subgraph Computer["Your computer"]
- direction TB
- UI["Six app windows<br/>(Tauri + React)"]
- Core["Rust engine<br/>sync · outbox · merge"]
- DB[("Local library<br/>SQLite + caches")]
- Keyring["System keyring"]
- UI <-->|"IPC only"| Core
- Core <--> DB
- Core <--> Keyring
- end
- Core <-->|"HTTPS, Apple hosts only"| Apple["iCloud<br/>(CloudKit, Contacts,<br/>Calendar, Drive, Photos)"]
- Apple <--> Phone["Your iPhone"]
-```
-
-1. **Sign in once.** Apple's own sign-in and two-factor code. The session goes into your keyring.
-2. **Your library comes home.** Each service syncs into a local SQLite library, and each screen fills as its service lands.
-3. **Edits show instantly.** A change appears the moment you make it and goes into an outbox. It is sent to Apple when you're online, and put back with the reason if Apple ever refuses it.
-4. **Changes flow back.** Notes and Reminders arrive over Apple's push channel; Calendar and Contacts are checked every few seconds, the same way icloud.com does.
+| App | What you can do | Coming |
+|---|---|---|
+| **Notes** | Write with headings, styles, lists and checklists. See pictures, scans, PDFs and tables in place. Folders, pinned notes, search and Recently Deleted. Edits from your phone merge with yours. | Adding attachments, editing tables |
+| **Reminders** | Lists with colours and icons, Today, Scheduled, Flagged and your smart lists. Subtasks, due dates, repeats, flags and priorities. Alerts with **Complete** and **Snooze**. | Editing tags, links, early alerts and sections |
+| **Calendar** | Day, Week, Month and Year. Drag to create, move and resize. Repeating events, alerts, time zones, birthdays and holidays. Subscribe to any `webcal://` calendar and open `.ics` files. | |
+| **Contacts** | Every field, with Apple's labels. Lists, My Card, find and merge duplicates. Import vCard or a Google or Outlook CSV; export vCard. | |
+| **iCloud Drive** | List or grid with thumbnails. Upload files and folders, rename, move, duplicate and preview with Space. On Linux, iCloud Drive is also a real folder in your file manager. | |
+| **Photos** <sub>preview</sub> | Your library by month, albums and shared albums, Favourites and Videos. A viewer for Live Photos and videos, slideshow, upload and original-quality download. | |
+| **Everywhere** | Search across every app. Quick capture for a note or reminder. Results in GNOME and KDE search, a tray icon, light and dark. **Export Everything** to Markdown, iCalendar, vCard and your original files. | |
## Install
-> [!IMPORTANT]
-> The first public release is on its way. Packages appear on the [Releases page](https://github.com/YashwanthKamireddi/Skykeep/releases) as they're published, each with SHA-256 checksums. Until then, [build from source](#build-from-source) in a few minutes.
+Packages arrive with the first release on the [Releases page](https://github.com/YashwanthKamireddi/Skykeep/releases), each with SHA-256 checksums.
-| Platform | How | Status |
-|---|---|---|
-| **Arch, CachyOS, EndeavourOS, Manjaro** | `paru -S skykeep-git` or `yay -S skykeep-git` | AUR: coming soon |
-| **Any distribution** | Flatpak from Flathub | Coming soon |
-| **Debian, Ubuntu, Mint, Pop!_OS** | `.deb` from Releases | With the first release |
-| **Fedora, openSUSE, RHEL** | `.rpm` from Releases | With the first release |
-| **Any distribution, no install** | `.AppImage` from Releases | With the first release |
-| **Windows 10 and 11** | `.exe` or `.msi` from Releases | **Beta** |
+| Platform | Package |
+|---|---|
+| **Debian, Ubuntu, Mint** | `.deb` |
+| **Fedora, openSUSE** | `.rpm` |
+| **Any Linux** | `.AppImage` |
+| **Arch, CachyOS, EndeavourOS, Manjaro** | AUR `skykeep-git` <sub>coming to the AUR</sub> |
+| **Any Linux, sandboxed** | Flatpak <sub>coming to Flathub</sub> |
+| **Windows 10 and 11** | `.exe` or `.msi` <sub>beta</sub> |
<details>
-<summary><b>Arch Linux and derivatives</b></summary>
-<br>
-
-From the AUR (coming soon):
+<summary><b>Debian and Ubuntu</b></summary>
```sh
-paru -S skykeep-git # or: yay -S skykeep-git
+sudo apt install ./Skykeep_*_amd64.deb
```
+</details>
-Today, build the same package from a checkout:
+<details>
+<summary><b>Fedora and openSUSE</b></summary>
```sh
-git clone https://github.com/YashwanthKamireddi/Skykeep.git
-cd Skykeep/packaging/arch
-makepkg -si
+sudo dnf install ./Skykeep-*.x86_64.rpm # Fedora
+sudo zypper install ./Skykeep-*.x86_64.rpm # openSUSE
```
-
-Optional: install `fuse3` for iCloud Drive and Photos as folders in your file manager.
</details>
<details>
-<summary><b>Debian / Ubuntu (.deb)</b></summary>
-<br>
+<summary><b>AppImage</b></summary>
```sh
-sudo apt install ./Skykeep_*_amd64.deb
+chmod +x Skykeep_*_amd64.AppImage
+./Skykeep_*_amd64.AppImage
```
+
+Uses the WebKitGTK 4.1 and libsecret already on most desktops.
</details>
<details>
-<summary><b>Fedora / openSUSE (.rpm)</b></summary>
-<br>
+<summary><b>Arch and derivatives</b></summary>
+
+Once it's on the AUR:
```sh
-sudo dnf install ./Skykeep-*.x86_64.rpm # Fedora
-sudo zypper install ./Skykeep-*.x86_64.rpm # openSUSE
+paru -S skykeep-git # or: yay -S skykeep-git
```
-</details>
-<details>
-<summary><b>AppImage</b></summary>
-<br>
+Today, build the same package from a checkout:
```sh
-chmod +x Skykeep_*_amd64.AppImage
-./Skykeep_*_amd64.AppImage
+git clone https://github.com/YashwanthKamireddi/Skykeep.git
+cd Skykeep/packaging/arch && makepkg -si
```
-Needs WebKitGTK 4.1 and libsecret on the system, which most desktops already have.
+Add `fuse3` to see iCloud Drive and Photos as folders in your file manager.
</details>
<details>
-<summary><b>Flatpak</b> (coming soon)</summary>
-<br>
+<summary><b>Flatpak</b></summary>
-The Flathub manifest is in [`packaging/flatpak`](packaging/flatpak). Once it's live:
+The manifest lives in [`packaging/flatpak`](packaging/flatpak). Once it's on Flathub:
```sh
flatpak install flathub io.github.yashwanthkamireddi.Skykeep
```
-In the Flatpak, iCloud Drive and Photos are available inside the app; the file-manager folders need the native packages.
+In the Flatpak, iCloud Drive and Photos open inside the app.
</details>
<details>
<summary><b>Windows</b> (beta)</summary>
-<br>
-
-> [!NOTE]
-> Windows builds are tested on every release in CI (the full test suite, every interface suite in Edge, and an install-and-launch smoke test), and they're labelled **beta** until they've been verified on more real Windows machines. Feedback is very welcome.
-Download `Skykeep_*_x64-setup.exe` (per-user, no admin needed) or the `.msi` from [Releases](https://github.com/YashwanthKamireddi/Skykeep/releases) and run it. It registers `.ics` and `.vcf` files, and notifications come with Complete and Snooze buttons.
-
-The iCloud Drive and Photos folders in Explorer are on the roadmap.
+Run `Skykeep_*_x64-setup.exe` (installs for you alone, no admin needed) or the `.msi`. Skykeep opens `.ics` and `.vcf` files, and its alerts come with **Complete** and **Snooze**.
</details>
-**Requirements on Linux:** `webkit2gtk-4.1` for the window and `libsecret` for the keyring (GNOME Keyring or KWallet). Packages pull them in for you.
-
-## First run
+**First run:** open Skykeep, sign in with your Apple Account, and enter the code from your iPhone. Each app fills as your library arrives, then opens instantly from then on.
-1. **Open Skykeep** from your app menu. On Linux, each app (Notes, Reminders, Calendar, Contacts, Drive, Photos) also has its own launcher entry.
-2. **Sign in** with your Apple Account, then enter the code shown on your iPhone. This is Apple's own two-factor flow.
-3. **Watch your library arrive.** Each app fills as its data lands. After this first sync, everything opens instantly, even offline.
-4. **Optional:** in Settings, turn on the iCloud Drive and iCloud Photos folders (Linux), choose your appearance, and set which alerts ring.
+## Privacy
-> [!TIP]
-> Using **Advanced Data Protection**? Turn on **Access iCloud Data on the Web** on your iPhone: Settings → your name → iCloud → Access iCloud Data on the Web. Skykeep tells you if it's needed.
+- **Local-first.** Your library lives on your computer, so every app opens instantly and works offline. Changes you make offline are sent when you're back online.
+- **Credentials stay in your system keychain.** You sign in through Apple's own two-factor flow, and your password and account tokens are kept in the keychain, never in a file: Secret Service on Linux, Credential Manager on Windows.
+- **Talks only to Apple.** Skykeep's network layer reaches Apple's iCloud hosts, plus any calendars you subscribe to. No Skykeep account, no Skykeep server, no telemetry.
+- **Independent.** Skykeep is an open-source project, not affiliated with or endorsed by Apple.
-## Keyboard shortcuts
+The details, with the code behind each one, are in [SECURITY.md](SECURITY.md).
-Skykeep follows the keys of Apple's own apps, with **Ctrl** in place of **⌘**.
+## Performance
-<details>
-<summary><b>Show all shortcuts</b></summary>
-<br>
+Measured on release builds. Numbers land with the first release.
-| Where | Keys | Action |
+| | Linux | Windows |
|---|---|---|
-| Everywhere | `Ctrl` `R` / `F5` | Sync the app in front |
-| Notes | `Ctrl` `N` | New note |
-| | `Ctrl` `F` / `Ctrl` `Shift` `F` | Search this folder / all notes |
-| | `↑` `↓` | Previous / next note |
-| | `Ctrl` `Delete` | Delete note |
-| | `Ctrl` `S` | Finish editing |
-| Reminders | `Ctrl` `N` / `Ctrl` `Shift` `N` | New reminder / new list |
-| | `Tab` / `Shift` `Tab` (or `Ctrl` `]` / `Ctrl` `[`) | Make a subtask / move it back out |
-| | `Space` · `Return` | Tick · edit |
-| | `Ctrl` `I` | Show details |
-| | `Ctrl` `F` | Search |
-| Calendar | `Ctrl` `1` – `4` | Day, Week, Month, Year |
-| | `T` | Today |
-| | `Ctrl` `Shift` `T` | Go to Date |
-| | `←` `→` | Previous / next |
-| | `Ctrl` `N` | New event |
-| | `Ctrl` `D` · `Ctrl` `C` · `Ctrl` `V` | Duplicate · copy · paste event |
-| | `Ctrl` `Alt` `↑↓←→` | Nudge the selected event |
-| Contacts | `Ctrl` `N` · `Ctrl` `F` · `Ctrl` `A` | New contact · search · select all |
-| Drive | `Return` / `Ctrl` `↓` | Open |
-| | `Ctrl` `↑` | Enclosing folder |
-| | `Space` | Quick preview |
-| | `F2` · `Delete` | Rename · move to Recently Deleted |
-| Photos | `←` `→` | Previous / next |
-| | `.` or `F` | Favourite |
-| | `I` · `Z` | Info · zoom to fit / full size |
-| | `Ctrl` `+` `-` `0` | Zoom in / out / reset |
-| | `Space` | Play a video or Live Photo |
-| | `Esc` | Close the viewer |
-
-</details>
+| Launch to a usable window | *to be measured* | *to be measured* |
+| Open a note from the list | *to be measured* | *to be measured* |
+| A change on iPhone shown here | *to be measured* | *to be measured* |
+| Memory with all six apps open | *to be measured* | *to be measured* |
+| Download size | *to be measured* | *to be measured* |
## FAQ
<details>
<summary><b>Is Skykeep made by Apple?</b></summary>
-<br>
-No. Skykeep is an independent, open-source project. It is **not affiliated with, endorsed by, or sponsored by Apple Inc.** iCloud, iPhone and Apple are trademarks of Apple Inc., used here only to describe what Skykeep works with.
-</details>
-
-<details>
-<summary><b>Is it safe to give Skykeep my Apple Account password?</b></summary>
-<br>
-
-Your password is used only on your computer, through Apple's SRP sign-in, which proves you know it without sending it. It's stored in your system keyring so a lapsed session can sign itself back in. Skykeep has no server and no account of its own, and its network layer refuses every host but Apple's. Every claim is in [SECURITY.md](SECURITY.md), with the code and tests that back it up.
-</details>
-
-<details>
-<summary><b>I use Advanced Data Protection. Will it work?</b></summary>
-<br>
-
-Yes, with **Access iCloud Data on the Web** turned on (iPhone: Settings → your name → iCloud → Access iCloud Data on the Web). With that switch off, Apple lets no app outside your own devices read your iCloud data, Skykeep included. Skykeep explains this once and names the switch; it never asks you to turn Advanced Data Protection off.
+No. It's an independent, open-source app that works with iCloud. Apple, iCloud and iPhone are trademarks of Apple Inc.
</details>
<details>
<summary><b>Does it work offline?</b></summary>
-<br>
-Yes. Everything you've synced is on your disk. Read and edit freely; your changes wait in an outbox and are sent when you're back online. A small indicator shows anything still waiting.
+Yes. Everything you've synced is on your disk. Notes, reminders, events and contacts can be edited offline and sync when you reconnect.
</details>
<details>
-<summary><b>How fast does a change on my iPhone show up?</b></summary>
-<br>
+<summary><b>How fast do changes from my iPhone appear?</b></summary>
-Notes and Reminders arrive over Apple's push channel, typically in about a second. Calendar and Contacts are checked every few seconds while a window is open. Your own edits in Skykeep show the instant you make them.
+Notes and Reminders arrive over Apple's push channel, usually in about a second. Calendar and Contacts are checked every few seconds while a window is open. Your own edits show the moment you make them.
</details>
<details>
-<summary><b>What if I edit the same note on my phone and here at the same time?</b></summary>
-<br>
-
-Both edits are kept. Notes merges text the way Apple's apps do, so nothing either side typed is lost.
-</details>
-
-<details>
-<summary><b>Which parts of iCloud aren't included?</b></summary>
-<br>
-
-Mail and Find My aren't part of Skykeep today. Health, Messages, Keychain, Home and Safari history are end-to-end encrypted by Apple and can't be read by any app outside your devices; Skykeep shows them as unavailable rather than leaving them out silently.
-</details>
-
-<details>
-<summary><b>Which Linux desktops does it support?</b></summary>
-<br>
-
-Skykeep is built for any desktop with WebKitGTK 4.1 and a Secret Service keyring (GNOME Keyring or KWallet), on Wayland or X11. It's used daily on Hyprland, and GNOME and KDE Plasma also get Skykeep results in their desktop search. If something looks off on your desktop, please [open an issue](https://github.com/YashwanthKamireddi/Skykeep/issues/new/choose).
-</details>
-
-<details>
-<summary><b>Can I get my data out?</b></summary>
-<br>
+<summary><b>I use Advanced Data Protection. Will it work?</b></summary>
-Any time. Settings → Export Everything writes your whole library to a folder: notes as Markdown, events as iCalendar, contacts as vCard and CSV, and your files as they are. It works offline.
+Yes, with **Access iCloud Data on the Web** turned on: on your iPhone, Settings → your name → iCloud. Skykeep tells you when it's needed.
</details>
<details>
-<summary><b>What happens if Apple changes something?</b></summary>
-<br>
+<summary><b>Can I take my data with me?</b></summary>
-Skykeep uses the same services icloud.com uses. If Apple changes one, the affected screen may pause until an update catches up. Your local copy stays on your computer the whole time.
+Any time. Settings → Export Everything saves your notes as Markdown, events as iCalendar, contacts as vCard and CSV, and your files as they are.
</details>
<details>
-<summary><b>How do I sign out or remove my data?</b></summary>
-<br>
+<summary><b>Which desktops does it run on?</b></summary>
-Settings → Sign Out asks whether to keep a copy on this computer. Choose to remove it, and the library, its caches and its file-manager thumbnails are deleted.
+Any Linux desktop with WebKitGTK 4.1 and a keyring (GNOME Keyring or KWallet), on Wayland or X11, and Windows 10 and 11.
</details>
-## Build from source
-
-<details open>
-<summary><b>Linux</b></summary>
-<br>
-
-Prerequisites: Rust 1.85+ ([rustup](https://rustup.rs)), Node.js 22, and the system libraries.
-
-```sh
-# Debian / Ubuntu
-sudo apt install libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev \
- librsvg2-dev libsecret-1-dev libheif-dev libfuse3-dev pkg-config
-
-# Arch
-sudo pacman -S --needed webkit2gtk-4.1 gtk3 libsecret libheif libayatana-appindicator \
- gstreamer gst-plugins-base-libs fuse3 rust nodejs npm pkgconf
-
-# Fedora
-sudo dnf install webkit2gtk4.1-devel gtk3-devel libayatana-appindicator-gtk3-devel \
- librsvg2-devel libsecret-devel libheif-devel fuse3-devel pkgconf-pkg-config
-```
+## Contributing
-Then:
+Bug reports, packaging recipes, design ideas and code are all welcome. Start with [CONTRIBUTING.md](.github/CONTRIBUTING.md) for setup and the checks, and run `./check.sh` before a pull request.
```sh
git clone https://github.com/YashwanthKamireddi/Skykeep.git
-cd Skykeep
-npm ci
-./run.sh # builds the interface and the app, then opens Skykeep
-```
-
-Packages (`.deb`, `.rpm`, `.AppImage` under `target/release/bundle/`):
-
-```sh
-npx tauri build
-```
-</details>
-
-<details>
-<summary><b>Windows</b></summary>
-<br>
-
-Install Rust, Node.js 22 and the [Tauri prerequisites](https://tauri.app/start/prerequisites/). HEIC support uses libheif from vcpkg:
-
-```powershell
-vcpkg install libheif:x64-windows-static-md
-$env:VCPKG_ROOT = "<path to vcpkg>"
-$env:VCPKGRS_TRIPLET = "x64-windows-static-md"
-npm ci
-npx tauri build
+cd Skykeep && npm ci && ./run.sh
```
-The exact steps CI uses are in [`.github/workflows/windows.yml`](.github/workflows/windows.yml).
-</details>
-
-## Architecture
-
-Skykeep is one Rust engine with six app windows on top. The Rust side does all the talking to Apple; the interface is a React app rendered by the system's web engine (WebKitGTK on Linux, WebView2 on Windows), with no network access of its own.
-
-<details>
-<summary><b>Project layout</b></summary>
-<br>
-
-```text
-crates/
- quince-auth/ Apple sign-in (SRP, two-factor), the session, the keyring,
- and the apple_only() network allow-list
- quince-icloud/ iCloud services: CloudKit, Notes (topotext CRDT, tables),
- Reminders, Calendar, Contacts, Drive, Photos, push channel
- quince-core/ The local library (SQLite), sync, outbox, search, export
- quince-vfs/ iCloud Drive and Photos as folders (FUSE, Linux)
- quince-media/ Picture decoding and thumbnails (including HEIC)
-src-tauri/ The desktop app: windows, commands, alerts, tray, desktop search,
- file import, migrations
-src/ The interface (React + TypeScript)
- screens/ One folder or file per app, plus sign-in and Settings
- components/ The shared design system: Toast, Confirm, EmptyState, PaneTitle and more
- lib/ IPC, sync state, optimistic writes, theming
-probe/ Live checks against a real iCloud account (run deliberately)
-.uiverify/ Playwright interface suites, in Chromium and WebKit
-packaging/ Arch, AUR, Flatpak, desktop entries, AppStream metadata, icons
-```
-
-The crates keep their original `quince-` prefix from before the project was named Skykeep.
-</details>
-
-<details>
-<summary><b>Design principles</b></summary>
-<br>
-
-- **Instant, always.** Every write shows the moment it's made and rolls back with a reason if Apple refuses it. No screen waits on the network to redraw.
-- **Calm and familiar.** Each app looks and behaves like the Apple app you already know, with that app's colour: Notes yellow, Calendar red, the rest blue.
-- **Your content, never decorated.** Glass and translucency on the chrome only; content stays crisp.
-- **Motion that never flickers.** Large layers open instantly; nothing animates that the engine can't draw cleanly on every desktop.
-- **Simple for a beginner, fast for an expert, open for a developer.**
-</details>
-
-## Contributing
-
-Contributions are welcome, from a typo fix to a new feature. Start with **[CONTRIBUTING.md](.github/CONTRIBUTING.md)** for setup, the checks, and commit style.
-
-- **New here?** Pick a [good first issue](https://github.com/YashwanthKamireddi/Skykeep/labels/good%20first%20issue).
-- **Ideas and questions:** [Discussions](https://github.com/YashwanthKamireddi/Skykeep/discussions).
-- **Found a bug?** [Open an issue](https://github.com/YashwanthKamireddi/Skykeep/issues/new/choose).
-- **Packagers:** Nix, Fedora COPR, Debian, winget and Snap recipes are especially welcome.
-- **Designers:** UI contributions are welcome. Open a Discussion with a mockup or screenshot first, and read the design principles above.
-
-Before a pull request, run `./check.sh`: formatting, Clippy, Rust tests, TypeScript, and the interface suites in a real browser engine.
-
-## Roadmap
-
-| | |
-|---|---|
-| **Shipped** | Six apps on one engine · two-way sync · offline outbox · Export Everything · desktop search · quick capture · `.ics` / `.vcf` import · the Apple-only network allow-list |
-| **Now** | First public release · AUR and Flathub · Windows out of beta · Photos out of preview |
-| **Next** | Editing Notes tables · adding attachments to notes · locked notes · editing reminder tags and sections · offline edits for events · merging duplicate contacts · an accessibility pass |
-| **Later** | Drive and Photos folders in Windows Explorer · calendar invitations · sharing |
-
-Have an idea? Share it in [Discussions](https://github.com/YashwanthKamireddi/Skykeep/discussions/categories/ideas).
-
-## Security
-
-Please report vulnerabilities privately through [GitHub's private vulnerability reporting](https://github.com/YashwanthKamireddi/Skykeep/security/advisories/new), not in a public issue. See [SECURITY.md](SECURITY.md) for what Skykeep talks to, what it stores, and where.
-
-## Support the project
-
-Skykeep is free and open source, built by one person. If it saves you a browser tab every day, a star helps others find it.
-<!-- Enable once GitHub Sponsors is approved:
-You can also [sponsor its development](https://github.com/sponsors/YashwanthKamireddi).
--->
+Found a security issue? Please report it privately, as described in [SECURITY.md](SECURITY.md).
## License
-Skykeep is free software, licensed under the [GNU General Public License v3.0](LICENSE).
-
-**Not affiliated with Apple.** Skykeep is an independent project that works with iCloud. Apple, iCloud, iPhone and related marks are trademarks of Apple Inc.
-
-## Acknowledgements
-
-Skykeep stands on excellent open-source work, including [Tauri](https://tauri.app), [Rust](https://www.rust-lang.org) and its ecosystem ([Tokio](https://tokio.rs), [reqwest](https://github.com/seanmonstar/reqwest), [rusqlite](https://github.com/rusqlite/rusqlite), [fuser](https://github.com/cberner/fuser), [libheif](https://github.com/strukturag/libheif)), [React](https://react.dev), [ProseMirror](https://prosemirror.net), [Lucide](https://lucide.dev), [Vite](https://vite.dev) and [Playwright](https://playwright.dev). Thank you to everyone who maintains them.
-
-<div align="center">
-<br>
-
-<a href="https://star-history.com/#YashwanthKamireddi/Skykeep&Date">
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=YashwanthKamireddi/Skykeep&type=Date&theme=dark">
- <img alt="Star history of Skykeep" src="https://api.star-history.com/svg?repos=YashwanthKamireddi/Skykeep&type=Date" width="600">
- </picture>
-</a>
-
-<br><br>
-
-Made with care by [Yashwanth Kamireddi](https://github.com/YashwanthKamireddi).
-
-</div>
+[GPL-3.0](LICENSE). Not affiliated with Apple Inc.
diff --git a/SECURITY.md b/SECURITY.md
index ab4e0c3..bd4279e 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -14,7 +14,8 @@ Apple, and to calendars you subscribe to — nothing else:
- `*.icloud.com` service addresses Apple gives the session (CloudKit, Contacts, Calendar,
iCloud Drive, Photos), `gateway.icloud.com` and `cvws.icloud-content.com` (downloads).
- `calendars.icloud.com` — Apple's public holiday calendars.
-- The `.com.cn` equivalents of the above, for accounts in mainland China.
+- The `.com.cn` equivalents of the above are on the allow-list too, kept for accounts in
+ mainland China. Signing in with one isn't supported yet, so today they go unused.
- The host of each calendar you subscribe to by address (Calendar ▸ + ▸ New Subscription…),
and only once you have: a `webcal://` or `https://` address of a public calendar file.
diff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rs
index 22a47e7..c5273e2 100644
--- a/crates/quince-auth/src/lib.rs
+++ b/crates/quince-auth/src/lib.rs
@@ -114,6 +114,10 @@ pub enum Error {
Network(#[from] reqwest::Error),
#[error("Apple sent back something unexpected: {0}")]
Protocol(String),
+ /// Apple's servers answered but could not serve now — an outage, maintenance, too many
+ /// requests (5xx, 429). Like being offline: try again later, never "signed out".
+ #[error("Apple's servers are busy right now ({0}). Skykeep will try again shortly.")]
+ Unavailable(u16),
#[error("Too many attempts. Try again in {seconds} seconds.")]
CoolingDown { seconds: u64 },
#[error("this needs a fresh sign-in — Apple won't accept a resumed session for it")]
@@ -133,6 +137,12 @@ pub enum Error {
type Result<T> = std::result::Result<T, Error>;
+/// A reply that says "not now" rather than "no": Apple's servers failing or overloaded.
+fn transient(status: reqwest::StatusCode) -> Option<Error> {
+ (status.is_server_error() || status.as_u16() == 429)
+ .then(|| Error::Unavailable(status.as_u16()))
+}
+
/// Apple returns `{"serviceErrors":[{"code":"-21669","message":"..."}]}` on failures.
/// Surface its own words; a bare status code explains nothing.
fn apple_error(context: &str, status: StatusCode, body: &str) -> Error {
@@ -299,10 +309,20 @@ impl Client {
HeaderValue::from_static("en-US,en;q=0.9"),
);
+ // Never waits for ever. After a sleep or a change of network a pooled connection can
+ // be dead without saying so, and a request on it hung until the kernel gave up — a
+ // quarter of an hour or more — holding the sign-in lock, so every screen waited too.
+ // A read that brings nothing for a minute is given up (a long download keeps going as
+ // long as bytes arrive); idle connections are let go of before they can go stale; and
+ // keep-alives notice a dead one.
let http = apple_only()
.cookie_provider(Arc::clone(&jar))
.user_agent(UA)
.default_headers(defaults)
+ .connect_timeout(std::time::Duration::from_secs(15))
+ .read_timeout(std::time::Duration::from_secs(60))
+ .pool_idle_timeout(std::time::Duration::from_secs(50))
+ .tcp_keepalive(std::time::Duration::from_secs(30))
.build()?;
Ok(Self {
@@ -471,7 +491,10 @@ impl Client {
// from sleep mid-reconnect — the session is left exactly as it is and the caller
// told so; signing in again here cleared the session token, failed on the network,
// and saved the cleared state, so every launch after showed the sign-in screen.
- if matches!(validated, Error::Network(_)) && matches!(logged_in, Error::Network(_)) {
+ // Offline, or Apple down for a while: the session is not dead, only unreachable — it
+ // is kept and tried again, rather than a sign-in that ends in "Apple signed you out".
+ let away = |e: &Error| matches!(e, Error::Network(_) | Error::Unavailable(_));
+ if away(&validated) && away(&logged_in) {
return Err(logged_in);
}
@@ -523,7 +546,8 @@ impl Client {
let status = r.status();
let body = r.text().await.unwrap_or_default();
if !status.is_success() {
- return Err(Error::Protocol(format!("validate returned {status}")));
+ return Err(transient(status)
+ .unwrap_or_else(|| Error::Protocol(format!("validate returned {status}"))));
}
Ok(serde_json::from_str(&body).unwrap_or(Value::Null))
}
@@ -958,9 +982,9 @@ impl Client {
let status = r.status();
let text = r.text().await.unwrap_or_default();
if !status.is_success() {
- return Err(Error::Protocol(format!(
- "couldn't open the account ({status})"
- )));
+ return Err(transient(status).unwrap_or_else(|| {
+ Error::Protocol(format!("couldn't open the account ({status})"))
+ }));
}
Ok(serde_json::from_str(&text)?)
}
@@ -1045,22 +1069,25 @@ impl Client {
}
}
-/// Whether `host` is Apple's: its sign-in, iCloud's services and their files, push, and their
-/// China-mainland twins — every host Skykeep has any reason to reach. Loopback too, which is
-/// this computer.
+/// The domains Apple's client can reach, each with every host under it: Apple's sign-in,
+/// iCloud's services and their files, push, and their China-mainland twins. What Settings
+/// lists as what Skykeep talks to, read from here so the list is the lock itself.
+pub const APPLE_DOMAINS: [&str; 6] = [
+ "apple.com",
+ "icloud.com",
+ "icloud-content.com",
+ "apple.com.cn",
+ "icloud.com.cn",
+ "icloud-content.com.cn",
+];
+
+/// Whether `host` is Apple's: under one of [`APPLE_DOMAINS`] — every host Skykeep has any
+/// reason to reach. Loopback too, which is this computer.
#[must_use]
pub fn is_apple_host(host: &str) -> bool {
let host = host.trim_end_matches('.').to_ascii_lowercase();
- const APPLE: [&str; 6] = [
- "apple.com",
- "icloud.com",
- "icloud-content.com",
- "apple.com.cn",
- "icloud.com.cn",
- "icloud-content.com.cn",
- ];
host == "localhost"
- || APPLE
+ || APPLE_DOMAINS
.iter()
.any(|d| host == *d || host.ends_with(&format!(".{d}")))
}
diff --git a/crates/quince-core/Cargo.toml b/crates/quince-core/Cargo.toml
index 6a6762e..b21831e 100644
--- a/crates/quince-core/Cargo.toml
+++ b/crates/quince-core/Cargo.toml
@@ -11,6 +11,7 @@ jiff = "0.2.37"
serde.workspace = true
thiserror = "2"
serde_json.workspace = true
+base64 = "0.22"
icu_normalizer = { version = "2.3", default-features = false, features = ["compiled_data"] }
[dev-dependencies]
diff --git a/crates/quince-core/src/contacts.rs b/crates/quince-core/src/contacts.rs
index 4a2b7bb..394c8c5 100644
--- a/crates/quince-core/src/contacts.rs
+++ b/crates/quince-core/src/contacts.rs
@@ -4,6 +4,102 @@ use crate::{Library, Result};
use rusqlite::params;
use serde::{Deserialize, Serialize};
+/// Apple's own names for the labels on a card's numbers, addresses, dates and people.
+#[path = "contacts_labels.rs"]
+pub mod labels;
+
+/// Cards that are one person twice, and putting them back together.
+#[path = "contacts_merge.rs"]
+pub mod merge;
+
+/// The rest of a person's name and work, as Apple's card holds them. Kept beside [`Contact`]
+/// rather than in it, so code that builds a `Contact` by hand is not made to name them.
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ContactDetails {
+ #[serde(default)]
+ pub prefix: Option<String>,
+ #[serde(default)]
+ pub suffix: Option<String>,
+ #[serde(default)]
+ pub nickname: Option<String>,
+ #[serde(default)]
+ pub phonetic_first_name: Option<String>,
+ #[serde(default)]
+ pub phonetic_last_name: Option<String>,
+ #[serde(default)]
+ pub phonetic_company: Option<String>,
+ #[serde(default)]
+ pub job_title: Option<String>,
+ #[serde(default)]
+ pub department: Option<String>,
+}
+
+/// Each detail by the key Apple's card names it with (`/co/` contact JSON).
+pub const DETAIL_KEYS: [&str; 8] = [
+ "prefix",
+ "suffix",
+ "nickName",
+ "phoneticFirstName",
+ "phoneticLastName",
+ "phoneticCompanyName",
+ "jobTitle",
+ "department",
+];
+
+impl ContactDetails {
+ /// One detail by Apple's key for it; `None` for a key that is not one.
+ #[must_use]
+ pub fn get(&self, key: &str) -> Option<&Option<String>> {
+ Some(match key {
+ "prefix" => &self.prefix,
+ "suffix" => &self.suffix,
+ "nickName" => &self.nickname,
+ "phoneticFirstName" => &self.phonetic_first_name,
+ "phoneticLastName" => &self.phonetic_last_name,
+ "phoneticCompanyName" => &self.phonetic_company,
+ "jobTitle" => &self.job_title,
+ "department" => &self.department,
+ _ => return None,
+ })
+ }
+
+ /// Set one detail by Apple's key, blank meaning cleared. False for a key that is not one.
+ pub fn set(&mut self, key: &str, value: Option<&str>) -> bool {
+ let slot = match key {
+ "prefix" => &mut self.prefix,
+ "suffix" => &mut self.suffix,
+ "nickName" => &mut self.nickname,
+ "phoneticFirstName" => &mut self.phonetic_first_name,
+ "phoneticLastName" => &mut self.phonetic_last_name,
+ "phoneticCompanyName" => &mut self.phonetic_company,
+ "jobTitle" => &mut self.job_title,
+ "department" => &mut self.department,
+ _ => return false,
+ };
+ *slot = clean(value);
+ true
+ }
+
+ /// Nothing in any of them.
+ #[must_use]
+ pub fn is_empty(&self) -> bool {
+ DETAIL_KEYS
+ .iter()
+ .all(|k| self.get(k).is_none_or(Option::is_none))
+ }
+}
+
+/// A whole card as the interface reads and writes it: the person and the rest of their name
+/// and work, side by side in one object.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+pub struct Card {
+ #[serde(flatten)]
+ pub contact: Contact,
+ #[serde(flatten)]
+ pub details: ContactDetails,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ContactMethod {
@@ -286,7 +382,7 @@ impl Contact {
}
/// Sorted on last name where there is one, which is how Apple orders the list.
- fn sort_key(&self) -> String {
+ pub(crate) fn sort_key(&self) -> String {
let key = [self.last_name.as_deref(), self.first_name.as_deref()]
.into_iter()
.flatten()
@@ -335,6 +431,91 @@ impl Library {
Ok(())
}
+ /// Store the rest of each card's name and work, as a read of the book found them. A whole
+ /// book clears every card's first, so a nickname taken off on the phone goes here too.
+ pub fn put_contact_details(
+ &mut self,
+ book: &[(String, ContactDetails)],
+ whole_book: bool,
+ ) -> Result<()> {
+ let tx = self.conn.savepoint()?;
+ if whole_book {
+ tx.execute(
+ "UPDATE contacts SET prefix = NULL, suffix = NULL, nickname = NULL,
+ phonetic_first_name = NULL, phonetic_last_name = NULL,
+ phonetic_company = NULL, job_title = NULL, department = NULL",
+ [],
+ )?;
+ }
+ {
+ let mut set = tx.prepare(
+ "UPDATE contacts SET prefix = ?2, suffix = ?3, nickname = ?4,
+ phonetic_first_name = ?5, phonetic_last_name = ?6, phonetic_company = ?7,
+ job_title = ?8, department = ?9
+ WHERE guid = ?1",
+ )?;
+ for (guid, d) in book {
+ set.execute(params![
+ guid,
+ d.prefix,
+ d.suffix,
+ d.nickname,
+ d.phonetic_first_name,
+ d.phonetic_last_name,
+ d.phonetic_company,
+ d.job_title,
+ d.department
+ ])?;
+ }
+ }
+ tx.commit()?;
+ Ok(())
+ }
+
+ /// One card, whole, as it now stands — made or edited here — leaving everyone else as
+ /// they are.
+ pub fn put_card(&mut self, card: &Card) -> Result<()> {
+ self.atomically(|l| {
+ l.put_contact(&card.contact)?;
+ l.put_contact_details(&[(card.contact.guid.clone(), card.details.clone())], false)
+ })
+ }
+
+ /// The rest of one card's name and work.
+ pub fn contact_details(&self, guid: &str) -> Result<ContactDetails> {
+ Ok(self
+ .details_by_guid(Some(guid))?
+ .remove(guid)
+ .unwrap_or_default())
+ }
+
+ fn details_by_guid(
+ &self,
+ guid: Option<&str>,
+ ) -> Result<std::collections::HashMap<String, ContactDetails>> {
+ let mut stmt = self.conn.prepare(
+ "SELECT guid, prefix, suffix, nickname, phonetic_first_name, phonetic_last_name,
+ phonetic_company, job_title, department
+ FROM contacts WHERE ?1 IS NULL OR guid = ?1",
+ )?;
+ let rows = stmt.query_map(params![guid], |row| {
+ Ok((
+ row.get::<_, String>(0)?,
+ ContactDetails {
+ prefix: row.get(1)?,
+ suffix: row.get(2)?,
+ nickname: row.get(3)?,
+ phonetic_first_name: row.get(4)?,
+ phonetic_last_name: row.get(5)?,
+ phonetic_company: row.get(6)?,
+ job_title: row.get(7)?,
+ department: row.get(8)?,
+ },
+ ))
+ })?;
+ Ok(rows.collect::<rusqlite::Result<_>>()?)
+ }
+
fn store_contacts(&mut self, contacts: &[Contact], whole_book: bool) -> Result<()> {
let tx = self.conn.savepoint()?;
{
@@ -561,6 +742,12 @@ impl Library {
/// "+91 98765-43210". That is done here rather than in SQL, which folds ASCII alone and
/// knows nothing about phone formatting.
pub fn contacts(&self, search: Option<&str>) -> Result<Vec<Contact>> {
+ Ok(self.cards(search)?.into_iter().map(|c| c.contact).collect())
+ }
+
+ /// [`Library::contacts`], each card whole: with the rest of its name and work, which a
+ /// search matches too — a nickname or a job title finds the person.
+ pub fn cards(&self, search: Option<&str>) -> Result<Vec<Card>> {
let words = crate::fold::words(search.unwrap_or(""));
let mut stmt = self.conn.prepare(
@@ -612,12 +799,22 @@ impl Library {
for contact in &mut contacts {
contact.methods = methods.remove(&contact.guid).unwrap_or_default();
}
+ let mut details = self.details_by_guid(None)?;
+ let mut cards: Vec<Card> = contacts
+ .into_iter()
+ .map(|contact| Card {
+ details: details.remove(&contact.guid).unwrap_or_default(),
+ contact,
+ })
+ .collect();
if !words.is_empty() {
- contacts.retain(|c| c.matches(&words));
+ cards.retain(|c| c.contact.matches(&words, &c.details));
}
- let mut keyed: Vec<(String, Contact)> =
- contacts.into_iter().map(|c| (c.sort_key(), c)).collect();
+ let mut keyed: Vec<(String, Card)> = cards
+ .into_iter()
+ .map(|c| (c.contact.sort_key(), c))
+ .collect();
keyed.sort_by(|(a, _), (b, _)| crate::fold::natural(a, b));
Ok(keyed.into_iter().map(|(_, c)| c).collect())
}
@@ -665,18 +862,24 @@ fn looks_like_number(word: &str) -> bool {
}
impl Contact {
- fn matches(&self, words: &[String]) -> bool {
+ fn matches(&self, words: &[String], details: &ContactDetails) -> bool {
let mut text = [
self.first_name.as_deref(),
self.middle_name.as_deref(),
self.last_name.as_deref(),
self.company.as_deref(),
+ details.nickname.as_deref(),
+ details.job_title.as_deref(),
+ details.department.as_deref(),
+ details.phonetic_first_name.as_deref(),
+ details.phonetic_last_name.as_deref(),
]
.into_iter()
.flatten()
.collect::<Vec<_>>()
.join(" ");
- for m in &self.methods {
+ // A date is not something a person searches for by its digits.
+ for m in self.methods.iter().filter(|m| m.kind != "date") {
text.push('\n');
text.push_str(&m.value);
}
diff --git a/crates/quince-core/src/contacts_labels.rs b/crates/quince-core/src/contacts_labels.rs
new file mode 100644
index 0000000..0443912
--- /dev/null
+++ b/crates/quince-core/src/contacts_labels.rs
@@ -0,0 +1,187 @@
+//! Apple's own names for the labels on a card's numbers, emails, links, addresses, dates and
+//! related people.
+//!
+//! A label reaches this app in one of two spellings. Contacts on the phone and the Mac keep
+//! Apple's internal token, `_$!<Mobile>!$_`, and a vCard carries it as `X-ABLabel`. Apple's web
+//! service (`/co/`, what this app reads and writes) hands the same label out in its own upper
+//! case — `MOBILE` — and takes it back that way; icloud.com's editor writes nothing else
+//! (contacts2 bundle, 2026-10). Anything that is neither is a custom label, kept as typed.
+//!
+//! So a label is compared and shown through here, by what it means, and a label already on a
+//! card is written back exactly as it came: neither spelling is ever rewritten into the other.
+
+/// One label Apple knows: how `/co/` spells it, Apple's internal token, and how a card shows it.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Known {
+ pub wire: &'static str,
+ pub token: &'static str,
+ pub shown: &'static str,
+}
+
+const fn k(wire: &'static str, token: &'static str, shown: &'static str) -> Known {
+ Known { wire, token, shown }
+}
+
+/// Every label Apple names, from icloud.com's editor and the Contacts framework's constants.
+pub const KNOWN: &[Known] = &[
+ k("MOBILE", "_$!<Mobile>!$_", "mobile"),
+ k("IPHONE", "iPhone", "iPhone"),
+ k("APPLE WATCH", "_$!<AppleWatch>!$_", "Apple Watch"),
+ k("HOME", "_$!<Home>!$_", "home"),
+ k("WORK", "_$!<Work>!$_", "work"),
+ k("SCHOOL", "_$!<School>!$_", "school"),
+ k("MAIN", "_$!<Main>!$_", "main"),
+ k("HOME FAX", "_$!<HomeFAX>!$_", "home fax"),
+ k("WORK FAX", "_$!<WorkFAX>!$_", "work fax"),
+ k("OTHER FAX", "_$!<OtherFAX>!$_", "other fax"),
+ k("PAGER", "_$!<Pager>!$_", "pager"),
+ k("PHONE", "_$!<Phone>!$_", "phone"),
+ k("OTHER", "_$!<Other>!$_", "other"),
+ k("ICLOUD", "iCloud", "iCloud"),
+ k("HOMEPAGE", "_$!<HomePage>!$_", "homepage"),
+ k("BLOG", "_$!<Blog>!$_", "blog"),
+ k("ANNIVERSARY", "_$!<Anniversary>!$_", "anniversary"),
+ k("BIRTHDAY", "_$!<Birthday>!$_", "birthday"),
+ k("MOTHER", "_$!<Mother>!$_", "mother"),
+ k("FATHER", "_$!<Father>!$_", "father"),
+ k("PARENT", "_$!<Parent>!$_", "parent"),
+ k("BROTHER", "_$!<Brother>!$_", "brother"),
+ k("SISTER", "_$!<Sister>!$_", "sister"),
+ k("SON", "_$!<Son>!$_", "son"),
+ k("DAUGHTER", "_$!<Daughter>!$_", "daughter"),
+ k("CHILD", "_$!<Child>!$_", "child"),
+ k("FRIEND", "_$!<Friend>!$_", "friend"),
+ k("SPOUSE", "_$!<Spouse>!$_", "spouse"),
+ k("PARTNER", "_$!<Partner>!$_", "partner"),
+ k("ASSISTANT", "_$!<Assistant>!$_", "assistant"),
+ k("MANAGER", "_$!<Manager>!$_", "manager"),
+];
+
+/// The labels icloud.com's editor offers for each kind of detail, in its order, `OTHER` last
+/// as it adds it. Instant messaging is labelled by its service; a social profile by its network.
+#[must_use]
+pub fn offered(kind: &str) -> &'static [&'static str] {
+ match kind {
+ "phone" => &[
+ "MOBILE",
+ "IPHONE",
+ "APPLE WATCH",
+ "HOME",
+ "WORK",
+ "SCHOOL",
+ "MAIN",
+ "HOME FAX",
+ "WORK FAX",
+ "PAGER",
+ "OTHER",
+ ],
+ "email" => &["HOME", "WORK", "SCHOOL", "ICLOUD", "OTHER"],
+ "url" => &["HOMEPAGE", "HOME", "WORK", "SCHOOL", "OTHER"],
+ "address" => &["HOME", "WORK", "SCHOOL", "OTHER"],
+ "date" => &["ANNIVERSARY", "OTHER"],
+ "related" => &[
+ "MOTHER",
+ "FATHER",
+ "PARENT",
+ "BROTHER",
+ "SISTER",
+ "SON",
+ "DAUGHTER",
+ "CHILD",
+ "FRIEND",
+ "SPOUSE",
+ "PARTNER",
+ "ASSISTANT",
+ "MANAGER",
+ "OTHER",
+ ],
+ "im" => &[
+ "AIM",
+ "YAHOO",
+ "MSN",
+ "ICQ",
+ "JABBER",
+ "SKYPE",
+ "GOOGLETALK",
+ "FACEBOOK",
+ "QQ",
+ "GADUGADU",
+ ],
+ "profile" => &[
+ "TWITTER",
+ "FACEBOOK",
+ "FLICKR",
+ "LINKEDIN",
+ "MYSPACE",
+ "SINAWEIBO",
+ ],
+ _ => &[],
+ }
+}
+
+/// The label Apple means, in either spelling and any case; `None` for a custom label.
+#[must_use]
+pub fn known(label: &str) -> Option<&'static Known> {
+ let label = label.trim();
+ KNOWN.iter().find(|k| {
+ k.wire.eq_ignore_ascii_case(label)
+ || k.token.eq_ignore_ascii_case(label)
+ || k.shown.eq_ignore_ascii_case(label)
+ })
+}
+
+/// How a card shows a label: Apple's own word for one it knows, a custom one as typed.
+#[must_use]
+pub fn shown(label: &str) -> String {
+ known(label).map_or_else(|| label.trim().to_string(), |k| k.shown.to_string())
+}
+
+/// What a label means, for comparing two: Apple's spelling of one it knows, a custom one
+/// folded. `MOBILE`, `mobile` and `_$!<Mobile>!$_` are one label.
+#[must_use]
+pub fn meaning(label: Option<&str>) -> String {
+ match label.map(str::trim).filter(|l| !l.is_empty()) {
+ None => String::new(),
+ Some(l) => known(l).map_or_else(|| crate::fold::fold(l), |k| k.wire.to_string()),
+ }
+}
+
+/// Whether two labels say the same thing, however each is spelled.
+#[must_use]
+pub fn same(a: Option<&str>, b: Option<&str>) -> bool {
+ meaning(a) == meaning(b)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn both_spellings_of_a_label_mean_one_thing() {
+ assert!(same(Some("MOBILE"), Some("_$!<Mobile>!$_")));
+ assert!(same(Some("mobile"), Some("MOBILE")));
+ assert!(same(Some("HOME FAX"), Some("_$!<HomeFAX>!$_")));
+ assert!(!same(Some("HOME"), Some("WORK")));
+ assert!(same(None, Some(" ")));
+ }
+
+ #[test]
+ fn a_label_is_shown_in_apples_words_and_a_custom_one_as_typed() {
+ assert_eq!(shown("_$!<Mobile>!$_"), "mobile");
+ assert_eq!(shown("IPHONE"), "iPhone");
+ assert_eq!(shown("APPLE WATCH"), "Apple Watch");
+ assert_eq!(shown("ICLOUD"), "iCloud");
+ assert_eq!(shown("_$!<Anniversary>!$_"), "anniversary");
+ assert_eq!(shown("Grandma's landline"), "Grandma's landline");
+ assert_eq!(meaning(Some("Grandma's Landline")), "grandma's landline");
+ }
+
+ #[test]
+ fn every_label_offered_is_one_apple_knows_or_a_service() {
+ for kind in ["phone", "email", "url", "address", "date", "related"] {
+ for label in offered(kind) {
+ assert!(known(label).is_some(), "{kind}: {label}");
+ }
+ }
+ }
+}
diff --git a/crates/quince-core/src/contacts_merge.rs b/crates/quince-core/src/contacts_merge.rs
new file mode 100644
index 0000000..509b77b
--- /dev/null
+++ b/crates/quince-core/src/contacts_merge.rs
@@ -0,0 +1,515 @@
+//! Cards that are one person twice, found and put back together.
+//!
+//! Found the way Contacts on the iPhone finds them: the same name, or a phone number or an
+//! email address two cards share — numbers compared by their digits, so "+91 90000 00001" and
+//! "090000 00001" are one. Put together without losing anything: every number, address, date
+//! and person from every card, a name or a job filled from whichever card has one, notes from
+//! each, and a picture kept.
+
+use super::{labels, Card, Contact, ContactMethod, PostalAddress, DETAIL_KEYS};
+use serde::Serialize;
+use std::collections::HashMap;
+
+/// A number as the digits that identify it: formatting, a trunk `0` and a country code aside
+/// (its last ten), an extension cut off. `None` for fewer than seven digits — too short to say
+/// two cards are one person.
+#[must_use]
+pub fn phone_key(value: &str) -> Option<String> {
+ let lower = value.to_ascii_lowercase();
+ let main = lower
+ .split([',', ';', 'x'])
+ .next()
+ .unwrap_or("")
+ .split("ext")
+ .next()
+ .unwrap_or("");
+ let digits: String = main.chars().filter(char::is_ascii_digit).collect();
+ (digits.len() >= 7).then(|| digits[digits.len().saturating_sub(10)..].to_string())
+}
+
+/// What makes two of a card's details the same detail: a number's digits, an address's
+/// letters folded, any other value folded and trimmed.
+#[must_use]
+pub fn method_key(m: &ContactMethod) -> String {
+ let folded = crate::fold::fold(m.value.trim());
+ match m.kind.as_str() {
+ "phone" => format!(
+ "phone:{}",
+ phone_key(&m.value).unwrap_or_else(|| folded.clone())
+ ),
+ "email" => format!("email:{}", m.value.trim().to_lowercase()),
+ "im" | "profile" => format!(
+ "{}:{}:{}",
+ m.kind,
+ labels::meaning(m.label.as_deref()),
+ folded.trim_start_matches('@')
+ ),
+ "related" | "date" => format!(
+ "{}:{}:{}",
+ m.kind,
+ labels::meaning(m.label.as_deref()),
+ folded
+ ),
+ kind => format!(
+ "{kind}:{}",
+ folded.split_whitespace().collect::<Vec<_>>().join(" ")
+ ),
+ }
+}
+
+/// A person's name as compared for duplicates: first, middle and last folded, or a company's
+/// name when the card is a company. `None` when there is no name to go on.
+fn name_key(c: &Contact) -> Option<String> {
+ let name = if c.is_company {
+ c.company.clone().unwrap_or_default()
+ } else {
+ [&c.first_name, &c.middle_name, &c.last_name]
+ .into_iter()
+ .flatten()
+ .map(String::as_str)
+ .collect::<Vec<_>>()
+ .join(" ")
+ };
+ let folded = crate::fold::fold(&name)
+ .split_whitespace()
+ .collect::<Vec<_>>()
+ .join(" ");
+ (folded.chars().count() >= 2).then_some(folded)
+}
+
+/// Cards that look like one person, and what they have in common.
+#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct Duplicates {
+ /// In the address book's order.
+ pub guids: Vec<String>,
+ /// What they share, of `name`, `phone` and `email`.
+ pub reasons: Vec<String>,
+}
+
+/// Every group of two or more cards that share a name, a number or an email address, in the
+/// address book's order. Shared through a third counts: A has B's number and C's name, so all
+/// three are one person.
+#[must_use]
+pub fn find_duplicates(book: &[Contact]) -> Vec<Duplicates> {
+ let mut parent: Vec<usize> = (0..book.len()).collect();
+ fn root(parent: &mut [usize], mut i: usize) -> usize {
+ while parent[i] != i {
+ parent[i] = parent[parent[i]];
+ i = parent[i];
+ }
+ i
+ }
+ // Each key, the first card that had it and why it counts.
+ let mut first: HashMap<String, usize> = HashMap::new();
+ let mut shared: HashMap<String, Vec<usize>> = HashMap::new();
+ for (i, c) in book.iter().enumerate() {
+ let mut keys: Vec<String> = Vec::new();
+ if let Some(n) = name_key(c) {
+ keys.push(format!("name:{n}"));
+ }
+ for m in &c.methods {
+ match m.kind.as_str() {
+ "phone" => {
+ if let Some(p) = phone_key(&m.value) {
+ keys.push(format!("phone:{p}"));
+ }
+ }
+ "email" => {
+ let e = m.value.trim().to_lowercase();
+ if e.contains('@') {
+ keys.push(format!("email:{e}"));
+ }
+ }
+ _ => {}
+ }
+ }
+ keys.sort();
+ keys.dedup();
+ for key in keys {
+ shared.entry(key.clone()).or_default().push(i);
+ match first.get(&key) {
+ Some(&j) => {
+ let (a, b) = (root(&mut parent, i), root(&mut parent, j));
+ if a != b {
+ parent[a.max(b)] = a.min(b);
+ }
+ }
+ None => {
+ first.insert(key, i);
+ }
+ }
+ }
+ }
+ let mut groups: HashMap<usize, Vec<usize>> = HashMap::new();
+ for i in 0..book.len() {
+ let r = root(&mut parent, i);
+ groups.entry(r).or_default().push(i);
+ }
+ let mut out: Vec<(usize, Duplicates)> = groups
+ .into_values()
+ .filter(|g| g.len() > 1)
+ .map(|mut g| {
+ g.sort_unstable();
+ let mut reasons: Vec<String> = shared
+ .iter()
+ .filter(|(_, who)| who.len() > 1 && who.iter().all(|w| g.contains(w)))
+ .filter_map(|(k, _)| k.split(':').next().map(ToString::to_string))
+ .collect();
+ reasons.sort_by_key(|r| ["name", "phone", "email"].iter().position(|x| x == r));
+ reasons.dedup();
+ (
+ g[0],
+ Duplicates {
+ guids: g.iter().map(|&i| book[i].guid.clone()).collect(),
+ reasons,
+ },
+ )
+ })
+ .collect();
+ out.sort_by_key(|(i, _)| *i);
+ out.into_iter().map(|(_, d)| d).collect()
+}
+
+/// How much a card holds, for choosing which of several to keep.
+fn richness(c: &Card) -> usize {
+ let p = &c.contact;
+ let names = [
+ &p.first_name,
+ &p.middle_name,
+ &p.last_name,
+ &p.company,
+ &p.birthday,
+ &p.notes,
+ ]
+ .into_iter()
+ .filter(|v| v.as_deref().is_some_and(|s| !s.trim().is_empty()))
+ .count();
+ let details = DETAIL_KEYS
+ .iter()
+ .filter(|k| c.details.get(k).is_some_and(Option::is_some))
+ .count();
+ names + details + p.methods.len()
+}
+
+/// Which card the others are merged into: this person's own card when it is one of them —
+/// so My Card stays My Card — else one with a picture, else the one holding the most, else
+/// the first.
+#[must_use]
+pub fn survivor(cards: &[Card], me: Option<&str>) -> usize {
+ if let Some(i) = me.and_then(|me| cards.iter().position(|c| c.contact.guid == me)) {
+ return i;
+ }
+ let mut best = 0;
+ for (i, c) in cards.iter().enumerate().skip(1) {
+ let rank = |c: &Card| (c.contact.photo_url.is_some(), richness(c));
+ if rank(c) > rank(&cards[best]) {
+ best = i;
+ }
+ }
+ best
+}
+
+fn filled(v: &Option<String>) -> bool {
+ v.as_deref().is_some_and(|s| !s.trim().is_empty())
+}
+
+/// Notes from each card, each once, a blank line between: none dropped, none repeated —
+/// merging the merged card again adds nothing.
+#[must_use]
+pub fn joined_notes<'a>(notes: impl IntoIterator<Item = Option<&'a str>>) -> Option<String> {
+ let mut out = String::new();
+ for n in notes.into_iter().flatten().map(str::trim) {
+ if n.is_empty() || out.contains(n) {
+ continue;
+ }
+ if !out.is_empty() {
+ out.push_str("\n\n");
+ }
+ out.push_str(n);
+ }
+ (!out.is_empty()).then_some(out)
+}
+
+/// The cards as one: `survivor`'s id, version and choices, with everything the others hold
+/// that it lacks. A name, a company, a birthday or a detail is the survivor's when it has one,
+/// else the first other card's that does; every number, email, link, profile, date and person
+/// is kept, each once (labels aside: the survivor's label stands); notes from each are joined;
+/// the picture is the survivor's, else the first other card's. Addresses are merged on their
+/// own ([`merged_addresses`]); the flattened address lines are left to them.
+#[must_use]
+pub fn merged(survivor: &Card, others: &[Card]) -> Card {
+ let mut out = survivor.clone();
+ let c = &mut out.contact;
+ for other in others {
+ let o = &other.contact;
+ for (mine, theirs) in [
+ (&mut c.first_name, &o.first_name),
+ (&mut c.middle_name, &o.middle_name),
+ (&mut c.last_name, &o.last_name),
+ (&mut c.company, &o.company),
+ (&mut c.birthday, &o.birthday),
+ ] {
+ if !filled(mine) && filled(theirs) {
+ mine.clone_from(theirs);
+ }
+ }
+ for key in DETAIL_KEYS {
+ let theirs = other.details.get(key).cloned().flatten();
+ if out.details.get(key).is_some_and(|v| !filled(v)) && theirs.is_some() {
+ out.details.set(key, theirs.as_deref());
+ }
+ }
+ if c.photo_url.is_none() && o.photo_url.is_some() {
+ c.photo_url.clone_from(&o.photo_url);
+ c.photo_signature.clone_from(&o.photo_signature);
+ c.photo_crop.clone_from(&o.photo_crop);
+ }
+ }
+ c.notes = joined_notes(
+ std::iter::once(survivor.contact.notes.as_deref())
+ .chain(others.iter().map(|o| o.contact.notes.as_deref())),
+ );
+ let mut seen: Vec<String> = c.methods.iter().map(method_key).collect();
+ for other in others {
+ for m in other.contact.methods.iter().filter(|m| m.kind != "address") {
+ let key = method_key(m);
+ if !seen.contains(&key) {
+ seen.push(key);
+ c.methods.push(m.clone());
+ }
+ }
+ }
+ out
+}
+
+/// Every card's addresses, each once — the same address written with different spacing or
+/// case is one — the first card's first.
+#[must_use]
+pub fn merged_addresses(lists: &[Vec<PostalAddress>]) -> Vec<PostalAddress> {
+ let key = |a: &PostalAddress| {
+ crate::fold::fold(&a.formatted())
+ .split_whitespace()
+ .collect::<Vec<_>>()
+ .join(" ")
+ };
+ let mut seen: Vec<String> = Vec::new();
+ let mut out = Vec::new();
+ for a in lists.iter().flatten().filter(|a| !a.is_empty()) {
+ let k = key(a);
+ if !seen.contains(&k) {
+ seen.push(k);
+ out.push(a.clone());
+ }
+ }
+ out
+}
+
+/// A card's details that the merge would add to `survivor`, for saying so before it is done.
+#[must_use]
+pub fn added_count(survivor: &Card, merged: &Card) -> usize {
+ let before = survivor.contact.methods.len();
+ merged.contact.methods.len().saturating_sub(before)
+ + DETAIL_KEYS
+ .iter()
+ .filter(|k| {
+ survivor.details.get(k).is_some_and(|v| !filled(v))
+ && merged.details.get(k).is_some_and(filled)
+ })
+ .count()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::contacts::ContactDetails;
+
+ fn person(guid: &str, first: &str, last: &str, methods: &[(&str, &str, &str)]) -> Card {
+ Card {
+ contact: Contact {
+ guid: guid.into(),
+ first_name: Some(first.into()).filter(|s: &String| !s.is_empty()),
+ middle_name: None,
+ photo_url: None,
+ photo_signature: None,
+ photo_crop: None,
+ last_name: Some(last.into()).filter(|s: &String| !s.is_empty()),
+ company: None,
+ is_company: false,
+ birthday: None,
+ notes: None,
+ etag: None,
+ methods: methods
+ .iter()
+ .map(|(k, l, v)| ContactMethod {
+ kind: (*k).into(),
+ label: Some((*l).into()).filter(|s: &String| !s.is_empty()),
+ value: (*v).into(),
+ })
+ .collect(),
+ },
+ details: ContactDetails::default(),
+ }
+ }
+
+ #[test]
+ fn a_number_is_its_digits_however_it_was_typed() {
+ assert_eq!(phone_key("+91 90000-00001"), phone_key("090000 00001"));
+ assert_eq!(
+ phone_key("(555) 010-0199 ext. 4"),
+ phone_key("555 010 0199")
+ );
+ assert_eq!(phone_key("112"), None, "too short to say who it is");
+ }
+
+ #[test]
+ fn cards_sharing_a_name_a_number_or_an_email_are_found_together() {
+ let book: Vec<Contact> = [
+ person(
+ "A",
+ "Zoya",
+ "Ahuja",
+ &[("phone", "MOBILE", "+91 90000 00001")],
+ ),
+ person("B", "Zoya", "", &[("phone", "", "090000 00001")]),
+ person("C", "Z.", "Ahuja", &[("email", "HOME", "[email protected]")]),
+ person(
+ "D",
+ "Zoe",
+ "Ahuja",
+ &[("email", "WORK", "[email protected] ")],
+ ),
+ person("E", "Ravi", "Nair", &[("phone", "", "+91 98765 43210")]),
+ person("F", "Émile", "Zola", &[]),
+ person("G", "EMILE", "ZOLA", &[]),
+ ]
+ .into_iter()
+ .map(|c| c.contact)
+ .collect();
+ let found = find_duplicates(&book);
+ assert_eq!(found.len(), 3, "{found:?}");
+ assert_eq!(found[0].guids, ["A", "B"]);
+ assert_eq!(found[0].reasons, ["phone"]);
+ assert_eq!(found[1].guids, ["C", "D"]);
+ assert_eq!(found[1].reasons, ["email"]);
+ assert_eq!(found[2].guids, ["F", "G"], "accents and case aside");
+ assert_eq!(found[2].reasons, ["name"]);
+ }
+
+ #[test]
+ fn a_link_through_a_third_card_joins_all_three() {
+ let book: Vec<Contact> = [
+ person("A", "Asha", "Rao", &[("phone", "", "+91 90000 00009")]),
+ person(
+ "B",
+ "A",
+ "R",
+ &[("phone", "", "90000 00009"), ("email", "", "[email protected]")],
+ ),
+ person("C", "Asha R", "", &[("email", "", "[email protected]")]),
+ ]
+ .into_iter()
+ .map(|c| c.contact)
+ .collect();
+ let found = find_duplicates(&book);
+ assert_eq!(found.len(), 1);
+ assert_eq!(found[0].guids, ["A", "B", "C"]);
+ }
+
+ #[test]
+ fn a_card_with_nothing_to_go_on_is_never_a_duplicate() {
+ let book: Vec<Contact> = [person("A", "", "", &[]), person("B", "", "", &[])]
+ .into_iter()
+ .map(|c| c.contact)
+ .collect();
+ assert!(find_duplicates(&book).is_empty());
+ }
+
+ #[test]
+ fn merging_loses_nothing_and_repeats_nothing() {
+ let mut a = person(
+ "A",
+ "Zoya",
+ "Ahuja",
+ &[
+ ("phone", "MOBILE", "+91 90000 00001"),
+ ("related", "MOTHER", "Amma"),
+ ],
+ );
+ a.contact.notes = Some("Met at the conference".into());
+ let mut b = person(
+ "B",
+ "Zoya",
+ "",
+ &[
+ ("phone", "_$!<Mobile>!$_", "090000 00001"),
+ ("email", "HOME", "[email protected]"),
+ ("date", "ANNIVERSARY", "2015-02-14"),
+ ],
+ );
+ b.contact.notes = Some("Prefers WhatsApp".into());
+ b.contact.birthday = Some("1604-03-17".into());
+ b.contact.photo_url = Some("https://p/B".into());
+ b.details.job_title = Some("Architect".into());
+ b.details.nickname = Some("Zo".into());
+ a.details.nickname = Some("Zee".into());
+
+ let m = merged(&a, std::slice::from_ref(&b));
+ assert_eq!(m.contact.guid, "A");
+ assert_eq!(m.contact.last_name.as_deref(), Some("Ahuja"));
+ assert_eq!(m.contact.birthday.as_deref(), Some("1604-03-17"));
+ assert_eq!(m.details.job_title.as_deref(), Some("Architect"));
+ assert_eq!(
+ m.details.nickname.as_deref(),
+ Some("Zee"),
+ "the kept card's stands"
+ );
+ assert_eq!(
+ m.contact.photo_url.as_deref(),
+ Some("https://p/B"),
+ "the picture kept"
+ );
+ assert_eq!(
+ m.contact.notes.as_deref(),
+ Some("Met at the conference\n\nPrefers WhatsApp")
+ );
+ let kinds: Vec<&str> = m.contact.methods.iter().map(|m| m.kind.as_str()).collect();
+ assert_eq!(
+ kinds,
+ ["phone", "related", "email", "date"],
+ "one phone, not two"
+ );
+ assert_eq!(added_count(&a, &m), 3);
+
+ // Merged again — a merge sent twice — nothing more is added.
+ let again = merged(&m, std::slice::from_ref(&b));
+ assert_eq!(again, m);
+ }
+
+ #[test]
+ fn my_card_is_kept_else_the_one_with_a_picture_else_the_fullest() {
+ let a = person("A", "Zoya", "", &[]);
+ let mut b = person("B", "Zoya", "Ahuja", &[("phone", "", "+91 90000 00001")]);
+ let mut c = person("C", "Zoya", "", &[]);
+ assert_eq!(survivor(&[a.clone(), b.clone(), c.clone()], None), 1);
+ c.contact.photo_url = Some("u".into());
+ assert_eq!(survivor(&[a.clone(), b.clone(), c.clone()], None), 2);
+ b.contact.guid = "ME".into();
+ assert_eq!(survivor(&[a, b, c], Some("ME")), 1);
+ }
+
+ #[test]
+ fn the_same_address_twice_is_kept_once() {
+ let home = |street: &str| PostalAddress {
+ label: Some("HOME".into()),
+ street: Some(street.into()),
+ city: Some("Pune".into()),
+ ..PostalAddress::default()
+ };
+ let all = merged_addresses(&[
+ vec![home("2 New Rd")],
+ vec![home("2 new rd"), home("9 Hill St")],
+ ]);
+ assert_eq!(all, [home("2 New Rd"), home("9 Hill St")]);
+ }
+}
diff --git a/crates/quince-core/src/notes.rs b/crates/quince-core/src/notes.rs
index f6b6eff..a357372 100644
--- a/crates/quince-core/src/notes.rs
+++ b/crates/quince-core/src/notes.rs
@@ -138,6 +138,17 @@ impl Library {
Ok(())
}
+ /// A note edited here, now: its time edited moved on (never back), so it goes to the top
+ /// of a list ordered by Date Edited at once, as the phone puts it, rather than at the next
+ /// pass.
+ pub fn touch_note(&mut self, guid: &str, at: i64) -> Result<()> {
+ self.conn.execute(
+ "UPDATE notes SET modified_at = MAX(COALESCE(modified_at, 0), ?2) WHERE guid = ?1",
+ params![guid, at],
+ )?;
+ Ok(())
+ }
+
/// A note's formatting as just saved — Apple's runs, as JSON — so a read before the next
/// pass finds runs that describe the text it was just given.
pub fn set_note_runs(&mut self, guid: &str, runs: &str) -> Result<()> {
diff --git a/crates/quince-core/src/outbox.rs b/crates/quince-core/src/outbox.rs
index 608db74..eda4be5 100644
--- a/crates/quince-core/src/outbox.rs
+++ b/crates/quince-core/src/outbox.rs
@@ -251,6 +251,26 @@ impl Library {
Ok(())
}
+ /// A waiting change taken back before any of it was sent: gone from the queue. False when
+ /// it may already be on its way (or is not waiting), and so cannot be taken back.
+ pub fn outbox_withdraw(&mut self, id: i64) -> Result<bool> {
+ let n = self.conn.execute(
+ "DELETE FROM outbox WHERE id = ?1 AND tries = 0 AND refused_at IS NULL",
+ params![id],
+ )?;
+ Ok(n == 1)
+ }
+
+ /// A change taken to send that reached nothing at Apple — it failed before its first
+ /// write — counted as never tried, so it can still be taken back.
+ pub fn outbox_untry(&mut self, id: i64) -> Result<()> {
+ self.conn.execute(
+ "UPDATE outbox SET tries = 0 WHERE id = ?1 AND refused_at IS NULL",
+ params![id],
+ )?;
+ Ok(())
+ }
+
/// The list a reminder is in, if it is in the library.
pub fn reminder_list_of(&self, guid: &str) -> Result<Option<String>> {
Ok(self
diff --git a/crates/quince-core/src/photos.rs b/crates/quince-core/src/photos.rs
index 624c145..550eb97 100644
--- a/crates/quince-core/src/photos.rs
+++ b/crates/quince-core/src/photos.rs
@@ -208,6 +208,46 @@ fn row_to_photo(r: &rusqlite::Row<'_>) -> rusqlite::Result<Photo> {
})
}
+/// What is typed, as SQL: one condition per word (each its own parameter — what is typed is
+/// never part of the SQL), every word to match the file's name, title, caption or a keyword, or
+/// the year or month it was taken. `None` when nothing is typed.
+fn search_terms(query: &str) -> Option<(String, Vec<String>)> {
+ let words: Vec<String> = query
+ .split_whitespace()
+ .map(|w| w.to_lowercase())
+ .filter(|w| !w.is_empty())
+ .take(8)
+ .collect();
+ if words.is_empty() {
+ return None;
+ }
+ let one = "(LOWER(COALESCE(filename, '')) LIKE ?{n} ESCAPE '\\'
+ OR LOWER(COALESCE(title, '')) LIKE ?{n} ESCAPE '\\'
+ OR LOWER(COALESCE(caption, '')) LIKE ?{n} ESCAPE '\\'
+ OR LOWER(COALESCE(keywords, '')) LIKE ?{n} ESCAPE '\\'
+ OR strftime('%Y', taken_at, 'unixepoch', 'localtime') LIKE ?{n} ESCAPE '\\'
+ OR (CASE strftime('%m', taken_at, 'unixepoch', 'localtime')
+ WHEN '01' THEN 'january' WHEN '02' THEN 'february' WHEN '03' THEN 'march'
+ WHEN '04' THEN 'april' WHEN '05' THEN 'may' WHEN '06' THEN 'june'
+ WHEN '07' THEN 'july' WHEN '08' THEN 'august' WHEN '09' THEN 'september'
+ WHEN '10' THEN 'october' WHEN '11' THEN 'november' ELSE 'december' END)
+ LIKE ?{n} ESCAPE '\\')";
+ let conditions: Vec<String> = (1..=words.len())
+ .map(|n| one.replace("{n}", &n.to_string()))
+ .collect();
+ let patterns = words
+ .iter()
+ .map(|w| {
+ let escaped = w
+ .replace('\\', "\\\\")
+ .replace('%', "\\%")
+ .replace('_', "\\_");
+ format!("%{escaped}%")
+ })
+ .collect();
+ Some((conditions.join(" AND "), patterns))
+}
+
impl Library {
/// Photos written or replaced, by asset id.
pub fn put_photos(&mut self, photos: &[Photo]) -> Result<()> {
@@ -310,12 +350,17 @@ impl Library {
if !photos.iter().any(|p| p.burst.is_some()) {
return Ok(photos);
}
- let mut stmt = self.conn.prepare(
- "SELECT burst, COUNT(*) FROM photos WHERE burst IS NOT NULL AND deleted = 0 GROUP BY burst",
- )?;
- let sizes: std::collections::HashMap<String, i64> = stmt
- .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))?
- .collect::<std::result::Result<_, _>>()?;
+ // Counted for the bursts here only: a page of two hundred never counts the library's.
+ let mut stmt = self
+ .conn
+ .prepare_cached("SELECT COUNT(*) FROM photos WHERE burst = ?1 AND deleted = 0")?;
+ let mut sizes: std::collections::HashMap<String, i64> = std::collections::HashMap::new();
+ for b in photos.iter().filter_map(|p| p.burst.as_ref()) {
+ if !sizes.contains_key(b) {
+ let n: i64 = stmt.query_row(params![b], |r| r.get(0))?;
+ sizes.insert(b.clone(), n);
+ }
+ }
for p in &mut photos {
if let Some(b) = &p.burst {
p.burst_count = sizes.get(b).copied().unwrap_or(1);
@@ -337,46 +382,14 @@ impl Library {
/// file's name, title, caption or a keyword, or the year or month it was taken ("2025",
/// "march"). Deleted and hidden photos are not searched. Newest first, at most `limit`.
pub fn search_photos(&self, query: &str, limit: usize) -> Result<Vec<Photo>> {
- let words: Vec<String> = query
- .split_whitespace()
- .map(|w| w.to_lowercase())
- .filter(|w| !w.is_empty())
- .take(8)
- .collect();
- if words.is_empty() {
+ let Some((conditions, patterns)) = search_terms(query) else {
return Ok(Vec::new());
- }
- // One condition per word, each its own parameter: what is typed is never part of the SQL.
- let one = "(LOWER(COALESCE(filename, '')) LIKE ?{n} ESCAPE '\\'
- OR LOWER(COALESCE(title, '')) LIKE ?{n} ESCAPE '\\'
- OR LOWER(COALESCE(caption, '')) LIKE ?{n} ESCAPE '\\'
- OR LOWER(COALESCE(keywords, '')) LIKE ?{n} ESCAPE '\\'
- OR strftime('%Y', taken_at, 'unixepoch', 'localtime') LIKE ?{n} ESCAPE '\\'
- OR (CASE strftime('%m', taken_at, 'unixepoch', 'localtime')
- WHEN '01' THEN 'january' WHEN '02' THEN 'february' WHEN '03' THEN 'march'
- WHEN '04' THEN 'april' WHEN '05' THEN 'may' WHEN '06' THEN 'june'
- WHEN '07' THEN 'july' WHEN '08' THEN 'august' WHEN '09' THEN 'september'
- WHEN '10' THEN 'october' WHEN '11' THEN 'november' ELSE 'december' END)
- LIKE ?{n} ESCAPE '\\')";
- let conditions: Vec<String> = (1..=words.len())
- .map(|n| one.replace("{n}", &n.to_string()))
- .collect();
+ };
let sql = format!(
- "SELECT {COLUMNS} FROM photos WHERE deleted = 0 AND hidden = 0 AND {ONE_PER_BURST} AND {}
+ "SELECT {COLUMNS} FROM photos WHERE deleted = 0 AND hidden = 0 AND {ONE_PER_BURST} AND {conditions}
ORDER BY taken_at DESC, id LIMIT {}",
- conditions.join(" AND "),
limit.min(50_000)
);
- let patterns: Vec<String> = words
- .iter()
- .map(|w| {
- let escaped = w
- .replace('\\', "\\\\")
- .replace('%', "\\%")
- .replace('_', "\\_");
- format!("%{escaped}%")
- })
- .collect();
let mut stmt = self.conn.prepare(&sql)?;
let rows = stmt.query_map(rusqlite::params_from_iter(patterns.iter()), row_to_photo)?;
self.with_bursts(rows.collect::<std::result::Result<_, _>>()?)
@@ -752,6 +765,201 @@ impl Library {
}
}
+/// Where the photos a grid shows come from: a view, an album, a search, or one burst.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub enum Source {
+ View(View),
+ Album(String),
+ Query(String),
+ Burst(String),
+}
+
+/// How a view the person can sort is sorted: by when taken or when added, newest or oldest
+/// first. Albums, searches, bursts, Rated and Recently Deleted keep their own order.
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct Order {
+ pub by: OrderBy,
+ pub oldest: bool,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub enum OrderBy {
+ Taken,
+ Added,
+}
+
+/// What a grid needs of every photo it shows, before any photo itself: enough to lay out every
+/// month, select, move and count — a few bytes a photo, where the photos are a kilobyte each.
+/// The photos themselves come a page at a time ([`Library::photo_page`]), in the same order.
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct PhotoIndex {
+ pub ids: Vec<String>,
+ /// What each is grouped by: when it was taken, or added when sorted by that.
+ pub keys: Vec<i64>,
+ /// Each one's kind and marks, packed: bits 0–1 the kind (0 image, 1 video, 2 Live), bit 2
+ /// a favorite, bits 3–5 its stars.
+ pub marks: Vec<u8>,
+ /// The earliest and latest it holds were taken, unix seconds.
+ pub first: Option<i64>,
+ pub last: Option<i64>,
+}
+
+/// One packed mark (see [`PhotoIndex::marks`]).
+fn mark(kind: &str, favorite: bool, rating: i64) -> u8 {
+ let k = match Kind::parse(kind) {
+ Kind::Image => 0,
+ Kind::Video => 1,
+ Kind::Live => 2,
+ };
+ k | (u8::from(favorite) << 2) | ((rating.clamp(0, 5) as u8) << 3)
+}
+
+/// A source's photos as SQL: what is selected from, which, in what order, with its parameters
+/// — one place for the index and the pages, so their orders never differ. `pre` qualifies the
+/// photos' columns where another table is joined (an album's items).
+struct Query {
+ from: &'static str,
+ pre: &'static str,
+ filter: String,
+ order: String,
+ key: &'static str,
+ params: Vec<String>,
+}
+
+impl Library {
+ fn source_query(source: &Source, order: Option<Order>) -> Query {
+ const TAKEN: &str = "taken_at";
+ const ADDED: &str = "COALESCE(added_at, taken_at)";
+ let plain = |filter: String, order: String, key, params| Query {
+ from: "photos",
+ pre: "",
+ filter,
+ order,
+ key,
+ params,
+ };
+ match source {
+ Source::View(view) => {
+ let (filter, own) = Self::view_query(*view);
+ let bursts = if *view == View::RecentlyDeleted {
+ "1"
+ } else {
+ ONE_PER_BURST
+ };
+ let sortable = !matches!(view, View::RecentlyDeleted | View::Rated);
+ let (order, key) = match order.filter(|_| sortable) {
+ Some(o) => {
+ let key = if o.by == OrderBy::Added { ADDED } else { TAKEN };
+ let dir = if o.oldest { "ASC" } else { "DESC" };
+ (format!("{key} {dir}, id"), key)
+ }
+ // Grouped by what it is sorted by: Recents by when added.
+ None => (
+ format!("{own}, id"),
+ if *view == View::Recents { ADDED } else { TAKEN },
+ ),
+ };
+ plain(format!("{filter} AND {bursts}"), order, key, Vec::new())
+ }
+ Source::Album(album) => Query {
+ from: "photo_album_items i JOIN photos p ON p.id = i.asset",
+ pre: "p.",
+ filter: "i.album = ?1 AND p.deleted = 0 AND p.hidden = 0".into(),
+ order: "i.position, p.taken_at DESC, p.id".into(),
+ key: "p.taken_at",
+ params: vec![album.clone()],
+ },
+ Source::Query(typed) => match search_terms(typed) {
+ Some((conditions, patterns)) => plain(
+ format!("deleted = 0 AND hidden = 0 AND {ONE_PER_BURST} AND {conditions}"),
+ "taken_at DESC, id".into(),
+ TAKEN,
+ patterns,
+ ),
+ None => plain("0".into(), "id".into(), TAKEN, Vec::new()),
+ },
+ Source::Burst(burst) => plain(
+ "burst = ?1 AND deleted = 0".into(),
+ "taken_at, id".into(),
+ TAKEN,
+ vec![burst.clone()],
+ ),
+ }
+ }
+
+ /// Every photo a source shows, as a grid lays them out (see [`PhotoIndex`]).
+ pub fn photo_index(&self, source: &Source, order: Option<Order>) -> Result<PhotoIndex> {
+ let q = Self::source_query(source, order);
+ let mut stmt = self.conn.prepare(&format!(
+ "SELECT {p}id, {key}, {p}kind, {p}favorite, {p}rating, {p}taken_at FROM {from}
+ WHERE {filter} ORDER BY {order}",
+ p = q.pre,
+ key = q.key,
+ from = q.from,
+ filter = q.filter,
+ order = q.order,
+ ))?;
+ let mut rows = stmt.query(rusqlite::params_from_iter(q.params.iter()))?;
+ let mut out = PhotoIndex::default();
+ while let Some(r) = rows.next()? {
+ out.ids.push(r.get(0)?);
+ out.keys.push(r.get(1)?);
+ out.marks.push(mark(
+ &r.get::<_, String>(2)?,
+ r.get::<_, i64>(3)? != 0,
+ r.get(4)?,
+ ));
+ let taken: i64 = r.get(5)?;
+ out.first = Some(out.first.map_or(taken, |f| f.min(taken)));
+ out.last = Some(out.last.map_or(taken, |l| l.max(taken)));
+ }
+ Ok(out)
+ }
+
+ /// `limit` photos of a source from `offset`, in the order its index has them.
+ pub fn photo_page(
+ &self,
+ source: &Source,
+ order: Option<Order>,
+ offset: usize,
+ limit: usize,
+ ) -> Result<Vec<Photo>> {
+ let q = Self::source_query(source, order);
+ let columns = COLUMNS
+ .split(", ")
+ .map(|c| format!("{}{}", q.pre, c.trim()))
+ .collect::<Vec<_>>()
+ .join(", ");
+ let mut stmt = self.conn.prepare(&format!(
+ "SELECT {columns} FROM {from} WHERE {filter} ORDER BY {order} LIMIT {limit} OFFSET {offset}",
+ from = q.from,
+ filter = q.filter,
+ order = q.order,
+ limit = limit.min(5_000),
+ ))?;
+ let rows = stmt.query_map(rusqlite::params_from_iter(q.params.iter()), row_to_photo)?;
+ self.with_bursts(rows.collect::<std::result::Result<_, _>>()?)
+ }
+
+ /// Photos by asset id, in the order asked; those gone are left out.
+ pub fn photos_by_ids(&self, ids: &[String]) -> Result<Vec<Photo>> {
+ let mut out = Vec::with_capacity(ids.len());
+ let mut stmt = self
+ .conn
+ .prepare_cached(&format!("SELECT {COLUMNS} FROM photos WHERE id = ?1"))?;
+ for id in ids {
+ if let Some(p) = stmt.query_row(params![id], row_to_photo).optional()? {
+ out.push(p);
+ }
+ }
+ self.with_bursts(out)
+ }
+}
+
/// A whole read of Photos that takes more than one pass.
///
/// A large library is more change feed than one pass reads, so a whole read goes on across
@@ -1057,6 +1265,149 @@ mod tests {
assert_eq!(ids(&lib, View::Library), ["c", "b"]);
}
+ /// The index and its pages are the whole list's read, cut up: the same photos in the same
+ /// order for every view, album, search and burst — sorted any way — whatever the page size,
+ /// ties on the same second broken by id as the window breaks them.
+ #[test]
+ fn the_index_and_its_pages_are_the_list_in_order() {
+ let mut lib = Library::in_memory().unwrap();
+ let mut all = Vec::new();
+ for i in 0..40i64 {
+ let mut p = photo(&format!("p{i:02}"), 1_000 + (i % 7) * 10);
+ p.added_at = Some(5_000 - i * 3);
+ p.favorite = i % 5 == 0;
+ p.rating = i % 6;
+ p.hidden = i % 11 == 3;
+ p.deleted = i % 13 == 4;
+ p.kind = if i % 9 == 0 { Kind::Video } else { Kind::Image };
+ p.subtype = if i % 8 == 1 { 3 } else { 0 };
+ if (20..24).contains(&i) {
+ p.burst = Some("B".into());
+ p.burst_pick = i == 22;
+ }
+ p.filename = Some(format!(
+ "{}{i}.jpg",
+ if i % 2 == 0 { "beach" } else { "city" }
+ ));
+ all.push(p);
+ }
+ lib.put_photos(&all).unwrap();
+ lib.put_album_items(&[
+ ("AL".into(), "p05".into(), 3),
+ ("AL".into(), "p01".into(), 1),
+ ("AL".into(), "p30".into(), 2),
+ ])
+ .unwrap();
+ let pages = |source: &Source, order: Option<Order>, size: usize| {
+ let mut out = Vec::new();
+ for at in (0..).step_by(size) {
+ let page = lib.photo_page(source, order, at, size).unwrap();
+ let n = page.len();
+ out.extend(page);
+ if n < size {
+ break;
+ }
+ }
+ out
+ };
+ let check = |source: Source, order: Option<Order>, want: Vec<Photo>| {
+ let index = lib.photo_index(&source, order).unwrap();
+ let ids: Vec<&str> = want.iter().map(|p| p.id.as_str()).collect();
+ assert_eq!(index.ids, ids, "{source:?} {order:?}");
+ for size in [1, 3, 7, 500] {
+ assert_eq!(
+ pages(&source, order, size),
+ want,
+ "{source:?} {order:?} by {size}"
+ );
+ }
+ for (i, p) in want.iter().enumerate() {
+ let m = index.marks[i];
+ assert_eq!(m & 3, if p.kind == Kind::Video { 1 } else { 0 });
+ assert_eq!(m & 4 != 0, p.favorite);
+ assert_eq!(i64::from(m >> 3), p.rating);
+ }
+ if !want.is_empty() {
+ assert_eq!(index.first, want.iter().map(|p| p.taken_at).min());
+ assert_eq!(index.last, want.iter().map(|p| p.taken_at).max());
+ }
+ };
+ for view in [
+ View::Library,
+ View::Favorites,
+ View::Videos,
+ View::Screenshots,
+ View::Recents,
+ View::Hidden,
+ View::Rated,
+ View::RecentlyDeleted,
+ ] {
+ check(Source::View(view), None, lib.photos(view).unwrap());
+ }
+ // Sorted as the window sorts: by the key, then by id; Rated and Recently Deleted keep
+ // their own order whatever is asked.
+ for by in [OrderBy::Taken, OrderBy::Added] {
+ for oldest in [false, true] {
+ let order = Some(Order { by, oldest });
+ let mut want = lib.photos(View::Library).unwrap();
+ let key = |p: &Photo| match by {
+ OrderBy::Taken => p.taken_at,
+ OrderBy::Added => p.added_at.unwrap_or(p.taken_at),
+ };
+ want.sort_by(|a, b| {
+ let k = if oldest {
+ key(a).cmp(&key(b))
+ } else {
+ key(b).cmp(&key(a))
+ };
+ k.then_with(|| a.id.cmp(&b.id))
+ });
+ check(Source::View(View::Library), order, want);
+ check(
+ Source::View(View::Rated),
+ order,
+ lib.photos(View::Rated).unwrap(),
+ );
+ let index = lib
+ .photo_index(&Source::View(View::Library), order)
+ .unwrap();
+ let keyed: Vec<i64> = lib
+ .photos_by_ids(&index.ids)
+ .unwrap()
+ .iter()
+ .map(key)
+ .collect();
+ assert_eq!(index.keys, keyed, "grouped by what it is sorted by");
+ }
+ }
+ check(
+ Source::Album("AL".into()),
+ None,
+ lib.album_photos("AL").unwrap(),
+ );
+ check(Source::Album("none".into()), None, Vec::new());
+ check(
+ Source::Query("beach".into()),
+ None,
+ lib.search_photos("beach", 1000).unwrap(),
+ );
+ check(Source::Query(" ".into()), None, Vec::new());
+ check(
+ Source::Burst("B".into()),
+ None,
+ lib.burst_photos("B").unwrap(),
+ );
+ // Asked for by id: in the order asked, the gone left out, burst sizes filled.
+ let got = lib
+ .photos_by_ids(&["p22".into(), "gone".into(), "p01".into()])
+ .unwrap();
+ assert_eq!(
+ got.iter().map(|p| p.id.as_str()).collect::<Vec<_>>(),
+ ["p22", "p01"]
+ );
+ assert_eq!(got[0].burst_count, 4);
+ }
+
/// Media types as Apple decides them (read from its smart albums on his library): a
/// screenshot is assetSubtypeV2 3 and a panorama 1 — not every PNG.
#[test]
@@ -1090,4 +1441,53 @@ mod tests {
["depth"]
);
}
+
+ /// The whole library over IPC against the index and a first page, on a copy of a real
+ /// library (never the real one): `QUINCE_DB_COPY=<dir holding a copy of library.db> cargo
+ /// test -p quince-core --release ipc_paging_on_a_copy -- --ignored --nocapture`.
+ #[test]
+ #[ignore = "needs a copy of a real library"]
+ fn ipc_paging_on_a_copy() {
+ let dir = std::path::PathBuf::from(std::env::var("QUINCE_DB_COPY").unwrap());
+ let lib = Library::open(&dir).unwrap();
+ let time = |f: &dyn Fn() -> usize| {
+ let mut runs: Vec<(std::time::Duration, usize)> = (0..5)
+ .map(|_| {
+ let t = std::time::Instant::now();
+ let n = f();
+ (t.elapsed(), n)
+ })
+ .collect();
+ runs.sort();
+ runs[2]
+ };
+ let source = Source::View(View::Library);
+ let whole = time(&|| {
+ serde_json::to_vec(&lib.photos(View::Library).unwrap())
+ .unwrap()
+ .len()
+ });
+ let index = time(&|| {
+ serde_json::to_vec(&lib.photo_index(&source, None).unwrap())
+ .unwrap()
+ .len()
+ });
+ let first = time(&|| {
+ serde_json::to_vec(&lib.photo_page(&source, None, 0, 240).unwrap())
+ .unwrap()
+ .len()
+ });
+ let ids = lib.photo_index(&source, None).unwrap().ids;
+ let mid = &ids[ids.len() / 2..(ids.len() / 2 + 240).min(ids.len())];
+ let deep = time(&|| {
+ serde_json::to_vec(&lib.photos_by_ids(mid).unwrap())
+ .unwrap()
+ .len()
+ });
+ println!("{} photos", ids.len());
+ println!("whole list: {:>10} bytes {:?}", whole.1, whole.0);
+ println!("index: {:>10} bytes {:?}", index.1, index.0);
+ println!("first page: {:>10} bytes {:?}", first.1, first.0);
+ println!("page by id (mid):{:>10} bytes {:?}", deep.1, deep.0);
+ }
}
diff --git a/crates/quince-core/src/reminders.rs b/crates/quince-core/src/reminders.rs
index 95dd8df..23a06c2 100644
--- a/crates/quince-core/src/reminders.rs
+++ b/crates/quince-core/src/reminders.rs
@@ -249,6 +249,7 @@ impl Reminder {
1 => jiff::Span::new().weeks(interval),
2 => jiff::Span::new().months(interval),
3 => jiff::Span::new().years(interval),
+ 4 => jiff::Span::new().hours(interval),
_ => return None,
};
// Stepped in the reminder's own zone, not in UTC. A day in UTC is always exactly
@@ -274,6 +275,119 @@ impl Reminder {
}
}
+impl Reminder {
+ /// Whether a tick at `at` is the last of the series: its repeat ends (`end_at`, End Repeat
+ /// On Date) before the next occurrence. Ticked then, it is completed, as on the iPhone,
+ /// rather than moved on to a date past its end.
+ #[must_use]
+ pub fn tick_ends_series(&self, end_at: Option<i64>, at: i64) -> bool {
+ self.tick_ends_series_on(end_at, &[], at)
+ }
+
+ /// [`Self::tick_ends_series`] for a rule that falls on chosen weekdays.
+ #[must_use]
+ pub fn tick_ends_series_on(&self, end_at: Option<i64>, days: &[i64], at: i64) -> bool {
+ let Some(end) = end_at else {
+ return false;
+ };
+ self.repeats()
+ && self
+ .next_occurrence_on(days, at)
+ .is_some_and(|next| next > end)
+ }
+
+ /// The next occurrence after `at` of a rule that falls on chosen weekdays (`days`, Apple's
+ /// numbering: 1 Sunday … 7 Saturday) — Weekdays, Weekends, or days picked in Custom. Weeks
+ /// count from Sunday, as the phone's `FirstDayOfTheWeek` 0 says, and every `interval`th
+ /// week is one it falls in. Any other rule steps as [`Self::next_occurrence_after`] does.
+ #[must_use]
+ pub fn next_occurrence_on(&self, days: &[i64], after: i64) -> Option<i64> {
+ if days.is_empty() || self.recur_frequency != Some(1) {
+ return self.next_occurrence_after(after);
+ }
+ let due = self.due_at?;
+ let interval = self.recur_interval.unwrap_or(1).clamp(1, 1_000);
+ let zone = self
+ .timezone
+ .as_deref()
+ .and_then(|name| jiff::tz::TimeZone::get(name).ok())
+ .unwrap_or_else(jiff::tz::TimeZone::system);
+ let start = jiff::Timestamp::from_second(due).ok()?.to_zoned(zone);
+ // Sunday of the week it was due in, as a day count.
+ let sunday = |d: jiff::civil::Date| {
+ let back = i64::from(d.weekday().to_sunday_zero_offset());
+ d.checked_sub(jiff::Span::new().days(back)).ok()
+ };
+ let first_week = sunday(start.date())?;
+ for step in 1..=(MAX_RECURRENCE_STEPS as i64 * 7) {
+ let candidate = start.checked_add(jiff::Span::new().days(step)).ok()?;
+ let weekday = i64::from(candidate.date().weekday().to_sunday_one_offset());
+ if !days.contains(&weekday) {
+ continue;
+ }
+ let weeks = first_week.until(sunday(candidate.date())?).ok()?.get_days() / 7;
+ if i64::from(weeks) % interval != 0 {
+ continue;
+ }
+ let at = candidate.timestamp().as_second();
+ if at > after {
+ return Some(at);
+ }
+ }
+ None
+ }
+}
+
+/// The weekdays a rule's `DaysOfTheWeek` holds — base64 of JSON as the phone writes it,
+/// `[{"dayOfTheWeek":2,"weekNumber":0},…]`, 1 Sunday … 7 Saturday — sorted. `None` when it
+/// does not read, or names a week of the month ("the first Monday"), which is not a weekday
+/// choice.
+#[must_use]
+pub fn days_of_week_from(base64_json: &str) -> Option<Vec<i64>> {
+ use base64::Engine;
+ let bytes = base64::engine::general_purpose::STANDARD
+ .decode(base64_json.trim())
+ .ok()?;
+ let entries: Vec<serde_json::Value> = serde_json::from_slice(&bytes).ok()?;
+ let mut days = Vec::with_capacity(entries.len());
+ for e in entries {
+ let day = e.get("dayOfTheWeek")?.as_i64()?;
+ if !(1..=7).contains(&day)
+ || e.get("weekNumber")
+ .and_then(serde_json::Value::as_i64)
+ .unwrap_or(0)
+ != 0
+ {
+ return None;
+ }
+ days.push(day);
+ }
+ days.sort_unstable();
+ days.dedup();
+ Some(days)
+}
+
+/// Weekdays as the phone writes them in a rule's `DaysOfTheWeek`: base64 of compact JSON,
+/// in day order, each `{"dayOfTheWeek":n,"weekNumber":0}` — the key order of the phone's
+/// own Weekdays rule.
+#[must_use]
+pub fn days_of_week_to(days: &[i64]) -> String {
+ use base64::Engine;
+ let mut days: Vec<i64> = days
+ .iter()
+ .copied()
+ .filter(|d| (1..=7).contains(d))
+ .collect();
+ days.sort_unstable();
+ days.dedup();
+ let json = days
+ .iter()
+ .map(|d| format!(r#"{{"dayOfTheWeek":{d},"weekNumber":0}}"#))
+ .collect::<Vec<_>>()
+ .join(",");
+ base64::engine::general_purpose::STANDARD.encode(format!("[{json}]"))
+}
+
/// How far `next_occurrence_after` will walk forward before giving up.
const MAX_RECURRENCE_STEPS: usize = 4_000;
@@ -483,7 +597,9 @@ impl Library {
JOIN reminder_lists l ON l.guid = r.list_guid
WHERE l.enabled = 1 AND r.due_at IS NOT NULL
AND r.due_at >= ?1 AND r.due_at < ?2
- ORDER BY r.due_at
+ -- Open ones first, so a busy year's finished history can never use up the cap and
+ -- leave reminders still to do off the Year view; each placed by its date anyway.
+ ORDER BY r.completed_at IS NOT NULL, r.due_at
LIMIT ?3",
)?;
let rows = stmt.query_map(params![from, to, MOST_AT_ONCE], |row| {
@@ -2158,8 +2274,10 @@ pub struct ReminderDetail {
pub tags: Vec<String>,
pub url: Option<String>,
pub early_alerts: Vec<EarlyAlert>,
- /// How many file or image attachments it has, which this app does not show yet.
+ /// How many file or image attachments it has, pictures included.
pub other_attachments: usize,
+ /// Its pictures' attachment ids (`Attachment/<UUID>`), in the order the phone lists them.
+ pub images: Vec<String>,
}
/// A tag across the whole account, and how many reminders still to do carry it.
@@ -2695,18 +2813,27 @@ impl Library {
tags.sort_by(|a, b| crate::fold::natural(a, b));
tags.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
let mut stmt = self.conn.prepare(
- "SELECT kind, url FROM reminder_attachments WHERE reminder_guid = ?1 ORDER BY guid",
+ "SELECT kind, url, guid FROM reminder_attachments WHERE reminder_guid = ?1 ORDER BY guid",
)?;
let attachments = stmt
.query_map(params![guid], |r| {
- Ok((r.get::<_, String>(0)?, r.get::<_, Option<String>>(1)?))
+ Ok((
+ r.get::<_, String>(0)?,
+ r.get::<_, Option<String>>(1)?,
+ r.get::<_, String>(2)?,
+ ))
})?
.collect::<rusqlite::Result<Vec<_>>>()?;
let url = attachments
.iter()
- .find(|(kind, url)| kind == "URL" && url.is_some())
- .and_then(|(_, url)| url.clone());
- let other_attachments = attachments.iter().filter(|(k, _)| k != "URL").count();
+ .find(|(kind, url, _)| kind == "URL" && url.is_some())
+ .and_then(|(_, url, _)| url.clone());
+ let other_attachments = attachments.iter().filter(|(k, _, _)| k != "URL").count();
+ let images = attachments
+ .iter()
+ .filter(|(k, _, _)| k == "Image")
+ .map(|(_, _, id)| id.clone())
+ .collect();
let mut stmt = self.conn.prepare(
"SELECT id, count, unit FROM reminder_early_alerts WHERE reminder_guid = ?1
ORDER BY unit, count, id",
@@ -2726,6 +2853,7 @@ impl Library {
url,
early_alerts,
other_attachments,
+ images,
})
}
@@ -3265,3 +3393,466 @@ mod detail_tests {
);
}
}
+
+// ---------------------------------------------------------------------------------------
+// The rest of a reminder's schedule: its repeat rule whole, where it rings, who it is about.
+// ---------------------------------------------------------------------------------------
+
+/// A record Apple keeps beside a reminder, stored whole as Apple sent it: a `RecurrenceRule`
+/// (with the reminder it governs) or a place `AlarmTrigger` (reached through the reminder's
+/// alarms). Kept verbatim so anything this app does not read yet is still there to read.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ReminderPart {
+ /// The record name, `RecurrenceRule/<id>` or `AlarmTrigger/<id>`.
+ pub name: String,
+ pub reminder_guid: Option<String>,
+ /// Apple's record type.
+ pub kind: String,
+ pub raw: String,
+}
+
+/// A repeat as the phone's Repeat and End Repeat rows show it.
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct RepeatRule {
+ /// Apple's `Frequency`: 0 daily, 1 weekly, 2 monthly, 3 yearly, 4 hourly.
+ pub frequency: i64,
+ pub interval: i64,
+ /// End Repeat On Date, as an instant in seconds.
+ pub end_at: Option<i64>,
+ /// Ends after this many times; 0 is never.
+ pub occurrence_count: i64,
+ /// The weekdays it falls on, 1 Sunday … 7 Saturday: Weekdays is 2–6, Weekends 1 and 7.
+ /// Empty when it falls on its due date's day.
+ #[serde(default)]
+ pub days_of_week: Vec<i64>,
+ /// Fields on Apple's rule this app does not read (chosen weekdays, days of the month…),
+ /// by name. A rule with any is shown as Apple's, and its days are kept as they are.
+ pub other: Vec<String>,
+}
+
+/// A place a reminder rings at: the phone's Location row.
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct PlaceAlarm {
+ /// The place as the phone names it ("Alex's Home").
+ pub title: Option<String>,
+ /// `arriving` or `leaving`, from Apple's `Proximity` (1 and 2); `None` when it says neither.
+ pub proximity: Option<String>,
+ /// Apple's trigger `Type`: `Location`, or another kind of place it knows.
+ pub kind: String,
+}
+
+/// The person a reminder comes up for when messaging them: the phone's When Messaging row.
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct MessagingPerson {
+ /// Their name, from this account's contacts, when one of the handles is on a card.
+ pub name: Option<String>,
+ /// Their email addresses and phone numbers, as Apple keeps them.
+ pub handles: Vec<String>,
+}
+
+/// What a reminder's row shows beside its date, as the phone's list does: Weekdays or
+/// Weekends by the repeat, the Urgent alarm, the place it rings at, the person it is about.
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ReminderMarks {
+ pub guid: String,
+ /// The weekdays its repeat falls on; empty for its due date's day.
+ pub days_of_week: Vec<i64>,
+ pub urgent: bool,
+ pub location: Option<PlaceAlarm>,
+ /// The person's name, or a handle where no card has one.
+ pub messaging: Option<String>,
+ /// Its link, for the chip the phone shows.
+ pub url: Option<String>,
+}
+
+/// What the phone's Details screen shows beyond tags, a link and early alerts.
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ReminderMore {
+ pub guid: String,
+ pub repeat: Option<RepeatRule>,
+ /// The named zone its time is kept in ("America/New_York").
+ pub time_zone: Option<String>,
+ /// Urgent: rings as an alarm, even in a Focus or with the sound off. `None` until known.
+ pub urgent: Option<bool>,
+ pub location: Option<PlaceAlarm>,
+ pub messaging: Option<MessagingPerson>,
+}
+
+impl Library {
+ /// Store the parts a pass brought back. A whole pass replaces what is stored; an
+ /// incremental one lays itself over it, less the records named in `gone`.
+ pub fn put_reminder_parts(
+ &mut self,
+ parts: &[ReminderPart],
+ gone: &[String],
+ whole: bool,
+ ) -> Result<()> {
+ let tx = self.conn.savepoint()?;
+ if whole {
+ tx.execute("DELETE FROM reminder_parts", [])?;
+ }
+ {
+ let mut forget = tx.prepare("DELETE FROM reminder_parts WHERE name = ?1")?;
+ for name in gone {
+ forget.execute(params![name])?;
+ }
+ let mut put = tx.prepare(
+ "INSERT INTO reminder_parts (name, reminder_guid, kind, raw) VALUES (?1, ?2, ?3, ?4)
+ ON CONFLICT(name) DO UPDATE SET reminder_guid = excluded.reminder_guid,
+ kind = excluded.kind, raw = excluded.raw",
+ )?;
+ for p in parts {
+ put.execute(params![p.name, p.reminder_guid, p.kind, p.raw])?;
+ }
+ }
+ tx.commit()?;
+ Ok(())
+ }
+
+ /// Everything kept beside one reminder: its repeat rules, and the place triggers its
+ /// alarms name.
+ pub fn reminder_parts(&self, guid: &str) -> Result<Vec<ReminderPart>> {
+ let mut stmt = self.conn.prepare(
+ "SELECT name, reminder_guid, kind, raw FROM reminder_parts WHERE reminder_guid = ?1
+ UNION ALL
+ SELECT p.name, p.reminder_guid, p.kind, p.raw FROM reminder_parts p
+ JOIN reminder_alarms a ON p.name = 'AlarmTrigger/' || a.trigger_id
+ WHERE a.reminder_guid = ?1
+ ORDER BY 1",
+ )?;
+ let rows = stmt.query_map(params![guid], |r| {
+ Ok(ReminderPart {
+ name: r.get(0)?,
+ reminder_guid: r.get(1)?,
+ kind: r.get(2)?,
+ raw: r.get(3)?,
+ })
+ })?;
+ Ok(rows.collect::<rusqlite::Result<_>>()?)
+ }
+
+ /// The weekdays a reminder's repeat falls on (Weekdays, Weekends, chosen days), from the
+ /// rule it names now; empty when it falls on its due date's day.
+ pub fn reminder_repeat_days(&self, guid: &str) -> Result<Vec<i64>> {
+ use rusqlite::OptionalExtension;
+ let raw: Option<Option<String>> = self
+ .conn
+ .query_row(
+ "SELECT json_extract(p.raw, '$.fields.DaysOfTheWeek.value')
+ FROM reminder_parts p JOIN reminders r ON r.guid = p.reminder_guid
+ WHERE p.reminder_guid = ?1 AND p.kind = 'RecurrenceRule'
+ AND json_valid(p.raw) AND json_valid(r.raw)
+ AND EXISTS (SELECT 1 FROM json_each(r.raw, '$.fields.RecurrenceRuleIDs.value') j
+ WHERE upper(p.name) = upper('RecurrenceRule/' || j.value))
+ LIMIT 1",
+ params![guid],
+ |row| row.get(0),
+ )
+ .optional()?;
+ Ok(raw
+ .flatten()
+ .and_then(|b| days_of_week_from(&b))
+ .unwrap_or_default())
+ }
+
+ /// When a reminder's repeat ends (End Repeat On Date), in seconds: from the rule the
+ /// reminder names now, as Apple sent it. `None` when it repeats for ever or not at all.
+ pub fn reminder_repeat_end(&self, guid: &str) -> Result<Option<i64>> {
+ Ok(self
+ .repeat_ends(Some(guid))?
+ .into_iter()
+ .next()
+ .map(|(_, end)| end))
+ }
+
+ /// Every open reminder whose repeat ends on a date, with that date in seconds.
+ pub fn reminder_repeat_ends(&self) -> Result<Vec<(String, i64)>> {
+ self.repeat_ends(None)
+ }
+
+ fn repeat_ends(&self, guid: Option<&str>) -> Result<Vec<(String, i64)>> {
+ let mut stmt = self.conn.prepare(
+ "SELECT p.reminder_guid, json_extract(p.raw, '$.fields.EndDate.value')
+ FROM reminder_parts p JOIN reminders r ON r.guid = p.reminder_guid
+ WHERE (?1 IS NULL OR p.reminder_guid = ?1) AND p.kind = 'RecurrenceRule'
+ AND r.completed_at IS NULL AND r.recur_frequency IS NOT NULL
+ AND json_valid(p.raw) AND json_valid(r.raw)
+ AND json_extract(p.raw, '$.fields.EndDate.value') IS NOT NULL
+ AND EXISTS (SELECT 1 FROM json_each(r.raw, '$.fields.RecurrenceRuleIDs.value') j
+ WHERE upper(p.name) = upper('RecurrenceRule/' || j.value))",
+ )?;
+ let rows = stmt.query_map(params![guid], |row| {
+ Ok((
+ row.get::<_, String>(0)?,
+ row.get::<_, i64>(1)?.div_euclid(1000),
+ ))
+ })?;
+ Ok(rows.collect::<rusqlite::Result<_>>()?)
+ }
+
+ /// The name on the card holding one of these email addresses or phone numbers. Numbers
+ /// are matched on their digits, the last ten where there are more, so "+91 98765 43210"
+ /// on a card finds "+919876543210".
+ pub fn contact_name_for(&self, handles: &[String]) -> Result<Option<String>> {
+ let digits = |s: &str| -> String { s.chars().filter(char::is_ascii_digit).collect() };
+ let tail = |d: &str| d[d.len().saturating_sub(10)..].to_string();
+ let mut stmt = self.conn.prepare(
+ "SELECT m.kind, m.value, trim(coalesce(c.first_name, '') || ' ' || coalesce(c.last_name, '')),
+ c.company
+ FROM contact_methods m JOIN contacts c ON c.guid = m.contact_guid
+ ORDER BY c.guid, m.position",
+ )?;
+ let rows = stmt
+ .query_map([], |r| {
+ Ok((
+ r.get::<_, String>(0)?,
+ r.get::<_, String>(1)?,
+ r.get::<_, String>(2)?,
+ r.get::<_, Option<String>>(3)?,
+ ))
+ })?
+ .collect::<rusqlite::Result<Vec<_>>>()?;
+ for handle in handles {
+ let email = handle.contains('@');
+ let wanted = if email {
+ handle.trim().to_lowercase()
+ } else {
+ tail(&digits(handle))
+ };
+ if wanted.is_empty() {
+ continue;
+ }
+ let found = rows.iter().find(|(_, value, _, _)| {
+ if email {
+ value.trim().to_lowercase() == wanted
+ } else {
+ let d = digits(value);
+ d.len() >= 6 && tail(&d) == wanted
+ }
+ });
+ if let Some((_, _, name, company)) = found {
+ let name = if name.is_empty() {
+ company.clone().unwrap_or_default()
+ } else {
+ name.clone()
+ };
+ if !name.trim().is_empty() {
+ return Ok(Some(name));
+ }
+ }
+ }
+ Ok(None)
+ }
+}
+
+#[cfg(test)]
+mod parts_tests {
+ use super::*;
+
+ fn part(name: &str, reminder: Option<&str>, kind: &str) -> ReminderPart {
+ ReminderPart {
+ name: name.into(),
+ reminder_guid: reminder.map(Into::into),
+ kind: kind.into(),
+ raw: format!("{{\"recordName\":\"{name}\"}}"),
+ }
+ }
+
+ #[test]
+ fn a_reminder_finds_its_rule_and_the_place_its_alarm_names() {
+ let mut lib = Library::in_memory().unwrap();
+ lib.put_reminder_parts(
+ &[
+ part("RecurrenceRule/R", Some("Reminder/1"), "RecurrenceRule"),
+ part("AlarmTrigger/T", None, "AlarmTrigger"),
+ part("RecurrenceRule/X", Some("Reminder/2"), "RecurrenceRule"),
+ ],
+ &[],
+ true,
+ )
+ .unwrap();
+ lib.put_alarms(
+ &[crate::alarms::Alarm {
+ id: "A".into(),
+ reminder_guid: "Reminder/1".into(),
+ trigger_id: "T".into(),
+ acknowledged_at: None,
+ }],
+ &[],
+ &[],
+ true,
+ )
+ .unwrap();
+ let names: Vec<String> = lib
+ .reminder_parts("Reminder/1")
+ .unwrap()
+ .into_iter()
+ .map(|p| p.name)
+ .collect();
+ assert_eq!(names, ["AlarmTrigger/T", "RecurrenceRule/R"]);
+ }
+
+ fn repeating(due: i64, frequency: i64) -> Reminder {
+ Reminder {
+ guid: "Reminder/1".into(),
+ list_guid: "List/a".into(),
+ title: "Take vitamins".into(),
+ due_at: Some(due),
+ recur_frequency: Some(frequency),
+ recur_interval: Some(1),
+ timezone: Some("UTC".into()),
+ ..Default::default()
+ }
+ }
+
+ const DUE: i64 = 1_792_681_200; // 22 Oct 2026, 15:00 UTC
+
+ #[test]
+ fn the_last_tick_before_the_end_completes_the_series() {
+ let r = repeating(DUE, 0);
+ // Ends the evening of the 22nd: tomorrow's is past it.
+ assert!(r.tick_ends_series(Some(DUE + 8 * 3600), DUE - 60));
+ // Ends on the 23rd at 23:59: tomorrow's 15:00 is still in it.
+ assert!(!r.tick_ends_series(Some(DUE + 86_400 + 9 * 3600), DUE - 60));
+ // No end: never.
+ assert!(!r.tick_ends_series(None, DUE - 60));
+ // A one-off has no series to end.
+ let mut once = r.clone();
+ once.recur_frequency = None;
+ assert!(!once.tick_ends_series(Some(DUE), DUE - 60));
+ }
+
+ #[test]
+ fn weekdays_step_over_the_weekend_and_weekends_over_the_week() {
+ // Thu 22 Oct 2026 15:00 UTC.
+ let mut r = repeating(DUE, 1);
+ let day = 86_400;
+ let weekdays = [2, 3, 4, 5, 6];
+ assert_eq!(
+ r.next_occurrence_on(&weekdays, DUE - 60),
+ Some(DUE + day),
+ "Thursday to Friday"
+ );
+ r.due_at = Some(DUE + day);
+ assert_eq!(
+ r.next_occurrence_on(&weekdays, DUE),
+ Some(DUE + 4 * day),
+ "Friday to Monday"
+ );
+ r.due_at = Some(DUE);
+ assert_eq!(
+ r.next_occurrence_on(&[1, 7], DUE - 60),
+ Some(DUE + 2 * day),
+ "Thursday to Saturday"
+ );
+ // Mon/Wed/Fri every other week: Friday this week, then Monday a fortnight on.
+ r.recur_interval = Some(2);
+ assert_eq!(r.next_occurrence_on(&[2, 4, 6], DUE - 60), Some(DUE + day));
+ r.due_at = Some(DUE + day);
+ assert_eq!(r.next_occurrence_on(&[2, 4, 6], DUE), Some(DUE + 11 * day));
+ // No days: a week on, as before.
+ r.recur_interval = Some(1);
+ r.due_at = Some(DUE);
+ assert_eq!(r.next_occurrence_on(&[], DUE - 60), Some(DUE + 7 * day));
+ // Weekdays ending Friday night: ticked Friday, it is done.
+ r.due_at = Some(DUE + day);
+ assert!(r.tick_ends_series_on(Some(DUE + day + 3600), &weekdays, DUE));
+ }
+
+ #[test]
+ fn hourly_steps_by_the_hour_and_ends_on_time() {
+ let r = repeating(DUE, 4);
+ assert_eq!(r.next_occurrence_after(DUE - 60), Some(DUE + 3600));
+ assert!(r.tick_ends_series(Some(DUE + 1800), DUE - 60));
+ assert!(!r.tick_ends_series(Some(DUE + 3600), DUE - 60));
+ }
+
+ #[test]
+ fn the_end_is_read_from_the_rule_the_reminder_names() {
+ let mut lib = Library::in_memory().unwrap();
+ lib.put_reminder_lists(&[ReminderList {
+ guid: "List/a".into(),
+ title: "A".into(),
+ enabled: true,
+ ..Default::default()
+ }])
+ .unwrap();
+ let mut r = repeating(DUE, 0);
+ r.raw = Some(
+ r#"{"fields":{"RecurrenceRuleIDs":{"type":"STRING_LIST","value":["abc-1"]}}}"#.into(),
+ );
+ lib.put_reminders(&[r]).unwrap();
+ let rule = |name: &str, end: i64| ReminderPart {
+ name: name.into(),
+ reminder_guid: Some("Reminder/1".into()),
+ kind: "RecurrenceRule".into(),
+ raw: format!(r#"{{"fields":{{"EndDate":{{"type":"TIMESTAMP","value":{end}}}}}}}"#),
+ };
+ // An old rule the reminder no longer names is not its end.
+ lib.put_reminder_parts(
+ &[
+ rule("RecurrenceRule/old", 1_000_000),
+ rule("RecurrenceRule/ABC-1", 1_792_900_000_000),
+ ],
+ &[],
+ true,
+ )
+ .unwrap();
+ assert_eq!(
+ lib.reminder_repeat_end("Reminder/1").unwrap(),
+ Some(1_792_900_000)
+ );
+ lib.put_reminder_parts(
+ &[part(
+ "RecurrenceRule/ABC-1",
+ Some("Reminder/1"),
+ "RecurrenceRule",
+ )],
+ &[],
+ true,
+ )
+ .unwrap();
+ assert_eq!(
+ lib.reminder_repeat_end("Reminder/1").unwrap(),
+ None,
+ "repeats for ever"
+ );
+ }
+
+ #[test]
+ fn an_incremental_pass_lays_over_and_forgets_what_is_gone() {
+ let mut lib = Library::in_memory().unwrap();
+ lib.put_reminder_parts(
+ &[part(
+ "RecurrenceRule/R",
+ Some("Reminder/1"),
+ "RecurrenceRule",
+ )],
+ &[],
+ true,
+ )
+ .unwrap();
+ lib.put_reminder_parts(
+ &[part(
+ "RecurrenceRule/S",
+ Some("Reminder/1"),
+ "RecurrenceRule",
+ )],
+ &["RecurrenceRule/R".into()],
+ false,
+ )
+ .unwrap();
+ let names: Vec<String> = lib
+ .reminder_parts("Reminder/1")
+ .unwrap()
+ .into_iter()
+ .map(|p| p.name)
+ .collect();
+ assert_eq!(names, ["RecurrenceRule/S"]);
+ }
+}
diff --git a/crates/quince-core/src/schema.rs b/crates/quince-core/src/schema.rs
index 7e0433f..5fc2a8b 100644
--- a/crates/quince-core/src/schema.rs
+++ b/crates/quince-core/src/schema.rs
@@ -814,4 +814,38 @@ pub const MIGRATIONS: &[&str] = &[
SELECT d.id, concat_ws(' ', c.first_name, c.middle_name, c.last_name), concat_ws(' ', c.company, (SELECT group_concat(m.value || CASE WHEN m.kind = 'phone' THEN ' ' || replace(replace(replace(replace(replace(replace(replace(m.value, ' ', ''), '-', ''), '(', ''), ')', ''), '+', ''), '.', ''), '/', '') || ' ' || substr(replace(replace(replace(replace(replace(replace(replace(m.value, ' ', ''), '-', ''), '(', ''), ')', ''), '+', ''), '.', ''), '/', ''), -10) ELSE '' END, ' ')
FROM contact_methods m WHERE m.contact_guid = c.guid)) FROM search_docs d JOIN contacts c ON d.kind = 'contact' AND d.key = c.guid;
"#,
+ // 46 — the rest of a contact's name and work, as Apple's card holds them: prefix, suffix,
+ // nickname, the phonetic spellings, job title and department. The book is read whole once
+ // so every card has them.
+ r#"
+ ALTER TABLE contacts ADD COLUMN prefix TEXT;
+ ALTER TABLE contacts ADD COLUMN suffix TEXT;
+ ALTER TABLE contacts ADD COLUMN nickname TEXT;
+ ALTER TABLE contacts ADD COLUMN phonetic_first_name TEXT;
+ ALTER TABLE contacts ADD COLUMN phonetic_last_name TEXT;
+ ALTER TABLE contacts ADD COLUMN phonetic_company TEXT;
+ ALTER TABLE contacts ADD COLUMN job_title TEXT;
+ ALTER TABLE contacts ADD COLUMN department TEXT;
+ UPDATE sync_state SET token = NULL WHERE service = 'contacts';
+ "#,
+ // 47 — the records Apple keeps beside a reminder that say how it repeats and where it
+ // rings (RecurrenceRule, Alarm, AlarmTrigger), each kept whole as Apple sent it, so the
+ // phone's whole schedule — its end date, a place, arriving or leaving — can be shown. The
+ // zone is walked again once so every library has them.
+ r#"
+ CREATE TABLE reminder_parts (
+ name TEXT PRIMARY KEY,
+ reminder_guid TEXT,
+ kind TEXT NOT NULL,
+ raw TEXT NOT NULL
+ ) STRICT;
+ CREATE INDEX reminder_parts_by_reminder ON reminder_parts (reminder_guid);
+ UPDATE sync_state SET token = NULL WHERE service = 'reminders';
+ "#,
+ // 48 — a reminder's alarms found by the reminder: each row's marks and details joined
+ // reminder_alarms on reminder_guid with no index, a whole-table scan per reminder, under
+ // the library lock every list open — ticks and edits queued behind it.
+ r#"
+ CREATE INDEX IF NOT EXISTS reminder_alarms_by_reminder ON reminder_alarms (reminder_guid);
+ "#,
];
diff --git a/crates/quince-icloud/Cargo.toml b/crates/quince-icloud/Cargo.toml
index 6dee4ad..ff137b1 100644
--- a/crates/quince-icloud/Cargo.toml
+++ b/crates/quince-icloud/Cargo.toml
@@ -16,7 +16,7 @@ plist = "1.10"
base64 = "0.22"
flate2 = "1"
uuid = { workspace = true }
-tokio = { workspace = true, features = ["fs", "io-util", "time"] }
+tokio = { workspace = true, features = ["fs", "io-util", "time", "net"] }
futures-util = { version = "0.3", default-features = false, features = ["std"] }
sha1 = "0.10"
# Locked notes (notes_locked.rs): PBKDF2-SHA256 → AES key unwrap (RFC 3394) → AES-GCM.
@@ -25,6 +25,10 @@ pbkdf2 = { version = "0.12", default-features = false, features = ["hmac"] }
aes = "0.8"
aes-kw = "0.2"
aes-gcm = { version = "0.10", default-features = false, features = ["aes", "alloc"] }
+# The live push channel (courier.rs): Apple's web push socket, its P-256 signed connect.
+tokio-tungstenite = { version = "0.28", default-features = false, features = ["connect", "rustls-tls-webpki-roots"] }
+p256 = { version = "0.13", default-features = false, features = ["ecdsa", "std"] }
+rand_core = { version = "0.6", features = ["getrandom"] }
[dev-dependencies]
tokio = { workspace = true }
diff --git a/crates/quince-icloud/src/calendar.rs b/crates/quince-icloud/src/calendar.rs
index 731c095..d707b9e 100644
--- a/crates/quince-icloud/src/calendar.rs
+++ b/crates/quince-icloud/src/calendar.rs
@@ -410,6 +410,104 @@ pub fn is_occurrence(guid: &str) -> bool {
}
/// How an event repeats, in icloud.com's words: `freq` is `daily`, `weekly`, `monthly` or
+/// Someone invited to an event, as Apple holds them: their name and address when Apple has
+/// them, their answer, and whether they are the person signed in or the one who invited.
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Guest {
+ pub name: Option<String>,
+ pub email: Option<String>,
+ /// `accepted`, `declined`, `tentative`, or `pending` for no answer yet — and for any
+ /// answer this app does not know, rather than a guess.
+ pub status: &'static str,
+ pub is_me: bool,
+ pub is_organizer: bool,
+}
+
+/// The guests of `event_guid` in an `eventdetail` body: the `Invitee` objects the event names
+/// in its `invitees`, or that name it (or its series) as their parent. The organizer first,
+/// then by name. Read only.
+#[must_use]
+pub fn guests_from(body: &Value, event_guid: &str) -> Vec<Guest> {
+ let named: Vec<&str> = body
+ .get("Event")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ .filter(|e| {
+ e.get("guid")
+ .and_then(Value::as_str)
+ .is_some_and(|g| g == event_guid || g == series_of(event_guid))
+ })
+ .flat_map(|e| {
+ e.get("invitees")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ })
+ .filter_map(Value::as_str)
+ .collect();
+ let text = |o: &Value, k: &str| {
+ o.get(k)
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(str::to_string)
+ };
+ let mut guests: Vec<Guest> = body
+ .get("Invitee")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ .filter(|i| {
+ belongs_to(i, event_guid)
+ || i.get("guid")
+ .and_then(Value::as_str)
+ .is_some_and(|g| named.contains(&g))
+ })
+ .map(|i| Guest {
+ name: text(i, "commonName"),
+ email: text(i, "email").map(|e| {
+ e.strip_prefix("mailto:")
+ .or_else(|| e.strip_prefix("MAILTO:"))
+ .unwrap_or(&e)
+ .to_string()
+ }),
+ status: match i
+ .get("inviteeStatus")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_ascii_uppercase()
+ .as_str()
+ {
+ "ACCEPTED" => "accepted",
+ "DECLINED" => "declined",
+ "TENTATIVE" => "tentative",
+ _ => "pending",
+ },
+ is_me: i.get("isMe").and_then(Value::as_bool).unwrap_or(false),
+ is_organizer: i
+ .get("isOrganizer")
+ .and_then(Value::as_bool)
+ .unwrap_or(false),
+ })
+ .collect();
+ guests.sort_by(|a, b| {
+ b.is_organizer.cmp(&a.is_organizer).then_with(|| {
+ let key = |g: &Guest| {
+ g.name
+ .clone()
+ .or_else(|| g.email.clone())
+ .unwrap_or_default()
+ .to_lowercase()
+ };
+ key(a).cmp(&key(b))
+ })
+ });
+ guests.dedup_by(|a, b| a.email.is_some() && a.email == b.email);
+ guests
+}
+
/// `yearly`; every `interval` of them; ending after `count` times, or never.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -858,6 +956,15 @@ impl<'a> CalendarClient<'a> {
}))
}
+ /// An event's guests as Apple holds them, the organizer first. Read only.
+ pub async fn guests(&self, event: &Event) -> Result<Vec<Guest>> {
+ let day = day_of(event.starts_at, event_zone(event).as_deref());
+ let Some(body) = self.event_detail_body(event, &day).await? else {
+ return Ok(Vec::new());
+ };
+ Ok(guests_from(&body, &event.guid))
+ }
+
/// An event's alerts as Apple holds them: minutes before its start, `0` at its time.
pub async fn alerts(&self, event: &Event) -> Result<Vec<i64>> {
let day = day_of(event.starts_at, event_zone(event).as_deref());
@@ -1354,6 +1461,63 @@ mod tests {
use super::*;
use serde_json::json;
+ /// Guests as an eventdetail answer holds them: named by the event, or naming it; the
+ /// organizer first; answers read whatever their case; anything unknown "pending".
+ #[test]
+ fn guests_are_read_from_the_invitees_an_event_names() {
+ let body = json!({
+ "Event": [{ "guid": "E1", "invitees": ["I1", "I2", "I3"] }],
+ "Invitee": [
+ { "guid": "I1", "commonName": "Zara", "email": "mailto:[email protected]", "inviteeStatus": "ACCEPTED", "isMe": false, "isOrganizer": false },
+ { "guid": "I2", "commonName": "Ana", "email": "[email protected]", "inviteeStatus": "needs-action", "isMe": true, "isOrganizer": false },
+ { "guid": "I3", "commonName": " ", "email": "[email protected]", "inviteeStatus": "TENTATIVE", "isOrganizer": true },
+ { "guid": "I9", "pGuid": "OTHER", "commonName": "Not here", "inviteeStatus": "ACCEPTED" },
+ { "guid": "I4", "pGuid": "E1", "commonName": "Ravi", "inviteeStatus": "DELEGATED" },
+ ]
+ });
+ let g = guests_from(&body, "E1");
+ let shown: Vec<_> = g
+ .iter()
+ .map(|g| {
+ (
+ g.name.as_deref(),
+ g.email.as_deref(),
+ g.status,
+ g.is_me,
+ g.is_organizer,
+ )
+ })
+ .collect();
+ assert_eq!(
+ shown,
+ vec![
+ (None, Some("[email protected]"), "tentative", false, true),
+ (Some("Ana"), Some("[email protected]"), "pending", true, false),
+ (Some("Ravi"), None, "pending", false, false),
+ (
+ Some("Zara"),
+ "accepted",
+ false,
+ false
+ ),
+ ]
+ );
+ }
+
+ /// An occurrence of a repeating event finds its series' guests; a body with none, or
+ /// shaped otherwise, gives none — never a panic.
+ #[test]
+ fn guests_of_an_occurrence_and_of_odd_bodies() {
+ let body = json!({ "Event": [{ "guid": "S1", "invitees": ["I1"] }], "Invitee": [{ "guid": "I1", "email": "[email protected]", "inviteeStatus": "DECLINED" }] });
+ assert_eq!(
+ guests_from(&body, "S1__20261102T073300Z")[0].status,
+ "declined"
+ );
+ assert!(guests_from(&json!({}), "E1").is_empty());
+ assert!(guests_from(&json!({ "Invitee": "nope", "Event": 3 }), "E1").is_empty());
+ }
+
fn meeting() -> Event {
Event {
guid: "EV".into(),
diff --git a/crates/quince-icloud/src/calendar_feeds.rs b/crates/quince-icloud/src/calendar_feeds.rs
index e2b4c20..3af788e 100644
--- a/crates/quince-icloud/src/calendar_feeds.rs
+++ b/crates/quince-icloud/src/calendar_feeds.rs
@@ -594,7 +594,12 @@ pub fn parse(text: &str, here: &TimeZone) -> Result<Feed> {
}
"X-APPLE-CALENDAR-COLOR" => {
let c = p.value.trim();
- if c.starts_with('#') && (c.len() == 7 || c.len() == 9) {
+ // Hex only: a feed is anyone's file, and slicing a colour with a
+ // multi-byte character in it ("#12345€") panicked mid-character.
+ if c.starts_with('#')
+ && (c.len() == 7 || c.len() == 9)
+ && c[1..].bytes().all(|b| b.is_ascii_hexdigit())
+ {
feed.colour = Some(c[..7].to_ascii_lowercase());
}
}
@@ -1000,6 +1005,21 @@ fn event_of(item: &Item, w: &When, calendar_guid: &str, key: i64) -> Option<Even
mod tests {
use super::*;
+ /// A colour that is not hex — non-ASCII included — is ignored, never a panic.
+ #[test]
+ fn a_feed_colour_that_is_not_hex_is_ignored() {
+ for bad in [
+ "#12345\u{20ac}",
+ "#zzzzzz",
+ "#12\u{e9}456",
+ "#1234567\u{20ac}",
+ ] {
+ let ics =
+ format!("BEGIN:VCALENDAR\r\nX-APPLE-CALENDAR-COLOR:{bad}\r\nEND:VCALENDAR\r\n");
+ let _ = parse(&ics, &jiff::tz::TimeZone::UTC);
+ }
+ }
+
fn kolkata() -> TimeZone {
TimeZone::get("Asia/Kolkata").unwrap()
}
diff --git a/crates/quince-icloud/src/ckdocument.rs b/crates/quince-icloud/src/ckdocument.rs
index f018313..a898f5d 100644
--- a/crates/quince-icloud/src/ckdocument.rs
+++ b/crates/quince-icloud/src/ckdocument.rs
@@ -1265,31 +1265,30 @@ fn with_runs(note: &[u8], runs: &[Vec<u8>]) -> Option<Vec<u8>> {
Some(out)
}
-/// The run Notes gives an attachment's one character, as a phone writes it (measured on a
-/// picture added on his iPhone): `1` length 1, `12` the attachment — `1` its id, `2` its
-/// type identifier — `13` when it was placed (Unix seconds), then `2` the paragraph's setting,
-/// which every run of a paragraph shares.
-fn attachment_run(id: &str, uti: &str, stamp: u64, paragraph: Option<&[u8]>) -> Vec<u8> {
+/// The paragraph setting Notes gives a paragraph holding an attachment: `3` 1 and a fresh
+/// paragraph uuid at `9`. Measured on every attachment his devices placed (2026-10-22, all
+/// notes): each sits on a paragraph of its own — after a newline or at the start, followed by
+/// a newline or the end — with this setting, most with `3` 1, the newline after it sharing it.
+fn attachment_paragraph(uuid: &[u8; 16]) -> Vec<u8> {
+ let mut p = varint_field(3, 1);
+ p.extend(length_delimited(9, uuid));
+ p
+}
+
+/// The run Notes gives an attachment's one character, as a phone writes it, fields in the
+/// phone's order: `1` length 1, `2` the paragraph's setting, `12` the attachment — `1` its id,
+/// `2` its type identifier — and `13` when it was placed (Unix seconds).
+fn attachment_run(id: &str, uti: &str, stamp: u64, paragraph: &[u8]) -> Vec<u8> {
let mut info = length_delimited(1, id.as_bytes());
info.extend(length_delimited(2, uti.as_bytes()));
let mut run = varint_field(1, 1);
+ run.extend(length_delimited(2, paragraph));
run.extend(length_delimited(ATTACHMENT_INFO, &info));
run.extend(varint_field(13, stamp));
- if let Some(p) = paragraph {
- run.extend(length_delimited(2, p));
- }
run
}
-/// A note with an attachment placed at UTF-16 offset `at`: one object-replacement character
-/// (U+FFFC) inserted there, the merge records edited for that one insertion as a device edits
-/// them, and the character given a run of its own naming the attachment.
-///
-/// Everything else is copied through: the text around it, every other run, the versions. The
-/// new run takes the setting of the paragraph it lands in — its style, its checklist item —
-/// from that paragraph's own runs, so a picture put in a checklist line stays in that line.
-/// `None`, and nothing to write, for an offset past the end or inside a surrogate pair, and for
-/// any document [`replace_text`] would refuse.
+/// A note with an attachment placed at UTF-16 offset `at`. See [`insert_attachment_placed`].
#[must_use]
pub fn insert_attachment(
original: &[u8],
@@ -1298,6 +1297,29 @@ pub fn insert_attachment(
uti: &str,
stamp: u64,
) -> Option<Vec<u8>> {
+ insert_attachment_placed(original, at, id, uti, stamp).map(|(d, _)| d)
+}
+
+/// A note with an attachment placed at UTF-16 offset `at`, as a phone places one: on a
+/// paragraph of its own. One object-replacement character (U+FFFC) goes in, with a newline
+/// before it when `at` is inside a line, and a newline after it unless it is the note's last
+/// character; at the very end of a line it goes on the line below. Its paragraph gets the
+/// setting a phone gives one ([`attachment_paragraph`]); the newline before it ends the
+/// paragraph it came from, in that paragraph's setting. The merge records are edited for the
+/// one insertion as a device edits them.
+///
+/// Everything else is copied through: the text around it, every other run, the versions.
+/// Answers the document and the offset of the attachment's character in it. `None`, and
+/// nothing to write, for an offset past the end or inside a surrogate pair, and for any
+/// document [`replace_text`] would refuse.
+#[must_use]
+pub fn insert_attachment_placed(
+ original: &[u8],
+ at: u64,
+ id: &str,
+ uti: &str,
+ stamp: u64,
+) -> Option<(Vec<u8>, u64)> {
let plain = inflate(original)?;
let current = field_at(&plain, TEXT_PATH)?;
// The same proof an edit needs: the document can be walked and put back byte for byte.
@@ -1306,7 +1328,7 @@ pub fn insert_attachment(
}
let old_text = std::str::from_utf8(current).ok()?;
let units: Vec<u16> = old_text.encode_utf16().collect();
- let place = usize::try_from(at).ok()?;
+ let mut place = usize::try_from(at).ok()?;
if place > units.len()
|| units
.get(place)
@@ -1316,55 +1338,94 @@ pub fn insert_attachment(
}
let note = field_at(&plain, &TEXT_PATH[..2])?;
// Runs that do not describe the text are not built on.
- if runs_in(note)?.iter().map(|r| run_length(r)).sum::<u64>() != units.len() as u64 {
+ let old_runs = runs_in(note)?;
+ if old_runs.iter().map(|r| run_length(r)).sum::<u64>() != units.len() as u64 {
return None;
}
- let mut new_units = units;
- new_units.insert(place, 0xFFFC);
+ let newline = u16::from(b'\n');
+ let inside_line = |p: usize| p > 0 && units[p - 1] != newline;
+ // At the end of a line that has more after it: on the next line instead, so the line's
+ // own newline stays its own.
+ if inside_line(place) && units.get(place) == Some(&newline) {
+ place += 1;
+ }
+ let before = inside_line(place);
+ let after = place < units.len();
+ let mut inserted: Vec<u16> = Vec::with_capacity(3);
+ if before {
+ inserted.push(newline);
+ }
+ inserted.push(0xFFFC);
+ if after {
+ inserted.push(newline);
+ }
+ let n = inserted.len() as u64;
+ let at = place as u64;
+ let mut new_units = units.clone();
+ new_units.splice(place..place, inserted.iter().copied());
let new_text = String::from_utf16(&new_units).ok()?;
- let rebuilt = rebuild_note_with(note, old_text, &new_text, &[(at, 0, 1)])?;
+ let rebuilt = rebuild_note_with(note, old_text, &new_text, &[(at, 0, n)])?;
let runs = runs_in(&rebuilt)?;
- // Which run speaks for the paragraph: the one over its newline, or — the last paragraph,
- // which has none — over its last character other than the new one.
- let newline = new_units[place + 1..]
- .iter()
- .position(|&u| u == u16::from(b'\n'))
- .map(|i| place + 1 + i);
- let speaker = newline
- .or_else(|| (new_units.len() > place + 1).then(|| new_units.len() - 1))
- .or_else(|| (place > 0 && new_units[place - 1] != u16::from(b'\n')).then(|| place - 1));
- let run_over = |unit: usize| {
- let mut end = 0usize;
- runs.iter().find(|r| {
- end += usize::try_from(run_length(r)).unwrap_or(usize::MAX);
- unit < end
- })
- };
- let paragraph = speaker.and_then(run_over).and_then(|r| bytes_field(r, 2));
-
- let mut out = Vec::with_capacity(runs.len() + 2);
+ // The runs the new characters get.
+ let mut uuid = [0u8; 16];
+ uuid.copy_from_slice(uuid::Uuid::new_v4().as_bytes());
+ let paragraph = attachment_paragraph(&uuid);
+ let mut placed_runs = Vec::with_capacity(3);
+ if before {
+ // The newline closing the line it was put in: that line's run, one long.
+ let mut end = 0u64;
+ let line = old_runs.iter().find(|r| {
+ end += run_length(r);
+ end >= at
+ })?;
+ let line = without_field(line, ATTACHMENT_INFO)?;
+ placed_runs.push(set_varint_field(
+ &set_varint_field(&line, 1, 1)?,
+ 13,
+ stamp,
+ )?);
+ }
+ placed_runs.push(attachment_run(id, uti, stamp, &paragraph));
+ if after {
+ let mut run = varint_field(1, 1);
+ run.extend(length_delimited(2, &paragraph));
+ placed_runs.push(run);
+ }
+
+ let mut out = Vec::with_capacity(runs.len() + 4);
let mut start = 0u64;
+ let mut done = false;
for run in &runs {
let end = start + run_length(run);
- if (start..end).contains(&at) {
+ if !done && (start..end).contains(&at) {
+ // The rebuild put every new character in this one run; they are given theirs.
+ if end < at + n {
+ return None;
+ }
if at > start {
out.push(set_varint_field(run, 1, at - start)?);
}
- out.push(attachment_run(id, uti, stamp, paragraph.as_deref()));
- if end > at + 1 {
- out.push(set_varint_field(run, 1, end - at - 1)?);
+ out.extend(placed_runs.iter().cloned());
+ if end > at + n {
+ out.push(set_varint_field(run, 1, end - at - n)?);
}
+ done = true;
} else {
out.push(run.clone());
}
start = end;
}
+ if !done {
+ return None;
+ }
let placed = with_runs(&rebuilt, &out)?;
- ensure_versions(&rewrite(&plain, &TEXT_PATH[..2], &placed)?)
+ let document = ensure_versions(&rewrite(&plain, &TEXT_PATH[..2], &placed)?)?;
+ Some((document, at + u64::from(before)))
}
-/// [`insert_attachment`] over the base64 a CloudKit field carries, gzipped on the way back.
+/// [`insert_attachment_placed`] over the base64 a CloudKit field carries, gzipped on the way
+/// back, with where the attachment's character landed.
#[must_use]
pub fn insert_attachment_in_base64(
original: &str,
@@ -1372,9 +1433,10 @@ pub fn insert_attachment_in_base64(
id: &str,
uti: &str,
stamp: u64,
-) -> Option<String> {
+) -> Option<(String, u64)> {
let raw = B64.decode(original.trim()).ok()?;
- Some(B64.encode(gzip(&insert_attachment(&raw, at, id, uti, stamp)?)))
+ let (document, offset) = insert_attachment_placed(&raw, at, id, uti, stamp)?;
+ Some((B64.encode(gzip(&document)), offset))
}
/// The text and its formatting together: the text replaced as [`replace_text`] replaces it,
@@ -2680,21 +2742,27 @@ mod rewrite_tests {
let (was, now) = (records(&before), records(&after));
let (was_ids, now_ids) = (was.live_ids(), now.live_ids());
assert_eq!(now.live_length(), 17);
+ // The list stays sorted by uuid, as Apple keeps it: the phone's number is its place.
+ let writers = now.writer_clocks();
+ assert!(writers.windows(2).all(|w| w[0].0 < w[1].0));
+ let phone = writers.iter().position(|w| w.0 == PHONE).unwrap() as u64 + 1;
+ let me = 3 - phone;
+ let theirs = |ids: &[(u64, u64)]| ids.iter().map(|&(_, c)| (phone, c)).collect::<Vec<_>>();
assert_eq!(
now_ids[..6],
- was_ids[..6],
+ theirs(&was_ids[..6])[..],
"\"first \" is still the phone's"
);
assert_eq!(
now_ids[12..],
- was_ids[6..],
+ theirs(&was_ids[6..])[..],
"\"draft\" is still the phone's"
);
assert!(
- now_ids[6..12].iter().all(|&(writer, _)| writer == 2),
+ now_ids[6..12].iter().all(|&(writer, _)| writer == me),
"the typed words are this app's"
);
- assert_eq!(now.writer_clocks()[0], (PHONE.to_vec(), vec![11, 1]));
+ assert_eq!(writers[phone as usize - 1], (PHONE.to_vec(), vec![11, 1]));
}
#[test]
diff --git a/crates/quince-icloud/src/contacts.rs b/crates/quince-icloud/src/contacts.rs
index e0357fe..fe5a24b 100644
--- a/crates/quince-icloud/src/contacts.rs
+++ b/crates/quince-icloud/src/contacts.rs
@@ -4,13 +4,19 @@
//! CloudKit, so `/co/startup` is the whole of it.
use crate::{Error, Result};
-use quince_core::contacts::{Contact, ContactMethod, PostalAddress, ADDRESS_FIELDS};
+use quince_core::contacts::{
+ Card, Contact, ContactDetails, ContactMethod, PostalAddress, ADDRESS_FIELDS, DETAIL_KEYS,
+};
use serde_json::Value;
/// Editing a card's postal addresses part by part.
#[path = "contacts_address.rs"]
pub mod address;
+/// Merging cards that are one person, on Apple's own cards.
+#[path = "contacts_merge.rs"]
+pub mod merge;
+
fn string(v: &Value, key: &str) -> Option<String> {
v.get(key)
.and_then(Value::as_str)
@@ -65,13 +71,28 @@ fn postal_from(entry: &Value) -> Option<PostalAddress> {
address.street = Some(text.trim().to_string()).filter(|s| !s.is_empty());
} else {
for key in ADDRESS_FIELDS {
- let value = field.get(key).and_then(Value::as_str);
+ let value = field
+ .get(address_wire(key))
+ .or_else(|| field.get(key))
+ .and_then(Value::as_str);
address.set_field(key, value);
}
}
(!address.is_empty()).then_some(address)
}
+/// The key Apple's card holds an address part under. Apple spells one part with a small `a`
+/// (`subadministrativeArea`, contacts2 bundle schema, 2026-10); the library names it as the
+/// Contacts framework does. Read under either, written as Apple spells it.
+#[must_use]
+pub(crate) fn address_wire(key: &str) -> &str {
+ if key == "subAdministrativeArea" {
+ "subadministrativeArea"
+ } else {
+ key
+ }
+}
+
/// Every card's addresses, part by part, as the library keeps them beside the card.
#[must_use]
pub fn parse_addresses(body: &Value) -> Vec<(String, Vec<PostalAddress>)> {
@@ -119,6 +140,28 @@ fn contact_from(v: &Value) -> Option<Contact> {
.unwrap_or_default(),
);
+ methods.extend(methods_from(v, "relatedNames", "related"));
+ methods.extend(methods_from(v, "dates", "date"));
+ // Instant messaging is labelled by its service, as icloud.com's editor labels it, and
+ // the name is inside: `{ "field": { "userName", "IMService" } }`.
+ methods.extend(
+ v.get("IMs")
+ .and_then(Value::as_array)
+ .map(|entries| {
+ entries
+ .iter()
+ .filter_map(|entry| {
+ Some(ContactMethod {
+ kind: "im".into(),
+ label: entry_label("im", entry),
+ value: entry_value("im", entry)?,
+ })
+ })
+ .collect::<Vec<_>>()
+ })
+ .unwrap_or_default(),
+ );
+
// A profile carries both an encoded handle and the readable one a person typed. The
// readable one is the point; `x-apple:%2B91%2090000` is not an answer to "who is this".
methods.extend(
@@ -131,7 +174,7 @@ fn contact_from(v: &Value) -> Option<Contact> {
Some(ContactMethod {
kind: "profile".into(),
label: string(entry, "label"),
- value: string(entry, "user").or_else(|| string(entry, "field"))?,
+ value: entry_value("profile", entry)?,
})
})
.collect::<Vec<_>>()
@@ -164,6 +207,140 @@ fn contact_from(v: &Value) -> Option<Contact> {
})
}
+/// The rest of a card's name and work, by Apple's keys.
+fn details_from(v: &Value) -> ContactDetails {
+ let mut d = ContactDetails::default();
+ for key in DETAIL_KEYS {
+ d.set(key, v.get(key).and_then(Value::as_str));
+ }
+ d
+}
+
+/// Every card's prefix, suffix, nickname, phonetic names, job title and department.
+#[must_use]
+pub fn parse_details(body: &Value) -> Vec<(String, ContactDetails)> {
+ body.get("contacts")
+ .and_then(Value::as_array)
+ .map(|cards| {
+ cards
+ .iter()
+ .filter_map(|card| Some((string(card, "contactId")?, details_from(card))))
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
+/// Each card whole, as one read found it.
+#[must_use]
+pub fn parse_cards(body: &Value) -> Vec<Card> {
+ body.get("contacts")
+ .and_then(Value::as_array)
+ .map(|arr| {
+ arr.iter()
+ .filter_map(|v| {
+ Some(Card {
+ contact: contact_from(v)?,
+ details: details_from(v),
+ })
+ })
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
+/// Where each kind of detail lives on Apple's card.
+const METHOD_KEYS: [(&str, &str); 7] = [
+ ("phones", "phone"),
+ ("emailAddresses", "email"),
+ ("urls", "url"),
+ ("relatedNames", "related"),
+ ("dates", "date"),
+ ("profiles", "profile"),
+ ("IMs", "im"),
+];
+
+/// What an entry of one kind holds, as icloud.com's editor reads it: most hold a string in
+/// `field`; a profile the handle a person typed (`user`, else its display name, else its
+/// link); instant messaging the name inside `field`.
+fn entry_value(kind: &str, entry: &Value) -> Option<String> {
+ match kind {
+ "profile" => string(entry, "user")
+ .or_else(|| string(entry, "displayname"))
+ .or_else(|| string(entry, "field")),
+ "im" => entry
+ .pointer("/field/userName")
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(ToString::to_string),
+ _ => string(entry, "field"),
+ }
+}
+
+/// An entry's label: for instant messaging, its service.
+fn entry_label(kind: &str, entry: &Value) -> Option<String> {
+ match kind {
+ "im" => entry
+ .pointer("/field/IMService")
+ .and_then(Value::as_str)
+ .map(ToString::to_string),
+ _ => entry
+ .get("label")
+ .and_then(Value::as_str)
+ .map(ToString::to_string),
+ }
+}
+
+/// Apple's entry for a detail — or, given the entry it replaces, that entry changed as
+/// icloud.com's editor changes one: the value and label set, everything else on it kept.
+fn build_entry(kind: &str, value: &str, label: Option<&str>, from: Option<&Value>) -> Value {
+ let mut e = from.and_then(Value::as_object).cloned().unwrap_or_default();
+ match kind {
+ "im" => {
+ let mut field = e
+ .get("field")
+ .and_then(Value::as_object)
+ .cloned()
+ .unwrap_or_default();
+ field.insert("userName".into(), Value::String(value.into()));
+ match label {
+ Some(l) => field.insert("IMService".into(), Value::String(l.into())),
+ None => field.remove("IMService"),
+ };
+ e.insert("field".into(), Value::Object(field));
+ }
+ "profile" => {
+ e.insert("user".into(), Value::String(value.into()));
+ set_label(&mut e, label);
+ }
+ _ => {
+ e.insert("field".into(), Value::String(value.into()));
+ set_label(&mut e, label);
+ }
+ }
+ Value::Object(e)
+}
+
+fn set_label(e: &mut serde_json::Map<String, Value>, label: Option<&str>) {
+ match label {
+ Some(l) => e.insert("label".into(), Value::String(l.into())),
+ None => e.remove("label"),
+ };
+}
+
+/// A crop as Apple's card holds it, from the `x,y,width,height` the library keeps.
+fn crop_value(crop: Option<&str>) -> Option<Value> {
+ let n: Vec<i64> = crop?
+ .split(',')
+ .map(|p| p.trim().parse().ok())
+ .collect::<Option<_>>()?;
+ let [x, y, width, height] = n[..] else {
+ return None;
+ };
+ (width > 0 && height > 0)
+ .then(|| serde_json::json!({ "x": x, "y": y, "width": width, "height": height }))
+}
+
#[must_use]
/// Apple's own address book service appends a vCard property to some picture URLs, leaving
/// `.../card/<32 hex>X-SHARED-PHOTO-DISPLAY-PREF:ALWAYS_ASK`. That URL answers 404. Four of
@@ -277,6 +454,7 @@ pub async fn fetch_book_with_tokens(
lists: parse_lists(&body),
me: me_card(&body),
addresses: parse_addresses(&body),
+ details: parse_details(&body),
},
Tokens {
sync: token("syncToken")?,
@@ -363,21 +541,25 @@ pub async fn fetch_with_tokens(
))
}
-/// Apple's card, built from ours.
-///
-/// Every field Apple sends back is sent again on a write, including the ones this app does
-/// not model — a card written with only the fields we understand would quietly drop
-/// everything else about the person.
-fn card_from(contact: &Contact, existing: Option<&Value>) -> Value {
- card_merged(contact, existing, None)
+/// [`card_written`] for a card without the rest of its name and work: those stay as Apple
+/// has them.
+fn card_merged(contact: &Contact, existing: Option<&Value>, base: Option<&Contact>) -> Value {
+ card_written(contact, None, existing, base, None)
}
/// The card to send: Apple's own as it stands now, with the fields this person changed —
/// and only those — set from the form. `base` is the card as the form opened it; a field the
/// form left as it found it keeps Apple's current value, so a name or number changed on the
/// phone while the form was open is not put back. Without a base every modelled field is
-/// written, as a new card needs.
-fn card_merged(contact: &Contact, existing: Option<&Value>, base: Option<&Contact>) -> Value {
+/// written, as a new card needs. `details` (with the form's `base_details`) are the rest of
+/// the name and work; `None` leaves Apple's.
+fn card_written(
+ contact: &Contact,
+ details: Option<&ContactDetails>,
+ existing: Option<&Value>,
+ base: Option<&Contact>,
+ base_details: Option<&ContactDetails>,
+) -> Value {
// Apple's card is the starting point, and Apple is not obliged to send an object; a
// write that panicked on network input would take the whole window down with it.
let mut card = existing
@@ -398,6 +580,9 @@ fn card_merged(contact: &Contact, existing: Option<&Value>, base: Option<&Contac
&contact.first_name,
(|c: &Contact| &c.first_name) as fn(&Contact) -> &Option<String>,
),
+ ("middleName", &contact.middle_name, |c: &Contact| {
+ &c.middle_name
+ }),
("lastName", &contact.last_name, |c: &Contact| &c.last_name),
("companyName", &contact.company, |c: &Contact| &c.company),
("birthday", &contact.birthday, |c: &Contact| &c.birthday),
@@ -406,6 +591,11 @@ fn card_merged(contact: &Contact, existing: Option<&Value>, base: Option<&Contac
if existing.is_some() && unchanged(pick) {
continue;
}
+ // A middle name is written only when one is given or one is being taken away: the
+ // forms before this one never held it, and a card made without one needs no key.
+ if key == "middleName" && value.is_none() && base.is_none_or(|b| b.middle_name.is_none()) {
+ continue;
+ }
match value {
Some(text) if !text.trim().is_empty() => {
object.insert(key.into(), Value::String(text.trim().to_string()));
@@ -418,65 +608,91 @@ fn card_merged(contact: &Contact, existing: Option<&Value>, base: Option<&Contac
}
}
- let of_kind = |kind: &str| -> Value {
- Value::Array(
- contact
- .methods
+ // The rest of the name and work: written when given, and then only what changed — on a
+ // new card, only what holds something.
+ if let Some(details) = details {
+ for key in DETAIL_KEYS {
+ let mine = details.get(key).cloned().flatten();
+ let write = if existing.is_none() {
+ mine.is_some()
+ } else {
+ base_details.is_none_or(|b| b.get(key).cloned().flatten() != mine)
+ };
+ if write {
+ object.insert(key.into(), Value::String(mine.unwrap_or_default()));
+ }
+ }
+ }
+
+ for (key, kind) in METHOD_KEYS {
+ let of = |c: &Contact| -> Vec<(String, Option<String>)> {
+ c.methods
.iter()
.filter(|m| m.kind == kind && !m.value.trim().is_empty())
- .map(|m| {
- let mut entry = serde_json::Map::new();
- entry.insert("field".into(), Value::String(m.value.trim().to_string()));
- if let Some(label) = &m.label {
- entry.insert("label".into(), Value::String(label.clone()));
- }
- Value::Object(entry)
- })
- .collect(),
- )
- };
- let kind_unchanged = |kind: &str| {
- base.is_some_and(|b| {
- let of = |c: &Contact| {
- c.methods
- .iter()
- .filter(|m| m.kind == kind)
- .cloned()
- .collect::<Vec<_>>()
- };
- of(b) == of(contact)
- })
- };
- for (key, kind) in [
- ("phones", "phone"),
- ("emailAddresses", "email"),
- ("urls", "url"),
- ] {
- if existing.is_some() && kind_unchanged(kind) {
+ .map(|m| (m.value.trim().to_string(), m.label.clone()))
+ .collect()
+ };
+ let mine = of(contact);
+ if existing.is_some() && base.is_some_and(|b| of(b) == mine) {
+ continue;
+ }
+ // The kinds this app read but never wrote are written only by a form that knows
+ // them: one from before, with no base, leaves them as Apple has them.
+ if base.is_none() && existing.is_some() && !matches!(kind, "phone" | "email" | "url") {
continue;
}
+ if existing.is_none() && mine.is_empty() && !matches!(kind, "phone" | "email" | "url") {
+ continue;
+ }
+ let theirs = existing
+ .and_then(|card| card.get(key))
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default();
// Edited from a base over Apple's current card: the edit laid over Apple's list, not
// the form's list written whole — a number added on the phone while the form was open
// here stays, as a name changed there does.
- let merged = match (base, existing) {
- (Some(base), Some(card)) => {
- let of = |c: &Contact| -> Vec<(String, Option<String>)> {
- c.methods
- .iter()
- .filter(|m| m.kind == kind && !m.value.trim().is_empty())
- .map(|m| (m.value.trim().to_string(), m.label.clone()))
- .collect()
- };
- let theirs = card
- .get(key)
- .and_then(Value::as_array)
+ let value = match (base, existing) {
+ (Some(base), Some(_)) => merge_methods(kind, &theirs, &of(base), &mine),
+ _ => Value::Array(
+ mine.iter()
+ .map(|(v, l)| build_entry(kind, v, l.as_deref(), None))
+ .collect(),
+ ),
+ };
+ object.insert(key.into(), value);
+ }
+
+ // The picture: a new one goes as icloud.com sends it — the image itself as a `data:` URL,
+ // with the square chosen — a new square for the same picture keeps the rest of Apple's
+ // entry, and a picture taken away is `null`.
+ let photo_of = |c: &Contact| (c.photo_url.clone(), c.photo_crop.clone());
+ let photo_changed = match base {
+ Some(b) => photo_of(b) != photo_of(contact),
+ None => existing.is_none() && contact.photo_url.is_some(),
+ };
+ if photo_changed {
+ let value = match &contact.photo_url {
+ None => Value::Null,
+ Some(url) => {
+ let same_picture = base.is_some_and(|b| b.photo_url.as_deref() == Some(url));
+ let mut photo = existing
+ .filter(|_| same_picture)
+ .and_then(|e| e.get("photo"))
+ .and_then(Value::as_object)
.cloned()
.unwrap_or_default();
- Some(merge_methods(&theirs, &of(base), &of(contact)))
+ if !same_picture {
+ photo.insert("url".into(), Value::String(url.clone()));
+ }
+ match crop_value(contact.photo_crop.as_deref()) {
+ Some(crop) => photo.insert("crop".into(), crop),
+ None => photo.remove("crop"),
+ };
+ Value::Object(photo)
}
- _ => None,
};
- object.insert(key.into(), merged.unwrap_or_else(|| of_kind(kind)));
+ object.insert("photo".into(), value);
}
// Laid over Apple's current card, the write is against that card's version; otherwise
@@ -494,26 +710,19 @@ fn card_merged(contact: &Contact, existing: Option<&Value>, base: Option<&Contac
card
}
-/// One kind of a card's numbers or addresses, as Apple holds it now (`theirs`), with the change
-/// the form made (`base` to `mine`) laid over it: what the form took out goes, what it put in
-/// is added — an edited entry in the old one's place — and everything else Apple has stays as
-/// Apple has it, entries made on another device included.
+/// One kind of a card's details, as Apple holds it now (`theirs`), with the change the form
+/// made (`base` to `mine`) laid over it: what the form took out goes, what it put in is added —
+/// an edited entry in the old one's place, keeping what else Apple kept on it — and everything
+/// else Apple has stays as Apple has it, entries made on another device included.
fn merge_methods(
+ kind: &str,
theirs: &[Value],
base: &[(String, Option<String>)],
mine: &[(String, Option<String>)],
) -> Value {
let matches = |entry: &Value, (value, label): &(String, Option<String>)| {
- entry.get("field").and_then(Value::as_str).map(str::trim) == Some(value.as_str())
- && entry.get("label").and_then(Value::as_str) == label.as_deref()
- };
- let entry = |(value, label): &(String, Option<String>)| {
- let mut e = serde_json::Map::new();
- e.insert("field".into(), Value::String(value.clone()));
- if let Some(label) = label {
- e.insert("label".into(), Value::String(label.clone()));
- }
- Value::Object(e)
+ entry_value(kind, entry).as_deref() == Some(value.as_str())
+ && entry_label(kind, entry).as_deref() == label.as_deref()
};
let removed: Vec<&(String, Option<String>)> =
base.iter().filter(|b| !mine.contains(b)).collect();
@@ -526,14 +735,14 @@ fn merge_methods(
for t in theirs {
if removed.iter().any(|r| matches(t, r)) {
// Edited rather than taken out: the new entry where the old one was.
- if let Some(a) = added.next() {
- out.push(entry(a));
+ if let Some((v, l)) = added.next() {
+ out.push(build_entry(kind, v, l.as_deref(), Some(t)));
}
} else {
out.push(t.clone());
}
}
- out.extend(added.map(entry));
+ out.extend(added.map(|(v, l)| build_entry(kind, v, l.as_deref(), None)));
Value::Array(out)
}
@@ -657,6 +866,18 @@ async fn write_new(
tokens: &Tokens,
guid: &str,
contact: &Contact,
+) -> Result<()> {
+ write_new_card(http, root, params, tokens, guid, contact, None).await
+}
+
+async fn write_new_card(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+ tokens: &Tokens,
+ guid: &str,
+ contact: &Contact,
+ details: Option<&ContactDetails>,
) -> Result<()> {
let mut fresh = contact.clone();
fresh.guid = guid.to_string();
@@ -668,7 +889,73 @@ async fn write_new(
params,
tokens,
reqwest::Method::POST,
- card_from(&fresh, None),
+ card_written(&fresh, details, None, None, None),
+ )
+ .await?;
+ Ok(())
+}
+
+/// [`create_named`] for a whole card: the rest of its name and work, and a picture, go too.
+pub async fn create_card_named(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+ tokens: &Tokens,
+ guid: &str,
+ card: &Card,
+) -> Result<()> {
+ if blank_card(&card.contact) && card.details.is_empty() {
+ return Err(Error::Refused(
+ "Add a name, a phone number or an email address first.".into(),
+ ));
+ }
+ if self::card(http, root, params.clone(), guid)
+ .await?
+ .is_some()
+ {
+ return Ok(());
+ }
+ write_new_card(
+ http,
+ root,
+ params,
+ tokens,
+ guid,
+ &card.contact,
+ Some(&card.details),
+ )
+ .await
+}
+
+/// [`update_from`] for a whole card: only what changed from `base`, the rest of the name and
+/// work and the picture included, over Apple's current card.
+pub async fn update_card(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+ tokens: &Tokens,
+ card: &Card,
+ existing: Option<&Value>,
+ base: Option<&Card>,
+) -> Result<()> {
+ if existing.is_none() {
+ return Err(Error::Refused(
+ "This contact was deleted on another device, so it wasn't saved.".into(),
+ ));
+ }
+ write(
+ http,
+ root,
+ params,
+ tokens,
+ reqwest::Method::PUT,
+ card_written(
+ &card.contact,
+ Some(&card.details),
+ existing,
+ base.map(|b| &b.contact),
+ base.map(|b| &b.details),
+ ),
)
.await?;
Ok(())
@@ -791,6 +1078,8 @@ pub struct AddressBook {
pub me: Option<String>,
/// Each card's postal addresses, part by part.
pub addresses: Vec<(String, Vec<PostalAddress>)>,
+ /// The rest of each card's name and work.
+ pub details: Vec<(String, ContactDetails)>,
}
/// Where the my-card id is kept between passes.
@@ -1429,6 +1718,7 @@ pub async fn fetch(
lists: parse_lists(&body),
me: me_card(&body),
addresses: parse_addresses(&body),
+ details: parse_details(&body),
})
}
@@ -1536,6 +1826,7 @@ pub fn apply(library: &mut quince_core::Library, book: AddressBook) -> Result<us
fn apply_whole(library: &mut quince_core::Library, book: AddressBook) -> Result<usize> {
library.put_contacts(&book.contacts)?;
library.put_addresses(&book.addresses, true)?;
+ library.put_contact_details(&book.details, true)?;
library.set_state(
LISTS_KEY,
&serde_json::to_string(&book.lists).unwrap_or_else(|_| "[]".into()),
@@ -2495,7 +2786,7 @@ mod odd_card_tests {
serde_json::json!("text"),
serde_json::json!(7),
] {
- let card = card_from(&contact, Some(&odd));
+ let card = card_merged(&contact, Some(&odd), None);
assert_eq!(card["firstName"], "Ada", "{odd} still produces the card");
}
}
@@ -2544,6 +2835,7 @@ mod atomic_apply_tests {
lists: vec![],
me: None,
addresses: vec![],
+ details: vec![],
},
);
assert!(failed.is_err());
@@ -2556,3 +2848,206 @@ mod atomic_apply_tests {
assert_eq!(guids, vec!["A".to_string()], "the old book, whole");
}
}
+
+#[cfg(test)]
+mod field_tests {
+ use super::*;
+ use serde_json::json;
+
+ fn apple() -> Value {
+ json!({
+ "contactId": "C1", "etag": "e1", "prefix": "Dr.", "firstName": "Asha",
+ "middleName": "K", "lastName": "Rao", "suffix": "Jr.", "nickName": "Ash",
+ "phoneticFirstName": "AA-sha", "phoneticLastName": "Rao",
+ "phoneticCompanyName": "nor-th-field", "companyName": "Northfield",
+ "jobTitle": "Architect", "department": "Design",
+ "birthday": "1604-03-17",
+ "phones": [{ "label": "MOBILE", "field": "+91 1" }, { "label": "Grandma's", "field": "+91 2" }],
+ "emailAddresses": [{ "label": "_$!<Work>!$_", "field": "[email protected]" }],
+ "urls": [{ "label": "HOMEPAGE", "field": "asha.in" }],
+ "dates": [{ "label": "ANNIVERSARY", "field": "2015-02-14" }, { "field": "1604-08-01", "label": "first day" }],
+ "relatedNames": [{ "label": "MOTHER", "field": "Amma" }],
+ "profiles": [{ "label": "TWITTER", "user": "asha", "field": "https://twitter.com/asha", "userId": "42" }],
+ "IMs": [{ "label": "HOME", "field": { "userName": "asha.k", "IMService": "SKYPE" } }],
+ "photo": { "url": "https://p/C1", "signature": "s1", "crop": { "x": 1, "y": 2, "width": 30, "height": 30 } },
+ "streetAddresses": [{ "label": "HOME", "field": { "city": "Pune" } }],
+ })
+ }
+
+ fn read() -> Card {
+ parse_cards(&json!({ "contacts": [apple()] })).remove(0)
+ }
+
+ #[test]
+ fn every_field_apple_keeps_is_read() {
+ let c = read();
+ let d = &c.details;
+ assert_eq!(d.prefix.as_deref(), Some("Dr."));
+ assert_eq!(d.suffix.as_deref(), Some("Jr."));
+ assert_eq!(d.nickname.as_deref(), Some("Ash"));
+ assert_eq!(d.phonetic_first_name.as_deref(), Some("AA-sha"));
+ assert_eq!(d.phonetic_company.as_deref(), Some("nor-th-field"));
+ assert_eq!(d.job_title.as_deref(), Some("Architect"));
+ assert_eq!(d.department.as_deref(), Some("Design"));
+ assert_eq!(c.contact.middle_name.as_deref(), Some("K"));
+ assert_eq!(c.contact.birthday.as_deref(), Some("1604-03-17"));
+ let of = |kind: &str| -> Vec<(Option<String>, String)> {
+ c.contact
+ .methods
+ .iter()
+ .filter(|m| m.kind == kind)
+ .map(|m| (m.label.clone(), m.value.clone()))
+ .collect()
+ };
+ assert_eq!(of("date").len(), 2);
+ assert_eq!(of("related"), [(Some("MOTHER".into()), "Amma".into())]);
+ assert_eq!(of("im"), [(Some("SKYPE".into()), "asha.k".into())]);
+ assert_eq!(of("profile"), [(Some("TWITTER".into()), "asha".into())]);
+ assert_eq!(
+ of("phone")[1].0.as_deref(),
+ Some("Grandma's"),
+ "a custom label as typed"
+ );
+ }
+
+ /// Opened and saved with nothing changed, the card goes back exactly as Apple sent it.
+ #[test]
+ fn a_card_saved_unchanged_goes_back_byte_for_byte() {
+ let c = read();
+ let written = card_written(
+ &c.contact,
+ Some(&c.details),
+ Some(&apple()),
+ Some(&c.contact),
+ Some(&c.details),
+ );
+ let mut want = apple();
+ want["isCompany"] = json!(false);
+ assert_eq!(written, want);
+ }
+
+ #[test]
+ fn each_new_field_is_written_as_apple_keeps_it() {
+ let base = read();
+ let mut c = base.clone();
+ c.details.nickname = None;
+ c.details.job_title = Some("Principal Architect".into());
+ c.contact.middle_name = None;
+ // An instant message edited: its outer label stays, as icloud.com keeps it.
+ let im = c
+ .contact
+ .methods
+ .iter_mut()
+ .find(|m| m.kind == "im")
+ .unwrap();
+ im.value = "asha.rao".into();
+ let profile = c
+ .contact
+ .methods
+ .iter_mut()
+ .find(|m| m.kind == "profile")
+ .unwrap();
+ profile.value = "asharao".into();
+ c.contact.methods.push(ContactMethod {
+ kind: "related".into(),
+ label: Some("SPOUSE".into()),
+ value: "Ravi".into(),
+ });
+ c.contact.methods.push(ContactMethod {
+ kind: "date".into(),
+ label: Some("ANNIVERSARY".into()),
+ value: "1604-11-02".into(),
+ });
+ let w = card_written(
+ &c.contact,
+ Some(&c.details),
+ Some(&apple()),
+ Some(&base.contact),
+ Some(&base.details),
+ );
+ assert_eq!(w["nickName"], "", "a cleared field is sent empty");
+ assert_eq!(w["jobTitle"], "Principal Architect");
+ assert_eq!(w["prefix"], "Dr.", "untouched");
+ assert_eq!(w["middleName"], "");
+ assert_eq!(
+ w["IMs"][0],
+ json!({ "label": "HOME", "field": { "userName": "asha.rao", "IMService": "SKYPE" } })
+ );
+ assert_eq!(w["profiles"][0]["user"], "asharao");
+ assert_eq!(w["profiles"][0]["label"], "TWITTER");
+ assert_eq!(
+ w["relatedNames"][1],
+ json!({ "label": "SPOUSE", "field": "Ravi" })
+ );
+ assert_eq!(
+ w["dates"][2],
+ json!({ "label": "ANNIVERSARY", "field": "1604-11-02" })
+ );
+ assert_eq!(
+ w["emailAddresses"][0]["label"], "_$!<Work>!$_",
+ "Apple's own spelling kept"
+ );
+ }
+
+ #[test]
+ fn a_new_card_carries_only_what_holds_something() {
+ let mut c = read();
+ c.contact.guid = "NEW".into();
+ c.contact.photo_url = None;
+ c.details.department = None;
+ let w = card_written(&c.contact, Some(&c.details), None, None, None);
+ assert_eq!(w["nickName"], "Ash");
+ assert!(w.get("department").is_none());
+ assert!(w.get("photo").is_none());
+ assert_eq!(w["IMs"][0]["field"]["IMService"], "SKYPE");
+ }
+
+ #[test]
+ fn a_picture_is_sent_whole_cropped_again_or_taken_away() {
+ let base = read();
+ let mut c = base.clone();
+ c.contact.photo_url = Some("data:image/jpeg;base64,AAAA".into());
+ c.contact.photo_crop = Some("0,10,200,200".into());
+ let w = card_written(&c.contact, None, Some(&apple()), Some(&base.contact), None);
+ assert_eq!(
+ w["photo"],
+ json!({ "url": "data:image/jpeg;base64,AAAA", "crop": { "x": 0, "y": 10, "width": 200, "height": 200 } })
+ );
+
+ let mut c = base.clone();
+ c.contact.photo_crop = Some("5,5,20,20".into());
+ let w = card_written(&c.contact, None, Some(&apple()), Some(&base.contact), None);
+ assert_eq!(w["photo"]["url"], "https://p/C1", "the same picture");
+ assert_eq!(w["photo"]["signature"], "s1");
+ assert_eq!(w["photo"]["crop"]["width"], 20);
+
+ let mut c = base.clone();
+ c.contact.photo_url = None;
+ let w = card_written(&c.contact, None, Some(&apple()), Some(&base.contact), None);
+ assert_eq!(w["photo"], Value::Null);
+
+ let mut c = base;
+ c.contact.guid = "NEW".into();
+ c.contact.photo_url = Some("data:image/jpeg;base64,BBBB".into());
+ c.contact.photo_crop = None;
+ let w = card_written(&c.contact, None, None, None, None);
+ assert_eq!(w["photo"], json!({ "url": "data:image/jpeg;base64,BBBB" }));
+ }
+
+ #[test]
+ fn a_whole_card_round_trips_through_json_as_the_interface_sends_it() {
+ let c = read();
+ let text = serde_json::to_string(&c).unwrap();
+ assert!(text.contains("\"jobTitle\":\"Architect\""));
+ assert!(text.contains("\"firstName\":\"Asha\""));
+ let back: Card = serde_json::from_str(&text).unwrap();
+ assert_eq!(back, c);
+ // A card from an older window, with none of the new fields, still reads.
+ let old: Card = serde_json::from_value(json!({
+ "guid": "X", "firstName": "A", "lastName": null, "company": null, "isCompany": false,
+ "birthday": null, "notes": null, "etag": null, "methods": []
+ }))
+ .unwrap();
+ assert!(old.details.is_empty());
+ }
+}
diff --git a/crates/quince-icloud/src/contacts_address.rs b/crates/quince-icloud/src/contacts_address.rs
index a8213fd..59bfad4 100644
--- a/crates/quince-icloud/src/contacts_address.rs
+++ b/crates/quince-icloud/src/contacts_address.rs
@@ -7,7 +7,7 @@
//! sent with the card's current etag and the book's sync token, so Apple refuses it rather
//! than overwrite a change it has not seen.
-use super::{postal_from, startup, write, Tokens};
+use super::{address_wire, postal_from, startup, write, Tokens};
use crate::{Error, Result};
use quince_core::contacts::{country_code_for, PostalAddress, ADDRESS_FIELDS};
use serde::{Deserialize, Serialize};
@@ -154,11 +154,11 @@ pub fn apply_edits(
}
/// Apple's entry for an address: its label, and every part that holds something.
-fn entry(address: &PostalAddress) -> Value {
+pub(super) fn entry(address: &PostalAddress) -> Value {
let mut field = Map::new();
for key in ADDRESS_FIELDS {
if let Some(Some(v)) = address.field(key) {
- field.insert(key.into(), Value::String(v.clone()));
+ field.insert(address_wire(key).into(), Value::String(v.clone()));
}
}
let mut e = Map::new();
@@ -253,12 +253,18 @@ pub fn merge_addresses(theirs: &[Value], changes: &[AddressChange]) -> Value {
if was == now {
continue;
}
+ // Under Apple's spelling of the part, whichever one this entry used.
+ let wire = if field.contains_key(key) {
+ key
+ } else {
+ address_wire(key)
+ };
match now.and_then(Option::as_ref) {
Some(v) => {
- field.insert(key.into(), Value::String(v.clone()));
+ field.insert(wire.into(), Value::String(v.clone()));
}
None => {
- field.remove(key);
+ field.remove(wire);
}
}
}
@@ -286,6 +292,25 @@ pub fn merge_addresses(theirs: &[Value], changes: &[AddressChange]) -> Value {
Value::Array(out.into_iter().flatten().chain(appended).collect())
}
+/// `edits`, made against `base`, laid over `current` the way a write lays them over Apple's
+/// card: what changed since `base` elsewhere stays, and only what the edits touch moves. What a
+/// queued edit shows while it waits, and what it shows again over each sync pass.
+///
+/// # Errors
+/// [`Error::Refused`] when an edit names an address or part `base` does not have.
+pub fn laid_over(
+ current: &[PostalAddress],
+ base: &[PostalAddress],
+ edits: &[AddressEdit],
+) -> Result<Vec<PostalAddress>> {
+ let (_, changes) = apply_edits(base, edits)?;
+ let theirs: Vec<Value> = current.iter().map(entry).collect();
+ Ok(match merge_addresses(&theirs, &changes) {
+ Value::Array(list) => list.iter().filter_map(postal_from).collect(),
+ _ => Vec::new(),
+ })
+}
+
/// Write `edits` to the card `guid`, over its addresses as Apple holds them now. `base` is
/// the list the edits were made against. Answers the card's addresses as written.
///
@@ -602,4 +627,36 @@ mod tests {
.unwrap();
assert_eq!(edits.len(), 4);
}
+
+ /// A queued edit shows over whatever a pass last read: a part changed on the phone since
+ /// stays, the part edited here wins, and laying it twice changes nothing more.
+ #[test]
+ fn a_queued_edit_lays_over_what_a_pass_read() {
+ let base = vec![home()];
+ let edits = vec![
+ AddressEdit::SetField {
+ index: 0,
+ field: "city".into(),
+ value: Some("Pune".into()),
+ },
+ AddressEdit::Add {
+ address: PostalAddress {
+ label: Some("WORK".into()),
+ city: Some("Mumbai".into()),
+ ..PostalAddress::default()
+ },
+ },
+ ];
+ let mut phone = home();
+ phone.postal_code = Some("654321".into());
+ let once = laid_over(&[phone], &base, &edits).unwrap();
+ assert_eq!(once.len(), 2);
+ assert_eq!(once[0].city.as_deref(), Some("Pune"));
+ assert_eq!(once[0].postal_code.as_deref(), Some("654321"));
+ assert_eq!(once[1].city.as_deref(), Some("Mumbai"));
+ assert_eq!(laid_over(&once, &base, &edits).unwrap(), once);
+ // A brand-new card: nothing at Apple yet, the additions are the list.
+ let fresh = laid_over(&[], &[], &edits[1..]).unwrap();
+ assert_eq!(fresh.len(), 1);
+ }
}
diff --git a/crates/quince-icloud/src/contacts_merge.rs b/crates/quince-icloud/src/contacts_merge.rs
new file mode 100644
index 0000000..3d89038
--- /dev/null
+++ b/crates/quince-icloud/src/contacts_merge.rs
@@ -0,0 +1,370 @@
+//! Merging cards that are one person, on Apple's own cards rather than this app's copy of
+//! them: whatever a card holds — the fields this app shows and any it does not — reaches the
+//! card that is kept. Every step is safe to take twice, so a merge cut off part way (offline,
+//! a restart) is simply sent again:
+//!
+//! 1. the kept card is written with everything from the others it lacks — written again, it
+//! already has it all, and nothing is added twice;
+//! 2. it joins every list the others were in — a list holds a person once;
+//! 3. the others are deleted — a card already gone is done.
+
+use super::{
+ address, card_written, contact_from, entry_label, entry_value, parse_lists, postal_from,
+ startup, string, write, ContactList, Tokens, METHOD_KEYS,
+};
+use crate::{Error, Result};
+use quince_core::contacts::merge::{joined_notes, method_key};
+use quince_core::contacts::{Card, ContactMethod, PostalAddress};
+use serde_json::{Map, Value};
+
+/// The address book as one read found it: every card as Apple holds it, its lists, and the
+/// tokens a write needs.
+pub struct Book {
+ body: Value,
+ pub tokens: Tokens,
+}
+
+impl Book {
+ /// Apple's card for one person, if it still has one.
+ #[must_use]
+ pub fn card(&self, guid: &str) -> Option<Value> {
+ self.body
+ .get("contacts")
+ .and_then(Value::as_array)?
+ .iter()
+ .find(|c| {
+ c.get("contactId")
+ .and_then(Value::as_str)
+ .is_some_and(|id| id.eq_ignore_ascii_case(guid))
+ })
+ .cloned()
+ }
+
+ /// Which card is this person's own.
+ #[must_use]
+ pub fn me(&self) -> Option<String> {
+ super::me_card(&self.body)
+ }
+
+ #[must_use]
+ pub fn lists(&self) -> Vec<ContactList> {
+ parse_lists(&self.body)
+ }
+}
+
+/// Read the book, with its tokens.
+///
+/// # Errors
+/// When Apple cannot be reached or refuses.
+pub async fn read_book(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+) -> Result<Book> {
+ let body = startup(http, root, params).await?;
+ let token = |key: &str| {
+ body.get(key)
+ .and_then(Value::as_str)
+ .map(ToString::to_string)
+ .ok_or_else(|| Error::Protocol(format!("/co/startup carried no {key}")))
+ };
+ let tokens = Tokens {
+ sync: token("syncToken")?,
+ pref: token("prefToken")?,
+ };
+ Ok(Book { body, tokens })
+}
+
+/// A card as this app last saw it, in Apple's shape — for a card merged here and gone from
+/// Apple before the merge was sent, so what it held still reaches the kept card.
+#[must_use]
+pub fn snapshot(card: &Card, addresses: &[PostalAddress]) -> Value {
+ let mut v = card_written(&card.contact, Some(&card.details), None, None, None);
+ if let Some(o) = v.as_object_mut() {
+ o.insert(
+ "streetAddresses".into(),
+ Value::Array(addresses.iter().map(address::entry).collect()),
+ );
+ o.remove("photo");
+ }
+ v
+}
+
+/// Keys that are the card's own bookkeeping, never carried from one card to another.
+const OWN: [&str; 11] = [
+ "contactId",
+ "etag",
+ "normalized",
+ "dateCreated",
+ "dateModified",
+ "photo",
+ "isCompany",
+ "order",
+ "whitelisted",
+ "isGuardianApproved",
+ "notes",
+];
+
+/// What makes two entries of one of Apple's lists the same entry.
+fn entry_key(key: &str, entry: &Value) -> String {
+ if key == "streetAddresses" {
+ if let Some(a) = postal_from(entry) {
+ let text = quince_core::fold::fold(&a.formatted());
+ return format!(
+ "address:{}",
+ text.split_whitespace().collect::<Vec<_>>().join(" ")
+ );
+ }
+ }
+ if let Some((_, kind)) = METHOD_KEYS.iter().find(|(k, _)| *k == key) {
+ if let Some(value) = entry_value(kind, entry) {
+ return method_key(&ContactMethod {
+ kind: (*kind).into(),
+ label: entry_label(kind, entry),
+ value,
+ });
+ }
+ }
+ format!("{key}:{entry}")
+}
+
+fn has_photo(card: &Value) -> bool {
+ card.pointer("/photo/url")
+ .and_then(Value::as_str)
+ .is_some_and(|u| !u.is_empty())
+}
+
+/// The kept card with everything the others hold that it lacks: a name, a company, a date or
+/// any other value it has none of; every entry of every list (numbers, emails, addresses,
+/// dates, people, profiles and any list this app does not know), each once; notes from each,
+/// joined. Answers the card, and the first other card's picture when the kept card has none —
+/// to be sent as an image of its own, since its link goes when that card is deleted.
+#[must_use]
+pub fn union(kept: &Value, others: &[Value]) -> (Value, Option<Value>) {
+ let mut out = kept.clone();
+ let mut photo = None;
+ let Some(o) = out.as_object_mut() else {
+ return (out, None);
+ };
+ for other in others {
+ let Some(theirs) = other.as_object() else {
+ continue;
+ };
+ for (key, value) in theirs {
+ if OWN.contains(&key.as_str()) {
+ continue;
+ }
+ match value {
+ Value::String(text) if !text.trim().is_empty() => {
+ let empty = o
+ .get(key)
+ .and_then(Value::as_str)
+ .is_none_or(|v| v.trim().is_empty());
+ if empty && !o.get(key).is_some_and(|v| !v.is_string() && !v.is_null()) {
+ o.insert(key.clone(), value.clone());
+ }
+ }
+ Value::Array(entries) => {
+ let mut list = o
+ .get(key)
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default();
+ let mut seen: Vec<String> = list.iter().map(|e| entry_key(key, e)).collect();
+ let mut grew = false;
+ for e in entries {
+ let k = entry_key(key, e);
+ if !seen.contains(&k) {
+ seen.push(k);
+ list.push(e.clone());
+ grew = true;
+ }
+ }
+ // Only a list that gained something is written: an empty one where the
+ // kept card had none would be a change of nothing.
+ if grew {
+ o.insert(key.clone(), Value::Array(list));
+ }
+ }
+ _ => {}
+ }
+ }
+ if photo.is_none() && !has_photo(kept) && has_photo(other) {
+ photo = other.get("photo").cloned();
+ }
+ }
+ let notes = joined_notes(
+ std::iter::once(kept)
+ .chain(others)
+ .map(|c| c.get("notes").and_then(Value::as_str)),
+ );
+ if let Some(n) = notes {
+ o.insert("notes".into(), Value::String(n));
+ }
+ (out, photo)
+}
+
+/// Write a card as it stands, against the version it carries.
+///
+/// # Errors
+/// [`Error::Conflict`] when it changed since it was read; otherwise when Apple refuses or
+/// cannot be reached.
+pub async fn put(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+ tokens: &Tokens,
+ card: Value,
+) -> Result<()> {
+ write(http, root, params, tokens, reqwest::Method::PUT, card).await?;
+ Ok(())
+}
+
+/// Delete a card by its id, against the version Apple holds.
+///
+/// # Errors
+/// When Apple refuses or cannot be reached.
+pub async fn delete_card(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+ tokens: &Tokens,
+ card: &Value,
+) -> Result<()> {
+ let Some(guid) = string(card, "contactId") else {
+ return Ok(());
+ };
+ let mut query = params;
+ query.push(("method".into(), "DELETE".into()));
+ write(
+ http,
+ root,
+ query,
+ tokens,
+ reqwest::Method::POST,
+ serde_json::json!({ "contactId": guid, "etag": card.get("etag") }),
+ )
+ .await?;
+ Ok(())
+}
+
+/// Whether a card read from Apple parses as a person at all — a guard before writing over it.
+#[must_use]
+pub fn readable(card: &Value) -> bool {
+ contact_from(card).is_some()
+}
+
+/// The entry Apple's card keeps a picture in, for an image sent whole as a `data:` URL.
+#[must_use]
+pub fn photo_entry(data_url: &str, crop: Option<(i64, i64, i64, i64)>) -> Value {
+ let mut p = Map::new();
+ p.insert("url".into(), Value::String(data_url.into()));
+ if let Some((x, y, width, height)) = crop {
+ p.insert(
+ "crop".into(),
+ serde_json::json!({ "x": x, "y": y, "width": width, "height": height }),
+ );
+ }
+ Value::Object(p)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn the_kept_card_gains_everything_and_repeats_nothing() {
+ let kept = json!({
+ "contactId": "A", "etag": "ea", "firstName": "Zoya", "lastName": "",
+ "phones": [{ "label": "MOBILE", "field": "+91 90000 00001" }],
+ "notes": "Met at the conference",
+ });
+ let other = json!({
+ "contactId": "B", "etag": "eb", "firstName": "Zoya", "lastName": "Ahuja",
+ "jobTitle": "Architect",
+ "phones": [{ "label": "_$!<Mobile>!$_", "field": "090000 00001" },
+ { "label": "WORK", "field": "+91 80 4000 0000" }],
+ "streetAddresses": [{ "label": "HOME", "field": { "street": "2 New Rd", "city": "Pune" } }],
+ "IMs": [{ "field": { "userName": "zoya", "IMService": "SKYPE" } }],
+ "X-SOMETHING-NEW": [{ "a": 1 }],
+ "notes": "Prefers WhatsApp",
+ "photo": { "url": "https://p/B", "crop": { "x": 0, "y": 0, "width": 10, "height": 10 } },
+ });
+ let (card, photo) = union(&kept, std::slice::from_ref(&other));
+ assert_eq!(card["contactId"], "A");
+ assert_eq!(card["etag"], "ea", "against the kept card's version");
+ assert_eq!(card["lastName"], "Ahuja");
+ assert_eq!(card["jobTitle"], "Architect");
+ assert_eq!(
+ card["phones"].as_array().unwrap().len(),
+ 2,
+ "the same number once"
+ );
+ assert_eq!(card["streetAddresses"][0]["field"]["city"], "Pune");
+ assert_eq!(card["IMs"][0]["field"]["IMService"], "SKYPE");
+ assert_eq!(
+ card["X-SOMETHING-NEW"][0]["a"], 1,
+ "even what this app does not know"
+ );
+ assert_eq!(card["notes"], "Met at the conference\n\nPrefers WhatsApp");
+ assert!(
+ card.get("photo").is_none(),
+ "a picture is sent as an image of its own"
+ );
+ assert_eq!(photo.unwrap()["url"], "https://p/B");
+
+ // Sent again over what the first send wrote: nothing changes.
+ let (again, photo) = union(&card, std::slice::from_ref(&other));
+ assert_eq!(again, card);
+ assert!(photo.is_some(), "still none on the kept card");
+ let mut with_photo = card.clone();
+ with_photo["photo"] = json!({ "url": "https://p/A" });
+ assert!(
+ union(&with_photo, &[other]).1.is_none(),
+ "a kept picture stays"
+ );
+ }
+
+ #[test]
+ fn a_card_gone_from_apple_still_brings_what_it_held() {
+ use quince_core::contacts::{Contact, ContactDetails};
+ let card = Card {
+ contact: Contact {
+ guid: "B".into(),
+ first_name: Some("Zoya".into()),
+ middle_name: None,
+ photo_url: None,
+ photo_signature: None,
+ photo_crop: None,
+ last_name: None,
+ company: None,
+ is_company: false,
+ birthday: Some("1604-03-17".into()),
+ notes: None,
+ etag: None,
+ methods: vec![ContactMethod {
+ kind: "related".into(),
+ label: Some("MOTHER".into()),
+ value: "Amma".into(),
+ }],
+ },
+ details: ContactDetails {
+ nickname: Some("Zo".into()),
+ ..ContactDetails::default()
+ },
+ };
+ let home = PostalAddress {
+ label: Some("HOME".into()),
+ city: Some("Pune".into()),
+ ..PostalAddress::default()
+ };
+ let v = snapshot(&card, &[home]);
+ assert_eq!(v["birthday"], "1604-03-17");
+ assert_eq!(v["nickName"], "Zo");
+ assert_eq!(v["relatedNames"][0]["label"], "MOTHER");
+ assert_eq!(v["streetAddresses"][0]["field"]["city"], "Pune");
+ let (merged, _) = union(&json!({ "contactId": "A", "firstName": "Zoya" }), &[v]);
+ assert_eq!(merged["relatedNames"][0]["field"], "Amma");
+ }
+}
diff --git a/crates/quince-icloud/src/courier.rs b/crates/quince-icloud/src/courier.rs
new file mode 100644
index 0000000..8151c26
--- /dev/null
+++ b/crates/quince-icloud/src/courier.rs
@@ -0,0 +1,970 @@
+//! Apple's push "web courier": the live channel icloud.com uses today to hear that something
+//! changed on another device.
+//!
+//! The older path — a token from `ckdeviceservice …/tokens/create`, long-polled on its
+//! `webcourierURL` — is retired: Apple answers it `403 ACCESS_DENIED, "This endpoint is
+//! deprecated."`, and the `push` service's `getToken` that the shell's own long-poll fallback
+//! used no longer resolves at all. What icloud.com's shell (`push-service-sharedworker`, build
+//! 2638Build27, read 2026-10-22) does instead, and this module does the same:
+//!
+//! 1. Make a P-256 key. Sign a nonce — `[0, unix-ms as 8 bytes big-endian, 8 random bytes]` —
+//! with ECDSA-SHA256; the signature goes as `[1, 3]` followed by its DER.
+//! 2. Open `wss://websocket.push.apple.com/v2/<hex of a WebClientConnectionMessage>` carrying
+//! the public key, nonce, signature and `newConnectionRequest { tokenExpirationSeconds }`
+//! (or `connectWithPushToken` to keep a token across a reconnect).
+//! 3. The first frame back is a `connectionResponseMessage`: a base64 push token, or
+//! `INVALID_NONCE` with the server's clock to sign against instead.
+//! 4. Send a `webFilterMessage` with the topics wanted — `com.apple.icloud-container.<id>` —
+//! and a `jwtRequestMessage`; the socket answers with a short-lived JWT.
+//! 5. Register the token for those topics with the push registry ("PDS"):
+//! `POST https://gatewayws.icloud.com/pds/WebObjects/pushregistry.woa/webBatchRegister/batchRegisterToken`,
+//! a protobuf `BatchRegisterReq` signed with the same key (nonce kind 2), sent with the
+//! session's cookies. Status 0 is success.
+//! 6. Pushes then arrive on the socket as `pushMessage`s — topic (or its SHA-1), id and a JSON
+//! payload like `{"ck":{"cid":"com.apple.notes", "met":{…}}}` — and each is acknowledged
+//! with its id and topic.
+//!
+//! Nothing is created or changed in iCloud by any of this: the account's own devices keep the
+//! CloudKit subscriptions that fire, as before.
+
+use crate::Error;
+use futures_util::{SinkExt, StreamExt};
+use p256::ecdsa::{signature::Signer, Signature, SigningKey};
+use rand_core::{OsRng, RngCore};
+use serde_json::Value;
+use std::time::Duration;
+use tokio_tungstenite::tungstenite::{self, client::IntoClientRequest, Message};
+
+/// The production push server icloud.com's shell connects to.
+pub const SERVER: &str = "websocket.push.apple.com";
+
+/// The push registry the token is registered with.
+pub const REGISTRY: &str =
+ "https://gatewayws.icloud.com/pds/WebObjects/pushregistry.woa/webBatchRegister/batchRegisterToken";
+
+/// How long a token asked for lives — the shell's own `86400`.
+const TOKEN_SECONDS: u32 = 86_400;
+
+/// How long a registration with the registry lasts — the shell's `43200`.
+pub const REGISTRATION_SECONDS: u64 = 43_200;
+
+/// The topic a CloudKit container's pushes come on.
+#[must_use]
+pub fn topic_of(container: &str) -> String {
+ format!("com.apple.icloud-container.{container}")
+}
+
+/// The container a topic is for, if it is a CloudKit one.
+#[must_use]
+pub fn container_of_topic(topic: &str) -> Option<&str> {
+ topic.strip_prefix("com.apple.icloud-container.")
+}
+
+fn hex(bytes: &[u8]) -> String {
+ use std::fmt::Write;
+ bytes.iter().fold(String::new(), |mut s, b| {
+ let _ = write!(s, "{b:02x}");
+ s
+ })
+}
+
+// --- protobuf, the few messages this needs ------------------------------------------------
+
+mod pb {
+ /// A protobuf writer: just the wire types these messages use.
+ #[derive(Default)]
+ pub struct W(pub Vec<u8>);
+
+ impl W {
+ fn varint(&mut self, mut v: u64) {
+ while v >= 0x80 {
+ self.0.push((v as u8) | 0x80);
+ v >>= 7;
+ }
+ self.0.push(v as u8);
+ }
+ pub fn uint(&mut self, field: u32, v: u64) -> &mut Self {
+ self.varint(u64::from(field) << 3);
+ self.varint(v);
+ self
+ }
+ pub fn bytes(&mut self, field: u32, v: &[u8]) -> &mut Self {
+ self.varint((u64::from(field) << 3) | 2);
+ self.varint(v.len() as u64);
+ self.0.extend_from_slice(v);
+ self
+ }
+ pub fn string(&mut self, field: u32, v: &str) -> &mut Self {
+ self.bytes(field, v.as_bytes())
+ }
+ pub fn message(&mut self, field: u32, inner: &W) -> &mut Self {
+ self.bytes(field, &inner.0)
+ }
+ }
+
+ /// One field as read: its number and either a varint or a length-delimited slice.
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+ pub enum V<'a> {
+ Int(u64),
+ Bytes(&'a [u8]),
+ }
+
+ fn varint(buf: &[u8], at: &mut usize) -> Option<u64> {
+ let mut v = 0u64;
+ for shift in (0..64).step_by(7) {
+ let b = *buf.get(*at)?;
+ *at += 1;
+ v |= u64::from(b & 0x7f) << shift;
+ if b < 0x80 {
+ return Some(v);
+ }
+ }
+ None
+ }
+
+ /// Every field of a message, in order. `None` for a malformed one.
+ pub fn fields(buf: &[u8]) -> Option<Vec<(u32, V<'_>)>> {
+ let mut at = 0;
+ let mut out = Vec::new();
+ while at < buf.len() {
+ let key = varint(buf, &mut at)?;
+ let field = u32::try_from(key >> 3).ok()?;
+ match key & 7 {
+ 0 => out.push((field, V::Int(varint(buf, &mut at)?))),
+ 2 => {
+ let len = usize::try_from(varint(buf, &mut at)?).ok()?;
+ let end = at.checked_add(len).filter(|e| *e <= buf.len())?;
+ out.push((field, V::Bytes(&buf[at..end])));
+ at = end;
+ }
+ 1 => at = at.checked_add(8).filter(|e| *e <= buf.len())?,
+ 5 => at = at.checked_add(4).filter(|e| *e <= buf.len())?,
+ _ => return None,
+ }
+ }
+ Some(out)
+ }
+
+ pub fn int(fields: &[(u32, V<'_>)], n: u32) -> Option<u64> {
+ fields.iter().find_map(|(f, v)| match v {
+ V::Int(i) if *f == n => Some(*i),
+ _ => None,
+ })
+ }
+
+ pub fn bytes<'a>(fields: &[(u32, V<'a>)], n: u32) -> Option<&'a [u8]> {
+ fields.iter().find_map(|(f, v)| match v {
+ V::Bytes(b) if *f == n => Some(*b),
+ _ => None,
+ })
+ }
+}
+
+// --- signing --------------------------------------------------------------------------------
+
+/// A nonce, signed: what both the socket and the registry are shown.
+#[derive(Debug, Clone)]
+pub struct Signed {
+ pub public_key: Vec<u8>,
+ pub nonce: Vec<u8>,
+ pub signature: Vec<u8>,
+}
+
+/// The nonce the shell signs. `kind` is the registry's purpose byte (`pds` = 2), absent for
+/// the socket's own connect message.
+fn nonce(unix_ms: u64, kind: Option<u8>) -> Vec<u8> {
+ let mut random = [0u8; 8];
+ OsRng.fill_bytes(&mut random);
+ let mut n = Vec::with_capacity(18);
+ match kind {
+ Some(k) => {
+ n.push(1);
+ n.extend_from_slice(&unix_ms.to_be_bytes());
+ n.push(k);
+ }
+ None => {
+ n.push(0);
+ n.extend_from_slice(&unix_ms.to_be_bytes());
+ }
+ }
+ n.extend_from_slice(&random);
+ n
+}
+
+/// The signature as the shell lays it out: `[1, 3]`, then a DER `SEQUENCE { INTEGER r,
+/// INTEGER s }` whose integers keep all 32 bytes, with a zero in front when the top bit is set.
+fn shell_signature(sig: &Signature) -> Vec<u8> {
+ let raw = sig.to_bytes();
+ let (r, s) = raw.split_at(32);
+ let int = |v: &[u8]| {
+ let mut out = vec![2u8];
+ let pad = v[0] > 127;
+ out.push(32 + u8::from(pad));
+ if pad {
+ out.push(0);
+ }
+ out.extend_from_slice(v);
+ out
+ };
+ let (r, s) = (int(r), int(s));
+ let mut out = vec![1u8, 3, 48, (r.len() + s.len()) as u8];
+ out.extend(r);
+ out.extend(s);
+ out
+}
+
+/// The key a connection is made with and the token Apple gave it. Kept across reconnects, so
+/// a dropped socket comes back on the same token and its registrations still stand.
+pub struct Identity {
+ key: SigningKey,
+ token: Option<Vec<u8>>,
+}
+
+impl Default for Identity {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Identity {
+ #[must_use]
+ pub fn new() -> Self {
+ Self {
+ key: SigningKey::random(&mut OsRng),
+ token: None,
+ }
+ }
+
+ /// Whether Apple has given this identity a token yet.
+ #[must_use]
+ pub fn has_token(&self) -> bool {
+ self.token.is_some()
+ }
+
+ /// Start over with no token: the next connection asks for a new one.
+ pub fn forget_token(&mut self) {
+ self.token = None;
+ }
+
+ #[must_use]
+ pub fn sign(&self, unix_ms: u64, kind: Option<u8>) -> Signed {
+ let nonce = nonce(unix_ms, kind);
+ let sig: Signature = self.key.sign(&nonce);
+ Signed {
+ public_key: self
+ .key
+ .verifying_key()
+ .to_encoded_point(false)
+ .as_bytes()
+ .to_vec(),
+ nonce,
+ signature: shell_signature(&sig),
+ }
+ }
+
+ /// The `WebClientConnectionMessage`, hex-encoded, that goes in the socket's address.
+ fn connect_message(&self, unix_ms: u64) -> String {
+ let s = self.sign(unix_ms, None);
+ let mut v1 = pb::W::default();
+ v1.bytes(1, &s.public_key)
+ .bytes(2, &s.nonce)
+ .bytes(3, &s.signature);
+ match &self.token {
+ Some(token) => {
+ let mut with = pb::W::default();
+ with.string(
+ 1,
+ &base64::Engine::encode(&base64::engine::general_purpose::STANDARD, token),
+ );
+ v1.message(4, &with);
+ }
+ None => {
+ let mut new = pb::W::default();
+ new.uint(1, u64::from(TOKEN_SECONDS));
+ v1.message(5, &new);
+ }
+ }
+ let mut outer = pb::W::default();
+ outer.message(1, &v1);
+ hex(&outer.0)
+ }
+}
+
+fn now_ms() -> u64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_millis() as u64)
+ .unwrap_or(0)
+}
+
+// --- the socket -----------------------------------------------------------------------------
+
+type Ws =
+ tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
+
+/// What the socket said, as far as the app cares.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Event {
+ /// A change in this CloudKit container.
+ Changed(String),
+ /// A push for something else, or one whose payload named no container.
+ Other,
+}
+
+/// Why the channel could not be opened or was lost.
+#[derive(Debug)]
+pub enum Failure {
+ /// Apple refused outright — a bad request, failed authentication, a retired endpoint. Asking
+ /// again soon will be refused again.
+ Refused(String),
+ /// Apple asked to be left alone for a while.
+ RateLimited(Duration),
+ /// The session needs a fresh sign-in.
+ Reauth,
+ /// The network, a dropped socket, a timeout: worth trying again shortly.
+ Transient(String),
+}
+
+impl std::fmt::Display for Failure {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Refused(why) => write!(f, "refused: {why}"),
+ Self::RateLimited(d) => write!(f, "rate limited for {}s", d.as_secs()),
+ Self::Reauth => write!(f, "needs a fresh sign-in"),
+ Self::Transient(why) => write!(f, "{why}"),
+ }
+ }
+}
+
+impl From<Error> for Failure {
+ fn from(e: Error) -> Self {
+ match e {
+ Error::ReauthRequired => Self::Reauth,
+ Error::Refused(why) => Self::Refused(why),
+ other => Self::Transient(other.to_string()),
+ }
+ }
+}
+
+/// A live connection to the push server, subscribed to some CloudKit containers.
+pub struct Courier {
+ ws: Ws,
+ topics: Vec<String>,
+ /// SHA-1 of each topic, as a push may name its topic that way.
+ hashed: Vec<([u8; 20], String)>,
+}
+
+fn sha1(s: &str) -> [u8; 20] {
+ use sha1::Digest;
+ sha1::Sha1::digest(s.as_bytes()).into()
+}
+
+/// The connection-response status codes (`WebConnectionResponseMessage.Status`).
+const OK: u64 = 0;
+const INVALID_NONCE: u64 = 2;
+const RATE_LIMITED: u64 = 4;
+const EXPIRED_PUSH_TOKEN: u64 = 6;
+
+/// How long the server is given to answer the connect, and a JWT request.
+const ANSWER: Duration = Duration::from_secs(15);
+
+impl Courier {
+ /// Connect to `server` (normally [`SERVER`]), get or keep a token, and filter the socket
+ /// to the containers' topics. Not yet registered: see [`Courier::register`].
+ pub async fn connect(
+ server: &str,
+ identity: &mut Identity,
+ containers: &[&str],
+ ) -> std::result::Result<Self, Failure> {
+ // Only Apple's push server, ever: the socket does not ride the HTTP client's locks.
+ let host = server
+ .split("://")
+ .last()
+ .unwrap_or(server)
+ .split(['/', ':'])
+ .next()
+ .unwrap_or_default();
+ if !(host.ends_with(".apple.com") || host == "localhost" || host == "127.0.0.1") {
+ return Err(Failure::Refused(format!("{host} is not Apple's")));
+ }
+ let scheme = if server.starts_with("ws://") {
+ ""
+ } else {
+ "wss://"
+ };
+ let topics: Vec<String> = containers.iter().map(|c| topic_of(c)).collect();
+ let mut clock: Option<u64> = None;
+ for _ in 0..3 {
+ let url = format!(
+ "{scheme}{server}/v2/{}",
+ identity.connect_message(clock.unwrap_or_else(now_ms))
+ );
+ let mut request = url
+ .into_client_request()
+ .map_err(|e| Failure::Transient(format!("bad push address: {e}")))?;
+ request.headers_mut().insert(
+ "origin",
+ tungstenite::http::HeaderValue::from_static("https://www.icloud.com"),
+ );
+ let (mut ws, _) =
+ tokio::time::timeout(ANSWER, tokio_tungstenite::connect_async(request))
+ .await
+ .map_err(|_| Failure::Transient("the push server did not answer".into()))?
+ .map_err(|e| match e {
+ tungstenite::Error::Http(r) => {
+ let s = r.status().as_u16();
+ if matches!(s, 400 | 401 | 403 | 404 | 410) {
+ Failure::Refused(format!("the push server answered {s}"))
+ } else {
+ Failure::Transient(format!("the push server answered {s}"))
+ }
+ }
+ other => Failure::Transient(format!("push socket: {}", words(&other))),
+ })?;
+ let first = tokio::time::timeout(ANSWER, next_binary(&mut ws))
+ .await
+ .map_err(|_| Failure::Transient("no answer to the connect".into()))??;
+ let outer = pb::fields(&first)
+ .ok_or_else(|| Failure::Transient("an unreadable connect answer".into()))?;
+ let Some(response) = pb::bytes(&outer, 1).and_then(pb::fields) else {
+ return Err(Failure::Transient(
+ "the connect was answered with something else".into(),
+ ));
+ };
+ let status = pb::int(&response, 2).unwrap_or(OK);
+ match status {
+ OK => {
+ let token = pb::bytes(&response, 1)
+ .and_then(|b| std::str::from_utf8(b).ok())
+ .and_then(|t| {
+ base64::Engine::decode(&base64::engine::general_purpose::STANDARD, t)
+ .ok()
+ })
+ .filter(|t| !t.is_empty())
+ .ok_or_else(|| Failure::Transient("connected without a token".into()))?;
+ identity.token = Some(token);
+ let mut courier = Self {
+ ws,
+ hashed: topics.iter().map(|t| (sha1(t), t.clone())).collect(),
+ topics,
+ };
+ let mut filter = pb::W::default();
+ for t in &courier.topics {
+ filter.string(1, t);
+ }
+ courier.send(3, &filter).await?;
+ return Ok(courier);
+ }
+ INVALID_NONCE => {
+ // Our clock is off from Apple's: sign against theirs, as the shell does.
+ clock = pb::int(&response, 3).map(|s| s.saturating_mul(1000));
+ if clock.is_none() {
+ return Err(Failure::Transient("nonce refused without a clock".into()));
+ }
+ }
+ EXPIRED_PUSH_TOKEN => identity.forget_token(),
+ RATE_LIMITED => return Err(Failure::RateLimited(Duration::from_secs(15 * 60))),
+ other => {
+ // A kept token that is refused is dropped; a fresh connection is refused
+ // for a reason asking again won't change.
+ if identity.token.take().is_none() {
+ return Err(Failure::Refused(format!("connect status {other}")));
+ }
+ }
+ }
+ }
+ Err(Failure::Transient(
+ "the push server would not take the connect".into(),
+ ))
+ }
+
+ async fn send(&mut self, field: u32, inner: &pb::W) -> std::result::Result<(), Failure> {
+ let mut outer = pb::W::default();
+ outer.message(field, inner);
+ self.ws
+ .send(Message::binary(outer.0))
+ .await
+ .map_err(|e| Failure::Transient(format!("push socket: {}", words(&e))))
+ }
+
+ /// Ask the socket for the short-lived JWT the registry wants.
+ async fn jwt(&mut self) -> std::result::Result<String, Failure> {
+ let mut ask = pb::W::default();
+ ask.uint(1, 600);
+ self.send(7, &ask).await?;
+ let deadline = tokio::time::Instant::now() + ANSWER;
+ loop {
+ let frame = tokio::time::timeout_at(deadline, next_binary(&mut self.ws))
+ .await
+ .map_err(|_| Failure::Transient("no JWT came back".into()))??;
+ let Some(outer) = pb::fields(&frame) else {
+ continue;
+ };
+ if let Some(answer) = pb::bytes(&outer, 8).and_then(pb::fields) {
+ return match pb::int(&answer, 2) {
+ Some(1) => pb::bytes(&answer, 1)
+ .and_then(|b| std::str::from_utf8(b).ok())
+ .map(str::to_string)
+ .filter(|j| !j.is_empty())
+ .ok_or_else(|| Failure::Transient("an empty JWT".into())),
+ Some(3) => Err(Failure::RateLimited(Duration::from_secs(10 * 60))),
+ other => Err(Failure::Transient(format!("JWT status {other:?}"))),
+ };
+ }
+ // A push that raced the answer is acknowledged and otherwise left to the next
+ // full pass, which runs once the channel is up.
+ self.acknowledge(&outer).await?;
+ }
+ }
+
+ /// Register this connection's token for its topics with the push registry, using the
+ /// session's cookies. Must be done after each new token and before a registration
+ /// lapses ([`REGISTRATION_SECONDS`]).
+ pub async fn register(
+ &mut self,
+ http: &reqwest::Client,
+ registry: &str,
+ identity: &Identity,
+ dsid: &str,
+ ) -> std::result::Result<(), Failure> {
+ let jwt = self.jwt().await?;
+ let token = identity
+ .token
+ .as_deref()
+ .ok_or_else(|| Failure::Transient("no token to register".into()))?;
+ let body = registration(identity, token, dsid, &jwt, &self.topics, now_ms());
+ let response = http
+ .post(registry)
+ .header("x-protocol-version", "1")
+ .header("x-pds-client-version", "2")
+ .header("x-pds-client-type", "iCloudCom")
+ .header("x-registration-reason", "1")
+ .header("content-type", "application/protobuf")
+ .body(body)
+ .send()
+ .await
+ .map_err(|e| Failure::from(Error::from(e)))?;
+ let status = response.status();
+ if matches!(status.as_u16(), 401 | 421 | 450) {
+ return Err(Failure::Reauth);
+ }
+ let bytes = response.bytes().await.unwrap_or_default();
+ if !status.is_success() {
+ return Err(if matches!(status.as_u16(), 400 | 403 | 404 | 410) {
+ Failure::Refused(format!("the push registry answered {status}"))
+ } else {
+ Failure::Transient(format!("the push registry answered {status}"))
+ });
+ }
+ let fields = pb::fields(&bytes)
+ .ok_or_else(|| Failure::Transient("an unreadable registry answer".into()))?;
+ match pb::int(&fields, 1).unwrap_or(0) {
+ 0 => Ok(()),
+ // RETRY_WITH_DELAY and friends: try again after what it says, or a while.
+ code @ (6002 | 6003 | 6007) => {
+ let wait = pb::int(&fields, 5).filter(|s| *s > 0).unwrap_or(60);
+ quiet!("push: registry status {code}, asked to wait {wait}s");
+ Err(Failure::RateLimited(Duration::from_secs(wait.min(3600))))
+ }
+ 6005 | 6008 | 6010 => Err(Failure::Reauth),
+ code => Err(Failure::Refused(format!("registry status {code}"))),
+ }
+ }
+
+ /// Acknowledge a push in `outer` if it is one, returning what it was about.
+ async fn acknowledge(
+ &mut self,
+ outer: &[(u32, pb::V<'_>)],
+ ) -> std::result::Result<Option<Event>, Failure> {
+ let Some(push) = pb::bytes(outer, 2).and_then(pb::fields) else {
+ return Ok(None);
+ };
+ let topic = pb::bytes(&push, 1).unwrap_or_default();
+ if let Some(id) = pb::int(&push, 2) {
+ let mut ack = pb::W::default();
+ ack.bytes(1, topic).uint(2, id);
+ self.send(2, &ack).await?;
+ }
+ let named = self.topic_name(topic);
+ let payload = pb::bytes(&push, 4)
+ .and_then(|p| serde_json::from_slice::<Value>(p).ok())
+ .unwrap_or(Value::Null);
+ let container = crate::push::container_of(&payload)
+ .or_else(|| named.and_then(|t| container_of_topic(&t).map(str::to_string)));
+ Ok(Some(container.map_or(Event::Other, Event::Changed)))
+ }
+
+ fn topic_name(&self, topic: &[u8]) -> Option<String> {
+ if let Some((_, t)) = self.hashed.iter().find(|(h, _)| h.as_slice() == topic) {
+ return Some(t.clone());
+ }
+ std::str::from_utf8(topic).ok().map(str::to_string)
+ }
+
+ /// Wait up to `longest` for the next push. `Ok(None)` is a quiet wait. The socket is pinged
+ /// while quiet, so a connection that died without closing is found within `longest`.
+ pub async fn next(&mut self, longest: Duration) -> std::result::Result<Option<Event>, Failure> {
+ let deadline = tokio::time::Instant::now() + longest;
+ let mut pinged: Option<tokio::time::Instant> = None;
+ loop {
+ let now = tokio::time::Instant::now();
+ if now >= deadline {
+ return Ok(None);
+ }
+ // A ping every minute of quiet; no answer at all within 30 s is a dead socket.
+ let wake = match pinged {
+ Some(at) => (at + Duration::from_secs(30)).min(deadline),
+ None => (now + Duration::from_secs(60)).min(deadline),
+ };
+ match tokio::time::timeout_at(wake, self.ws.next()).await {
+ Err(_) => match pinged {
+ Some(_) if tokio::time::Instant::now() < deadline => {
+ return Err(Failure::Transient(
+ "the push socket stopped answering".into(),
+ ))
+ }
+ Some(_) => return Ok(None),
+ None => {
+ self.ws
+ .send(Message::Ping(Vec::new().into()))
+ .await
+ .map_err(|e| {
+ Failure::Transient(format!("push socket: {}", words(&e)))
+ })?;
+ pinged = Some(tokio::time::Instant::now());
+ }
+ },
+ Ok(None) => return Err(Failure::Transient("the push socket closed".into())),
+ Ok(Some(Err(e))) => {
+ return Err(Failure::Transient(format!("push socket: {}", words(&e))))
+ }
+ Ok(Some(Ok(frame))) => {
+ pinged = None;
+ match frame {
+ Message::Binary(b) => {
+ let Some(outer) = pb::fields(&b) else {
+ continue;
+ };
+ if let Some(event) = self.acknowledge(&outer).await? {
+ return Ok(Some(event));
+ }
+ }
+ Message::Close(c) => {
+ return Err(Failure::Transient(format!(
+ "the push server closed the socket ({})",
+ c.map_or(0, |c| u16::from(c.code))
+ )))
+ }
+ _ => {}
+ }
+ }
+ }
+ }
+ }
+
+ /// Close politely.
+ pub async fn close(mut self) {
+ self.ws.close(None).await.ok();
+ }
+}
+
+/// The next binary frame, answering pings on the way (tungstenite queues the pong).
+async fn next_binary(ws: &mut Ws) -> std::result::Result<Vec<u8>, Failure> {
+ loop {
+ match ws.next().await {
+ Some(Ok(Message::Binary(b))) => return Ok(b.to_vec()),
+ Some(Ok(Message::Close(c))) => {
+ return Err(Failure::Transient(format!(
+ "the push server closed the socket ({})",
+ c.map_or(0, |c| u16::from(c.code))
+ )))
+ }
+ Some(Ok(_)) => {}
+ Some(Err(e)) => return Err(Failure::Transient(format!("push socket: {}", words(&e)))),
+ None => return Err(Failure::Transient("the push socket closed".into())),
+ }
+ }
+}
+
+/// A socket error in words, with no address in it (the address carries a signed nonce).
+fn words(e: &tungstenite::Error) -> String {
+ match e {
+ tungstenite::Error::Io(io) => format!("{}", io.kind()),
+ tungstenite::Error::Tls(_) => "a TLS failure".into(),
+ tungstenite::Error::ConnectionClosed | tungstenite::Error::AlreadyClosed => "closed".into(),
+ tungstenite::Error::Protocol(p) => format!("{p}"),
+ tungstenite::Error::Http(r) => format!("HTTP {}", r.status()),
+ tungstenite::Error::Url(_) => "a bad address".into(),
+ _ => "a socket error".into(),
+ }
+}
+
+/// The registry's `BatchRegisterReq` for one token and its topics.
+fn registration(
+ identity: &Identity,
+ token: &[u8],
+ dsid: &str,
+ jwt: &str,
+ topics: &[String],
+ unix_ms: u64,
+) -> Vec<u8> {
+ let signed = identity.sign(unix_ms, Some(2));
+ let mut web = pb::W::default();
+ web.bytes(1, &signed.nonce)
+ .bytes(2, &signed.public_key)
+ .bytes(3, &signed.signature)
+ .bytes(4, jwt.as_bytes());
+ let mut token_auth = pb::W::default();
+ token_auth.message(1, &web);
+ let mut user_auth = pb::W::default();
+ user_auth.message(2, &pb::W::default());
+ let mut user_token = pb::W::default();
+ user_token
+ .string(1, dsid)
+ .message(2, &user_auth)
+ .string(3, &hex(token).to_uppercase())
+ .message(4, &token_auth);
+ let mut request = pb::W::default();
+ request.message(1, &user_token);
+ for t in topics {
+ let qualifier = container_of_topic(t)
+ .map(|c| format!("{c}_P"))
+ .unwrap_or_default();
+ let mut topic = pb::W::default();
+ topic.string(1, t).string(2, &qualifier).uint(4, 5); // client: ICLOUDCOM
+ request.message(4, &topic);
+ }
+ let mut batch = pb::W::default();
+ batch.message(1, &request).uint(2, REGISTRATION_SECONDS);
+ batch.0
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use p256::ecdsa::{signature::Verifier, VerifyingKey};
+
+ #[test]
+ fn a_container_is_its_topic_and_back() {
+ assert_eq!(
+ topic_of("com.apple.notes"),
+ "com.apple.icloud-container.com.apple.notes"
+ );
+ assert_eq!(
+ container_of_topic("com.apple.icloud-container.com.apple.reminders"),
+ Some("com.apple.reminders")
+ );
+ assert_eq!(container_of_topic("com.apple.mail"), None);
+ }
+
+ #[test]
+ fn the_nonce_is_laid_out_as_the_shell_lays_it() {
+ let n = nonce(0x0102_0304_0506_0708, None);
+ assert_eq!(n.len(), 17);
+ assert_eq!(&n[..9], &[0, 1, 2, 3, 4, 5, 6, 7, 8]);
+ let n = nonce(0x0102_0304_0506_0708, Some(2));
+ assert_eq!(n.len(), 18);
+ assert_eq!(&n[..10], &[1, 1, 2, 3, 4, 5, 6, 7, 8, 2]);
+ }
+
+ #[test]
+ fn the_signature_verifies_once_unwrapped() {
+ let id = Identity::new();
+ let s = id.sign(1_700_000_000_000, None);
+ assert_eq!(s.public_key.len(), 65);
+ assert_eq!(s.public_key[0], 4, "uncompressed point");
+ assert_eq!(&s.signature[..3], &[1, 3, 48]);
+ // Strip the shell's framing back to r and s, and check them against the key.
+ let der = &s.signature[2..];
+ let mut at = 2;
+ let mut part = || {
+ assert_eq!(der[at], 2);
+ let len = der[at + 1] as usize;
+ let v = &der[at + 2..at + 2 + len];
+ at += 2 + len;
+ v[v.len() - 32..].to_vec()
+ };
+ let (r, sv) = (part(), part());
+ let sig = Signature::from_scalars(
+ *p256::FieldBytes::from_slice(&r),
+ *p256::FieldBytes::from_slice(&sv),
+ )
+ .unwrap();
+ let key = VerifyingKey::from_sec1_bytes(&s.public_key).unwrap();
+ key.verify(&s.nonce, &sig).unwrap();
+ }
+
+ #[test]
+ fn the_connect_message_asks_for_a_new_token_then_keeps_it() {
+ let mut id = Identity::new();
+ let fresh = id.connect_message(1);
+ let bytes: Vec<u8> = (0..fresh.len())
+ .step_by(2)
+ .map(|i| u8::from_str_radix(&fresh[i..i + 2], 16).unwrap())
+ .collect();
+ let outer = pb::fields(&bytes).unwrap();
+ let v1 = pb::fields(pb::bytes(&outer, 1).unwrap()).unwrap();
+ assert_eq!(pb::bytes(&v1, 1).unwrap().len(), 65);
+ assert_eq!(pb::bytes(&v1, 2).unwrap().len(), 17);
+ let new = pb::fields(pb::bytes(&v1, 5).unwrap()).unwrap();
+ assert_eq!(pb::int(&new, 1), Some(86_400));
+ assert!(pb::bytes(&v1, 4).is_none());
+
+ id.token = Some(vec![0xAB, 0xCD]);
+ let kept = id.connect_message(1);
+ let bytes: Vec<u8> = (0..kept.len())
+ .step_by(2)
+ .map(|i| u8::from_str_radix(&kept[i..i + 2], 16).unwrap())
+ .collect();
+ let outer = pb::fields(&bytes).unwrap();
+ let v1 = pb::fields(pb::bytes(&outer, 1).unwrap()).unwrap();
+ let with = pb::fields(pb::bytes(&v1, 4).unwrap()).unwrap();
+ assert_eq!(pb::bytes(&with, 1), Some(&b"q80="[..]));
+ assert!(pb::bytes(&v1, 5).is_none());
+ }
+
+ #[test]
+ fn the_registration_names_each_topic_for_icloud_com() {
+ let id = Identity::new();
+ let body = registration(
+ &id,
+ &[0xAB, 0x01],
+ "123",
+ "J.W.T",
+ &[topic_of("com.apple.notes")],
+ 5,
+ );
+ let batch = pb::fields(&body).unwrap();
+ assert_eq!(pb::int(&batch, 2), Some(43_200));
+ let request = pb::fields(pb::bytes(&batch, 1).unwrap()).unwrap();
+ let user = pb::fields(pb::bytes(&request, 1).unwrap()).unwrap();
+ assert_eq!(pb::bytes(&user, 1), Some(&b"123"[..]));
+ assert_eq!(pb::bytes(&user, 3), Some(&b"AB01"[..]), "upper-case hex");
+ let auth = pb::fields(pb::bytes(&user, 2).unwrap()).unwrap();
+ assert_eq!(pb::bytes(&auth, 2), Some(&b""[..]), "icloudAuth, empty");
+ let web =
+ pb::fields(pb::bytes(&pb::fields(pb::bytes(&user, 4).unwrap()).unwrap(), 1).unwrap())
+ .unwrap();
+ assert_eq!(pb::bytes(&web, 1).unwrap()[9], 2, "a registry nonce");
+ assert_eq!(pb::bytes(&web, 4), Some(&b"J.W.T"[..]));
+ let topic = pb::fields(pb::bytes(&request, 4).unwrap()).unwrap();
+ assert_eq!(
+ pb::bytes(&topic, 1),
+ Some(&b"com.apple.icloud-container.com.apple.notes"[..])
+ );
+ assert_eq!(pb::bytes(&topic, 2), Some(&b"com.apple.notes_P"[..]));
+ assert_eq!(pb::int(&topic, 4), Some(5));
+ }
+
+ /// The whole exchange against a stand-in push server and registry: the connect, the
+ /// token, the filter, the JWT, the registration, then a push named by its topic's SHA-1,
+ /// which comes out as its container and is acknowledged.
+ #[tokio::test]
+ #[allow(clippy::result_large_err)] // tungstenite's own callback signature
+ async fn a_push_arrives_as_its_container_and_is_acknowledged() {
+ use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let server = tokio::spawn(async move {
+ let (tcp, _) = listener.accept().await.unwrap();
+ let mut path = String::new();
+ let mut ws =
+ tokio_tungstenite::accept_hdr_async(tcp, |req: &Request, res: Response| {
+ path = req.uri().path().to_string();
+ Ok(res)
+ })
+ .await
+ .unwrap();
+ let hexed = path.strip_prefix("/v2/").expect("the v2 connect path");
+ let bytes: Vec<u8> = (0..hexed.len())
+ .step_by(2)
+ .map(|i| u8::from_str_radix(&hexed[i..i + 2], 16).unwrap())
+ .collect();
+ let outer = pb::fields(&bytes).unwrap();
+ let v1 = pb::fields(pb::bytes(&outer, 1).unwrap()).unwrap();
+ assert!(pb::bytes(&v1, 5).is_some(), "a new connection is asked for");
+ let mut ok = pb::W::default();
+ ok.string(1, "VE9L").uint(2, 0);
+ let mut reply = pb::W::default();
+ reply.message(1, &ok);
+ ws.send(Message::binary(reply.0)).await.unwrap();
+ let mut got_filter = false;
+ loop {
+ let Some(Ok(Message::Binary(b))) = ws.next().await else {
+ panic!("the client went away");
+ };
+ let m = pb::fields(&b).unwrap();
+ if let Some(filter) = pb::bytes(&m, 3) {
+ let f = pb::fields(filter).unwrap();
+ assert_eq!(f.len(), 2, "both topics");
+ got_filter = true;
+ } else if pb::bytes(&m, 7).is_some() {
+ assert!(got_filter, "filtered before anything else");
+ let mut jwt = pb::W::default();
+ jwt.string(1, "J.W.T").uint(2, 1);
+ let mut reply = pb::W::default();
+ reply.message(8, &jwt);
+ ws.send(Message::binary(reply.0)).await.unwrap();
+ break;
+ }
+ }
+ // A push, named by the SHA-1 of its topic, once the client has registered.
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ let topic = sha1(&topic_of("com.apple.reminders"));
+ let mut push = pb::W::default();
+ push.bytes(1, &topic).uint(2, 7).bytes(
+ 4,
+ br#"{"aps":{"content-available":1},"ck":{"cid":"com.apple.reminders"}}"#,
+ );
+ let mut reply = pb::W::default();
+ reply.message(2, &push);
+ ws.send(Message::binary(reply.0)).await.unwrap();
+ let Some(Ok(Message::Binary(b))) = ws.next().await else {
+ panic!("no acknowledgement");
+ };
+ let m = pb::fields(&b).unwrap();
+ let ack = pb::fields(pb::bytes(&m, 2).expect("an ack")).unwrap();
+ assert_eq!(pb::int(&ack, 2), Some(7));
+ assert_eq!(pb::bytes(&ack, 1), Some(&topic[..]));
+ });
+
+ let registry = wiremock::MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::method("POST"))
+ .and(wiremock::matchers::header("x-pds-client-type", "iCloudCom"))
+ .respond_with(wiremock::ResponseTemplate::new(200).set_body_bytes(vec![0x08, 0x00]))
+ .expect(1)
+ .mount(&registry)
+ .await;
+
+ let mut id = Identity::new();
+ let mut courier = Courier::connect(
+ &format!("ws://{addr}"),
+ &mut id,
+ &["com.apple.notes", "com.apple.reminders"],
+ )
+ .await
+ .unwrap();
+ assert!(id.has_token());
+ courier
+ .register(&reqwest::Client::new(), &registry.uri(), &id, "1")
+ .await
+ .unwrap();
+ let event = courier.next(Duration::from_secs(5)).await.unwrap();
+ assert_eq!(event, Some(Event::Changed("com.apple.reminders".into())));
+ server.await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn only_apple_is_ever_dialled() {
+ let mut id = Identity::new();
+ let got = Courier::connect("example.com", &mut id, &["com.apple.notes"]).await;
+ assert!(matches!(got, Err(Failure::Refused(_))));
+ }
+
+ #[test]
+ fn a_malformed_message_is_refused_not_panicked_on() {
+ assert!(pb::fields(&[0x0a, 0x05, 1]).is_none());
+ assert!(pb::fields(&[0xff]).is_none());
+ assert_eq!(pb::fields(&[]).unwrap().len(), 0);
+ }
+}
diff --git a/crates/quince-icloud/src/lib.rs b/crates/quince-icloud/src/lib.rs
index a939eb3..536813b 100644
--- a/crates/quince-icloud/src/lib.rs
+++ b/crates/quince-icloud/src/lib.rs
@@ -19,6 +19,7 @@ pub mod calendar_feeds;
pub mod ckdocument;
pub mod cloudkit;
pub mod contacts;
+pub mod courier;
pub mod drive;
pub mod markdown;
pub mod mergeable;
@@ -34,17 +35,6 @@ pub mod sync;
pub mod table;
pub mod topotext;
-/// Lets the gated writes (note attachments, reminder details) run for one supervised live
-/// test, from the probe that drives it (`probe/examples/skykeep_live.rs`) against the throwaway
-/// records the founder named. The app never sets it; the gating constants stay as they are.
-#[doc(hidden)]
-pub static SUPERVISED_LIVE_TEST: std::sync::atomic::AtomicBool =
- std::sync::atomic::AtomicBool::new(false);
-
-pub(crate) fn supervised_live_test() -> bool {
- SUPERVISED_LIVE_TEST.load(std::sync::atomic::Ordering::SeqCst)
-}
-
#[derive(Debug, thiserror::Error)]
pub enum Error {
/// Said in words, never with the address: an address carries the account's id and this
diff --git a/crates/quince-icloud/src/notes.rs b/crates/quince-icloud/src/notes.rs
index 589da21..2e9d7c3 100644
--- a/crates/quince-icloud/src/notes.rs
+++ b/crates/quince-icloud/src/notes.rs
@@ -591,44 +591,13 @@ pub async fn edit_rich_cloudkit_from(
.into(),
)
})?;
- let target = match base {
- Some(base) if base != theirs => merge_edits(base, body, &theirs).ok_or_else(|| {
- Error::Refused(
- "This note was changed on another device while you were writing, in the same place. Nothing was saved; your text is still here."
- .into(),
- )
- })?,
- _ => body.to_string(),
+ let Some((target, rewritten)) =
+ rewrite_for_save(encoded, &theirs, base, body, runs, base_runs)?
+ else {
+ // Apple already holds this text, set this way: nothing to write. A save that only
+ // re-reads the note (it was opened, looked at) must never become a write.
+ return Ok(theirs);
};
- let rewritten = match runs {
- Some(runs) => {
- let laid = if target == body { runs.to_vec() } else { crate::ckdocument::carry_runs(body, runs, &target) };
- // Lines not restyled here keep what Apple holds — a tick made on the phone.
- let laid = match (base, base_runs) {
- (Some(base), Some(base_runs)) => crate::ckdocument::keep_their_formatting(
- base,
- base_runs,
- &theirs,
- &crate::ckdocument::runs_from_base64(encoded),
- &target,
- &laid,
- ),
- _ => laid,
- };
- crate::ckdocument::replace_rich_in_base64(encoded, &target, &laid)
- }
- None => crate::ckdocument::replace_text_in_base64(encoded, &target),
- }
- .ok_or_else(|| {
- Error::Refused(
- "Skykeep can’t safely save changes to this note yet, so nothing was changed. Editing it on an Apple device is safe."
- .into(),
- )
- })?;
- fits_inline(&rewritten)?;
- if !crate::ckdocument::attachments_sound_in_base64(encoded, &rewritten) {
- return Err(Error::Refused(ATTACHMENTS_UNSOUND.into()));
- }
let (title, snippet) = title_and_snippet(&target);
let Some(tag) = current.get("recordChangeTag").and_then(Value::as_str) else {
return Err(Error::Refused(
@@ -666,6 +635,169 @@ pub async fn edit_rich_cloudkit_from(
))
}
+/// What a save writes over Apple's document `encoded` (whose text is `theirs`): the text it
+/// ends up holding and the document to write — or `None` when that is exactly what Apple
+/// already holds, text and formatting, so nothing is written at all.
+///
+/// The formatting goes the least invasive way that gives what the editor shows: when Apple's
+/// own runs, carried over the text edit as a text-only edit carries them, already describe the
+/// formatting wanted, only the text is rewritten and every other run keeps Apple's bytes —
+/// how the runs happen to be cut (Apple's come in pieces, the editor's merged) never turns into
+/// a rewrite. Only a real restyle writes runs.
+fn rewrite_for_save(
+ encoded: &str,
+ theirs: &str,
+ base: Option<&str>,
+ body: &str,
+ runs: Option<&[crate::ckdocument::Run]>,
+ base_runs: Option<&[crate::ckdocument::Run]>,
+) -> Result<Option<(String, String)>> {
+ let target = match base {
+ Some(base) if base != theirs => merge_edits(base, body, theirs).ok_or_else(|| {
+ Error::Refused(
+ "This note was changed on another device while you were writing, in the same place. Nothing was saved; your text is still here."
+ .into(),
+ )
+ })?,
+ _ => body.to_string(),
+ };
+ let their_runs = crate::ckdocument::runs_from_base64(encoded);
+ let wanted = runs.map(|runs| {
+ let laid = if target == body {
+ runs.to_vec()
+ } else {
+ crate::ckdocument::carry_runs(body, runs, &target)
+ };
+ // Lines not restyled here keep what Apple holds — a tick made on the phone.
+ match (base, base_runs) {
+ (Some(base), Some(base_runs)) => crate::ckdocument::keep_their_formatting(
+ base,
+ base_runs,
+ theirs,
+ &their_runs,
+ &target,
+ &laid,
+ ),
+ _ => laid,
+ }
+ });
+ if target == theirs
+ && wanted
+ .as_deref()
+ .is_none_or(|w| same_formatting(theirs, w, &their_runs))
+ {
+ return Ok(None);
+ }
+ let text_only = || crate::ckdocument::replace_text_in_base64(encoded, &target);
+ let rewritten = match wanted.as_deref() {
+ None => text_only(),
+ Some(wanted) => match text_only() {
+ Some(doc)
+ if same_formatting(
+ &target,
+ wanted,
+ &crate::ckdocument::runs_from_base64(&doc),
+ ) =>
+ {
+ Some(doc)
+ }
+ _ => crate::ckdocument::replace_rich_in_base64(encoded, &target, wanted),
+ },
+ }
+ .ok_or_else(|| {
+ Error::Refused(
+ "Skykeep can’t safely save changes to this note yet, so nothing was changed. Editing it on an Apple device is safe."
+ .into(),
+ )
+ })?;
+ fits_inline(&rewritten)?;
+ if !crate::ckdocument::attachments_sound_in_base64(encoded, &rewritten) {
+ return Err(Error::Refused(ATTACHMENTS_UNSOUND.into()));
+ }
+ Ok(Some((target, rewritten)))
+}
+
+/// `runs` over `text` in one canonical shape, so two descriptions of the same formatting
+/// compare equal however they are cut: each unit takes its own character attributes and the
+/// paragraph setting of the unit that ends its line (as Apple and the editor both read a
+/// line's setting), a tick only on a checklist line, a list's start only on a numbered one —
+/// then neighbours that differ in nothing but length are one run. An attachment's run is
+/// never joined to anything: each stands for its own character. `None` when the runs do not
+/// describe the text.
+#[must_use]
+pub fn canonical_runs(
+ text: &str,
+ runs: &[crate::ckdocument::Run],
+) -> Option<Vec<crate::ckdocument::Run>> {
+ use crate::ckdocument::Run;
+ let units: Vec<u16> = text.encode_utf16().collect();
+ if runs.iter().map(|r| r.length).sum::<u64>() != units.len() as u64 {
+ return None;
+ }
+ let mut each: Vec<&Run> = Vec::with_capacity(units.len());
+ for r in runs {
+ each.extend(std::iter::repeat_n(r, usize::try_from(r.length).ok()?));
+ }
+ // Where each unit's line ends: its newline, or the text's last unit.
+ let mut ends = vec![0usize; units.len()];
+ let mut end = units.len().saturating_sub(1);
+ for i in (0..units.len()).rev() {
+ if units[i] == u16::from(b'\n') {
+ end = i;
+ }
+ ends[i] = end;
+ }
+ let mut out: Vec<Run> = Vec::new();
+ for (i, own) in each.iter().enumerate() {
+ let line = each[ends[i]];
+ let style = line.style;
+ let unit = Run {
+ length: 1,
+ style,
+ indent: line.indent,
+ checked: (style == Some(103)).then(|| line.checked.unwrap_or(false)),
+ start: line.start.filter(|&n| style == Some(102) && n != 1),
+ quote: line.quote,
+ bold: own.bold,
+ italic: own.italic,
+ underline: own.underline,
+ strike: own.strike,
+ link: own.link.clone().filter(|l| !l.is_empty()),
+ attachment: own.attachment.clone(),
+ emphasis: own.emphasis,
+ };
+ match out.last_mut() {
+ Some(last)
+ if last.attachment.is_none()
+ && unit.attachment.is_none()
+ && *last
+ == Run {
+ length: last.length,
+ ..unit.clone()
+ } =>
+ {
+ last.length += 1;
+ }
+ _ => out.push(unit),
+ }
+ }
+ Some(out)
+}
+
+/// Whether `a` and `b` set `text` the same way: equal once both are in [`canonical_runs`]'s
+/// shape. Runs that do not describe the text are never the same as anything.
+#[must_use]
+pub fn same_formatting(
+ text: &str,
+ a: &[crate::ckdocument::Run],
+ b: &[crate::ckdocument::Run],
+) -> bool {
+ match (canonical_runs(text, a), canonical_runs(text, b)) {
+ (Some(a), Some(b)) => a == b,
+ _ => false,
+ }
+}
+
/// One edit of `base`, character by character: which of its characters it removed, and what
/// it put in each gap between them (gap `i` is just before character `i`).
struct Script {
@@ -1376,6 +1508,219 @@ pub async fn delete_cloudkit(
#[cfg(test)]
mod tests {
use super::*;
+ use crate::ckdocument::Run;
+
+ fn plain(length: u64) -> Run {
+ Run {
+ length,
+ ..Run::default()
+ }
+ }
+
+ fn attached(id: &str) -> Run {
+ Run {
+ attachment: Some(id.into()),
+ ..plain(1)
+ }
+ }
+
+ /// Shaped like his "Attachments" note (text made generic): Apple's runs in pieces — a word
+ /// split in two, a sentence in five — and the editor's, the same formatting merged.
+ #[test]
+ fn runs_cut_differently_are_the_same_formatting() {
+ let text = "Attachments\n\u{FFFC}\n\u{FFFC}\nA few words to try it out \n\u{FFFC}";
+ let apple = vec![
+ plain(10),
+ plain(1),
+ plain(1),
+ attached("A1"),
+ plain(1),
+ attached("A2"),
+ plain(1),
+ plain(2),
+ plain(10),
+ plain(8),
+ plain(5),
+ plain(1),
+ plain(1),
+ attached("A3"),
+ ];
+ let editor = vec![
+ plain(12),
+ attached("A1"),
+ plain(1),
+ attached("A2"),
+ plain(1 + 26 + 1),
+ attached("A3"),
+ ];
+ assert!(same_formatting(text, &apple, &editor));
+ assert_eq!(canonical_runs(text, &apple), canonical_runs(text, &editor));
+ // Bold on one word is a difference; so is an attachment moved or dropped.
+ let mut bold = editor.clone();
+ bold.splice(
+ 4..5,
+ [
+ plain(1),
+ Run {
+ bold: true,
+ ..plain(2)
+ },
+ plain(26),
+ ],
+ );
+ assert!(!same_formatting(text, &apple, &bold));
+ let mut moved = editor.clone();
+ moved[1] = attached("A2");
+ moved[3] = attached("A1");
+ assert!(!same_formatting(text, &apple, &moved));
+ let mut dropped = editor.clone();
+ dropped[1] = plain(1);
+ assert!(!same_formatting(text, &apple, &dropped));
+ // A line's setting is its newline's: a stray style on a character inside it is not one.
+ let stray = vec![
+ Run {
+ style: Some(1),
+ ..plain(5)
+ },
+ plain(5),
+ plain(2),
+ attached("A1"),
+ plain(1),
+ attached("A2"),
+ plain(28),
+ attached("A3"),
+ ];
+ assert!(same_formatting(text, &stray, &editor));
+ // Runs that do not describe the text are never the same as anything.
+ assert!(!same_formatting(text, &editor[..2], &editor[..2]));
+ }
+
+ /// A document as a phone leaves one: a title, pictures each on a line of their own (their
+ /// runs stamped, so Apple's runs come in pieces), a sentence, a last picture.
+ fn fixture() -> String {
+ let mut doc =
+ crate::ckdocument::text_to_base64("Attachments\nA few words to try it out \n");
+ for (i, at) in [12u64, 14, 16].into_iter().enumerate() {
+ doc = crate::ckdocument::insert_attachment_in_base64(
+ &doc,
+ at,
+ &format!("00000000-0000-4000-8000-00000000000{i}"),
+ "public.jpeg",
+ 10 + i as u64,
+ )
+ .expect("placed")
+ .0;
+ }
+ doc
+ }
+
+ /// Opening a note and leaving it — a "save" of exactly what Apple holds, its runs merged as
+ /// the editor merges them — writes nothing.
+ #[test]
+ fn a_save_that_changes_nothing_writes_nothing() {
+ let doc = fixture();
+ let text = crate::ckdocument::stored_text_from_base64(&doc).unwrap();
+ let apple = crate::ckdocument::runs_from_base64(&doc);
+ let editor = canonical_runs(&text, &apple).unwrap();
+ assert_ne!(
+ apple.len(),
+ editor.len(),
+ "the fixture's runs come in pieces"
+ );
+ assert!(
+ rewrite_for_save(&doc, &text, Some(&text), &text, Some(&editor), Some(&apple))
+ .unwrap()
+ .is_none()
+ );
+ assert!(rewrite_for_save(&doc, &text, None, &text, None, None)
+ .unwrap()
+ .is_none());
+ }
+
+ /// A real edit writes the text, and every run it did not touch keeps Apple's bytes: the
+ /// editor's merged runs never re-cut or rewrite the rest of the note.
+ #[test]
+ fn a_real_edit_keeps_every_other_run_byte_for_byte() {
+ let doc = fixture();
+ let text = crate::ckdocument::stored_text_from_base64(&doc).unwrap();
+ let apple = crate::ckdocument::runs_from_base64(&doc);
+ let editor = canonical_runs(&text, &apple).unwrap();
+ let at = text.find("out ").unwrap() + 3;
+ let typed = format!("{}!{}", &text[..at], &text[at..]);
+ let mine = crate::ckdocument::carry_runs(&text, &editor, &typed);
+ let (kept, written) =
+ rewrite_for_save(&doc, &text, Some(&text), &typed, Some(&mine), Some(&apple))
+ .unwrap()
+ .expect("an edit is written");
+ assert_eq!(kept, typed);
+ let raw = |d: &str| {
+ use base64::Engine;
+ crate::ckdocument::debug_attribute_runs(
+ &base64::engine::general_purpose::STANDARD.decode(d).unwrap(),
+ )
+ };
+ let (before, after) = (raw(&doc), raw(&written));
+ assert_eq!(before.len(), after.len(), "the runs were re-cut");
+ let changed: Vec<usize> = (0..before.len())
+ .filter(|&i| before[i] != after[i])
+ .collect();
+ assert_eq!(
+ changed.len(),
+ 1,
+ "only the run typed into changes: {changed:?}"
+ );
+ let i = changed[0];
+ assert_eq!(
+ crate::ckdocument::debug_run_length(&after[i]),
+ crate::ckdocument::debug_run_length(&before[i]) + 1
+ );
+ assert!(same_formatting(
+ &typed,
+ &crate::ckdocument::runs_from_base64(&written),
+ &mine
+ ));
+ // What the save wrote before: the editor's runs laid over the whole note, which re-cut
+ // and re-encoded runs nobody touched.
+ let old = crate::ckdocument::replace_rich_in_base64(&doc, &typed, &mine).unwrap();
+ let old = raw(&old);
+ assert!(
+ old.len() != before.len()
+ || (0..before.len()).filter(|&i| before[i] != old[i]).count() > 1,
+ "the old path rewrote only the edited run; this test would not catch the bug"
+ );
+ }
+
+ /// A restyle is written — and the lines it did not touch still read as Apple set them.
+ #[test]
+ fn a_restyle_is_written() {
+ let doc = fixture();
+ let text = crate::ckdocument::stored_text_from_base64(&doc).unwrap();
+ let apple = crate::ckdocument::runs_from_base64(&doc);
+ let mut mine = canonical_runs(&text, &apple).unwrap();
+ // The title made a title.
+ let first = mine[0].clone();
+ mine.splice(
+ 0..1,
+ [
+ Run {
+ length: 12,
+ style: Some(0),
+ ..first.clone()
+ },
+ Run {
+ length: first.length - 12,
+ ..first
+ },
+ ],
+ );
+ let (_, written) =
+ rewrite_for_save(&doc, &text, Some(&text), &text, Some(&mine), Some(&apple))
+ .unwrap()
+ .expect("a restyle is written");
+ let read = crate::ckdocument::runs_from_base64(&written);
+ assert_eq!(read[0].style, Some(0));
+ assert!(same_formatting(&text, &read, &mine));
+ }
/// A table on a note's first line, or a note of nothing but attachments: the title and
/// snippet are its words, never the marks where the attachments sit.
diff --git a/crates/quince-icloud/src/notes_attach.rs b/crates/quince-icloud/src/notes_attach.rs
index 40cf3ef..1c0f830 100644
--- a/crates/quince-icloud/src/notes_attach.rs
+++ b/crates/quince-icloud/src/notes_attach.rs
@@ -27,7 +27,7 @@
//! note is read again, the attachment is placed again — moved along with the other device's
//! edit — and the three are sent again. The file is uploaded once, before any of that.
//!
-//! Off until a supervised live test: see [`NOTE_ATTACH_WRITES`].
+//! Switched on by [`NOTE_ATTACH_WRITES`].
use crate::cloudkit::ZoneClient;
use crate::{Error, Result};
@@ -35,9 +35,10 @@ use base64::{engine::general_purpose::STANDARD as B64, Engine};
use serde::Serialize;
use serde_json::{json, Value};
-/// Whether adding a file to a note may write to iCloud at all. False until the live test on a
-/// throwaway note has been watched end to end on a phone.
-pub const NOTE_ATTACH_WRITES: bool = false;
+/// Whether adding a file to a note may write to iCloud at all. On: a picture added here to a
+/// throwaway note (2026-10-22, supervised, on his account) showed on his iPhone on a line of
+/// its own, the note's other attachments and table untouched, with no conflict copy.
+pub const NOTE_ATTACH_WRITES: bool = true;
const CONTAINER: &str = "com.apple.notes";
const ZONE: &str = "Notes";
@@ -288,8 +289,12 @@ pub fn place_in_document(
}
_ => at,
};
- let document = crate::ckdocument::insert_attachment_in_base64(current, place, id, uti, stamp)
- .ok_or_else(|| {
+ // On a paragraph of its own, as a phone places one: `place` moves to where its character
+ // landed, past the newline put before it when it went in mid-line.
+ let (document, place) = crate::ckdocument::insert_attachment_in_base64(
+ current, place, id, uti, stamp,
+ )
+ .ok_or_else(|| {
Error::Refused(
"Skykeep can’t safely add a file to this note yet, so nothing was changed.".into(),
)
@@ -425,7 +430,7 @@ pub async fn attach_file_cloudkit(
base: Option<&str>,
at: u64,
) -> Result<Attached> {
- if !NOTE_ATTACH_WRITES && !crate::supervised_live_test() {
+ if !NOTE_ATTACH_WRITES {
return Err(Error::Refused(
"Adding files to notes isn’t switched on yet. Nothing was changed.".into(),
));
@@ -717,9 +722,9 @@ mod tests {
const ID: &str = "11111111-2222-3333-4444-555555555555";
- /// The document change on a synthetic note: one U+FFFC where asked, a run of its own
- /// naming the attachment, the guard satisfied — and the place carried across a phone's
- /// edit made meanwhile.
+ /// The document change on a synthetic note: one U+FFFC where asked, on a paragraph of its
+ /// own as a phone puts one, a run of its own naming the attachment, the guard satisfied —
+ /// and the place carried across a phone's edit made meanwhile.
#[test]
fn the_attachment_lands_where_asked_even_after_an_edit_elsewhere() {
let original = crate::ckdocument::text_to_base64("Shopping\nmilk\n");
@@ -727,7 +732,7 @@ mod tests {
assert_eq!(at, 9);
assert_eq!(
crate::ckdocument::stored_text_from_base64(&doc).unwrap(),
- "Shopping\n\u{FFFC}milk\n"
+ "Shopping\n\u{FFFC}\nmilk\n"
);
let runs = crate::ckdocument::runs_from_base64(&doc);
let mut from = 0;
@@ -739,7 +744,7 @@ mod tests {
})
.collect();
assert_eq!(mine, [(ID, 9, 1)]);
- assert_eq!(runs.iter().map(|r| r.length).sum::<u64>(), 15);
+ assert_eq!(runs.iter().map(|r| r.length).sum::<u64>(), 16);
assert!(crate::ckdocument::attachments_sound_adding_in_base64(
&original, &doc, ID
));
@@ -750,7 +755,7 @@ mod tests {
));
// Once written, editing that note again is an ordinary, sound edit.
let edited =
- crate::ckdocument::replace_text_in_base64(&doc, "Shopping!\n\u{FFFC}milk\n").unwrap();
+ crate::ckdocument::replace_text_in_base64(&doc, "Shopping!\n\u{FFFC}\nmilk\n").unwrap();
assert!(crate::ckdocument::attachments_sound_in_base64(
&doc, &edited
));
@@ -763,7 +768,7 @@ mod tests {
assert_eq!(at, 15);
assert_eq!(
crate::ckdocument::stored_text_from_base64(&doc).unwrap(),
- "Today\nShopping\n\u{FFFC}milk\n"
+ "Today\nShopping\n\u{FFFC}\nmilk\n"
);
}
@@ -779,10 +784,11 @@ mod tests {
assert!(place_in_document(&doc, None, 0, ID, "public.png", 1).is_err());
}
- /// The paragraph a picture lands in keeps its setting: in a checklist line, the
- /// attachment's run carries that line's checklist item, as the phone's did.
+ /// A picture goes on a paragraph of its own, as a phone puts one: mid-line it splits the
+ /// line, at a line's end it goes on the line below, and the line it came from keeps its
+ /// setting — a checklist item stays one, and the picture is not made one.
#[test]
- fn the_attachment_takes_its_paragraphs_setting() {
+ fn the_attachment_gets_a_paragraph_of_its_own() {
use crate::ckdocument::ParagraphChange;
let plain = crate::ckdocument::text_to_base64("todo\nbuy\n");
let listed = crate::ckdocument::set_paragraph_in_base64(
@@ -792,11 +798,40 @@ mod tests {
Some("buy"),
)
.unwrap();
- let (doc, _) = place_in_document(&listed, None, 8, ID, "public.png", 1).unwrap();
+ // At the end of "buy": below it, as the note's last line.
+ let (doc, at) = place_in_document(&listed, None, 8, ID, "public.png", 1).unwrap();
+ assert_eq!(at, 9);
+ assert_eq!(
+ crate::ckdocument::stored_text_from_base64(&doc).unwrap(),
+ "todo\nbuy\n\u{FFFC}"
+ );
let runs = crate::ckdocument::runs_from_base64(&doc);
let pic = runs.iter().find(|r| r.attachment.is_some()).unwrap();
- assert_eq!(pic.style, Some(103));
+ assert_eq!(pic.style, None);
+ assert_eq!(pic.checked, None);
+ let mut from = 0;
+ let buy: Vec<_> = runs
+ .iter()
+ .filter(|r| {
+ from += r.length;
+ from > 5 && from <= 9
+ })
+ .collect();
+ assert!(buy.iter().all(|r| r.style == Some(103)));
assert_eq!(runs.iter().map(|r| r.length).sum::<u64>(), 10);
+
+ // Mid-line: the line is split around it.
+ let (doc, at) = place_in_document(&listed, None, 2, ID, "public.png", 1).unwrap();
+ assert_eq!(at, 3);
+ assert_eq!(
+ crate::ckdocument::stored_text_from_base64(&doc).unwrap(),
+ "to\n\u{FFFC}\ndo\nbuy\n"
+ );
+ let runs = crate::ckdocument::runs_from_base64(&doc);
+ assert_eq!(runs.iter().map(|r| r.length).sum::<u64>(), 12);
+ assert!(crate::ckdocument::attachments_sound_adding_in_base64(
+ &listed, &doc, ID
+ ));
}
fn modify_ok() -> ResponseTemplate {
@@ -882,7 +917,7 @@ mod tests {
let done = attach_file_unguarded(&http, &server.uri(), vec![], "N", &file, Some("a\nb"), 2)
.await
.unwrap();
- assert_eq!(done.body, "zz\na\n\u{FFFC}b");
+ assert_eq!(done.body, "zz\na\n\u{FFFC}\nb");
assert_eq!(done.offset, 5);
let sent = server.received_requests().await.unwrap();
diff --git a/crates/quince-icloud/src/push.rs b/crates/quince-icloud/src/push.rs
index d40fd6d..f8979bc 100644
--- a/crates/quince-icloud/src/push.rs
+++ b/crates/quince-icloud/src/push.rs
@@ -1,7 +1,10 @@
-//! CloudKit's push channel: how a change made on a phone reaches this computer in about a
-//! second, rather than at the next timed pass.
+//! CloudKit's push channel, as it was, and the cheap "has anything changed" check that stands in
+//! for it when no live channel can be had.
//!
-//! As icloud.com's CloudKit JS does it, measured against the real service:
+//! **Retired by Apple (measured 2026-10-22):** `tokens/create` below now answers
+//! `403 ACCESS_DENIED, "This endpoint is deprecated."`. icloud.com moved to the web push
+//! socket, which `crate::courier` speaks; `open` and `wait` stay only for the probes that
+//! measured the old path. What it was, as icloud.com's CloudKit JS did it:
//!
//! - `POST {ckdevice}/device/1/<container>/production/tokens/create` with
//! `{apnsEnvironment: "production", clientId}` answers `{apnsToken, webcourierURL}`.
@@ -128,6 +131,59 @@ pub async fn wait(
Ok(container_of(&body))
}
+/// Whether a container's private database moved since `token`: one
+/// `changes/database` call, a few hundred bytes, read-only. Returns whether any zone changed
+/// and the token to ask from next time. With no token it only seeds one — the zones it lists
+/// are everything there is, not a change.
+pub async fn database_changed(
+ http: &reqwest::Client,
+ ckdatabasews_root: &str,
+ params: &[(String, String)],
+ container: &str,
+ token: Option<&str>,
+) -> Result<(bool, Option<String>)> {
+ let url = format!(
+ "{}/database/1/{container}/production/private/changes/database",
+ ckdatabasews_root.trim_end_matches('/')
+ );
+ let mut body = json!({});
+ if let Some(t) = token.filter(|t| !t.is_empty()) {
+ body["syncToken"] = Value::String(t.to_string());
+ }
+ let response = http
+ .post(url)
+ .query(&query(params))
+ .json(&body)
+ .send()
+ .await?;
+ let status = response.status();
+ if matches!(status.as_u16(), 401 | 421 | 450) {
+ return Err(Error::ReauthRequired);
+ }
+ let text = response.text().await.unwrap_or_default();
+ if !status.is_success() {
+ // An expired or unreadable token is started over, not reported.
+ if text.contains("CHANGE_TOKEN_EXPIRED") || status.as_u16() == 400 && token.is_some() {
+ return Err(Error::StaleCursor);
+ }
+ return Err(Error::Protocol(format!(
+ "changes/database answered {status}"
+ )));
+ }
+ let body: Value = serde_json::from_str(&text)
+ .map_err(|e| Error::Protocol(format!("changes/database sent invalid JSON: {e}")))?;
+ let next = body
+ .get("syncToken")
+ .and_then(Value::as_str)
+ .map(str::to_string);
+ let zones = body
+ .get("zones")
+ .and_then(Value::as_array)
+ .is_some_and(|z| !z.is_empty());
+ let moved = token.is_some() && (zones || body.get("moreComing") == Some(&Value::Bool(true)));
+ Ok((moved, next.or_else(|| token.map(str::to_string))))
+}
+
/// Which container a push is about.
#[must_use]
pub fn container_of(push: &Value) -> Option<String> {
@@ -208,6 +264,52 @@ mod tests {
assert_eq!(got.as_deref(), Some("com.apple.reminders"));
}
+ #[tokio::test]
+ async fn the_first_database_check_seeds_and_later_ones_report_moves() {
+ let server = MockServer::start().await;
+ let path_ = "/database/1/com.apple.notes/production/private/changes/database";
+ Mock::given(method("POST"))
+ .and(path(path_))
+ .and(wiremock::matchers::body_json(json!({})))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({
+ "syncToken": "S1", "zones": [{"zoneID": {"zoneName": "Notes"}}], "moreComing": false
+ })))
+ .mount(&server)
+ .await;
+ Mock::given(method("POST"))
+ .and(path(path_))
+ .and(wiremock::matchers::body_json(json!({"syncToken": "S1"})))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({
+ "syncToken": "S1", "zones": [], "moreComing": false
+ })))
+ .mount(&server)
+ .await;
+ Mock::given(method("POST"))
+ .and(path(path_))
+ .and(wiremock::matchers::body_json(json!({"syncToken": "S2"})))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({
+ "syncToken": "S3", "zones": [{"zoneID": {"zoneName": "Notes"}}]
+ })))
+ .mount(&server)
+ .await;
+ let http = reqwest::Client::new();
+ let root = server.uri();
+ let c = "com.apple.notes";
+ let (moved, t) = database_changed(&http, &root, &[], c, None).await.unwrap();
+ assert!(!moved, "a seed is not a change");
+ assert_eq!(t.as_deref(), Some("S1"));
+ let (moved, t) = database_changed(&http, &root, &[], c, Some("S1"))
+ .await
+ .unwrap();
+ assert!(!moved);
+ assert_eq!(t.as_deref(), Some("S1"));
+ let (moved, t) = database_changed(&http, &root, &[], c, Some("S2"))
+ .await
+ .unwrap();
+ assert!(moved);
+ assert_eq!(t.as_deref(), Some("S3"));
+ }
+
#[tokio::test]
async fn a_wait_that_runs_out_is_nothing_not_a_failure() {
let server = MockServer::start().await;
diff --git a/crates/quince-icloud/src/reminders.rs b/crates/quince-icloud/src/reminders.rs
index 130fcee..39fe2f4 100644
--- a/crates/quince-icloud/src/reminders.rs
+++ b/crates/quince-icloud/src/reminders.rs
@@ -395,6 +395,10 @@ use crate::cloudkit::{field, ZoneClient};
#[path = "reminders_details.rs"]
pub mod details;
+/// The rest of the Details screen: the repeat whole, time zone, Urgent, a place, a person.
+#[path = "reminders_more.rs"]
+pub mod more;
+
const CONTAINER: &str = "com.apple.reminders";
const ZONE: &str = "Reminders";
@@ -831,6 +835,9 @@ fn apply_cloudkit_whole(
whole: !incremental,
..Default::default()
};
+ // Repeat rules and place triggers, kept whole beside their reminders.
+ let mut parts: Vec<quince_core::reminders::ReminderPart> = Vec::new();
+ let mut gone_parts: Vec<String> = Vec::new();
for record in &records {
let Some(name) = field::record_name(record) else {
@@ -851,6 +858,7 @@ fn apply_cloudkit_whole(
if removed {
gone_reminders.push(name.clone());
gone_sections.push(name.clone());
+ gone_parts.push(name.clone());
gone_alarms.push(name.clone());
details.gone.push(name.clone());
gone_lists.push(name);
@@ -930,11 +938,21 @@ fn apply_cloudkit_whole(
(false, Some(alarm)) => alarms.push(alarm),
_ => gone_alarms.push(name),
},
- "AlarmTrigger" => match (removed, trigger_from_record(record)) {
- (false, Some(trigger)) => triggers.push(trigger),
- _ => gone_alarms.push(name),
- },
+ "AlarmTrigger" => {
+ match (removed, more::part_from_record(record)) {
+ (false, Some(part)) => parts.push(part),
+ _ => gone_parts.push(name.clone()),
+ }
+ match (removed, trigger_from_record(record)) {
+ (false, Some(trigger)) => triggers.push(trigger),
+ _ => gone_alarms.push(name),
+ }
+ }
"RecurrenceRule" => {
+ match (removed, more::part_from_record(record)) {
+ (false, Some(part)) => parts.push(part),
+ _ => gone_parts.push(name.clone()),
+ }
if !removed {
if let Some(target) = field::reference(record, "Reminder") {
let frequency = field::int(record, "Frequency").unwrap_or(0);
@@ -1070,6 +1088,7 @@ fn apply_cloudkit_whole(
library.set_reminder_repeat(target, *frequency, *interval)?;
}
library.put_alarms(&alarms, &triggers, &gone_alarms, !incremental)?;
+ library.put_reminder_parts(&parts, &gone_parts, !incremental)?;
if !gone_reminders.is_empty() || !gone_lists.is_empty() {
library.forget_reminders(&gone_reminders, &gone_lists)?;
}
@@ -1373,16 +1392,45 @@ async fn place_in_list(
Ok(())
}
-/// How often a reminder comes back.
+/// How often a reminder comes back, and until when.
///
-/// Apple's frequency is 0 daily, 1 weekly, 2 monthly, 3 yearly — the same numbering the
-/// stored rule uses, so nothing is translated between here and the wire.
+/// Apple's frequency is 0 daily, 1 weekly, 2 monthly, 3 yearly, 4 hourly — the same
+/// numbering the stored rule uses, so nothing is translated between here and the wire. The
+/// phone's presets are these with an interval: Biweekly is weekly every 2, Every 3 Months is
+/// monthly every 3.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub struct Repeat {
pub frequency: i64,
pub interval: i64,
}
+/// A `RecurrenceRule` record's fields, as the iPhone writes one: the five numbers every rule
+/// on a real account carries, `EndDate` only when the repeat ends, and the reminder it
+/// governs. Nothing else — a field Apple did not write is not invented here.
+fn rule_fields(repeat: &Repeat, end_at: Option<i64>, days: &[i64], reminder: Value) -> Value {
+ let mut fields = serde_json::json!({
+ "Frequency": { "type": "NUMBER_INT64", "value": repeat.frequency },
+ "Interval": { "type": "NUMBER_INT64", "value": repeat.interval.clamp(1, 1_000) },
+ "FirstDayOfTheWeek": { "type": "NUMBER_INT64", "value": 0 },
+ "OccurrenceCount": { "type": "NUMBER_INT64", "value": 0 },
+ "Imported": { "type": "NUMBER_INT64", "value": 0 },
+ "Deleted": { "type": "NUMBER_INT64", "value": 0 },
+ "Reminder": reminder,
+ });
+ // Weekdays, Weekends or days chosen in Custom: a weekly rule's `DaysOfTheWeek`, BYTES.
+ if repeat.frequency == 1 && !days.is_empty() {
+ fields["DaysOfTheWeek"] = serde_json::json!({
+ "type": "BYTES",
+ "value": quince_core::reminders::days_of_week_to(days),
+ });
+ }
+ if let Some(end) = end_at {
+ fields["EndDate"] =
+ serde_json::json!({ "type": "TIMESTAMP", "value": end.saturating_mul(1000) });
+ }
+ fields
+}
+
/// Set or clear a reminder's repeat.
///
/// A repeat is not a field on the reminder: it is its own record pointing back at the
@@ -1396,6 +1444,21 @@ pub async fn set_recurrence_cloudkit(
params: Vec<(String, String)>,
reminder: &Reminder,
repeat: Option<Repeat>,
+) -> Result<()> {
+ set_repeat_until_cloudkit(http, ckdatabasews_root, params, reminder, repeat, None, &[]).await
+}
+
+/// [`set_recurrence_cloudkit`] with the phone's End Repeat — `end_at` (seconds) ends it on that
+/// date, `None` repeats for ever — and, for a weekly repeat, the weekdays it falls on (1 Sunday
+/// … 7 Saturday; Weekdays is 2–6, Weekends 1 and 7), empty for its due date's day.
+pub async fn set_repeat_until_cloudkit(
+ http: &reqwest::Client,
+ ckdatabasews_root: &str,
+ params: Vec<(String, String)>,
+ reminder: &Reminder,
+ repeat: Option<Repeat>,
+ end_at: Option<i64>,
+ days: &[i64],
) -> Result<()> {
// Apple will not schedule a repeat with nothing to repeat from, and a reminder that
// repeats from no date would simply never come back.
@@ -1426,9 +1489,14 @@ pub async fn set_recurrence_cloudkit(
let wanted: Vec<String> = match repeat {
None => Vec::new(),
Some(repeat) => {
- if !(0..=3).contains(&repeat.frequency) {
+ if !(0..=more::MOST_FREQUENCY).contains(&repeat.frequency) {
return Err(Error::Protocol("that is not a repeat Apple knows".into()));
}
+ if end_at.is_some_and(|end| reminder.due_at.is_some_and(|due| end < due)) {
+ return Err(Error::Protocol(
+ "choose an end date on or after the day it is due".into(),
+ ));
+ }
// The list holds the bare id; the record is named with a prefix. Apple's own
// records are written that way, and a mismatch leaves a rule nothing points at.
let id = uuid::Uuid::new_v4().to_string().to_uppercase();
@@ -1437,15 +1505,12 @@ pub async fn set_recurrence_cloudkit(
ZONE,
&format!("RecurrenceRule/{id}"),
"RecurrenceRule",
- serde_json::json!({
- "Frequency": { "type": "NUMBER_INT64", "value": repeat.frequency },
- "Interval": { "type": "NUMBER_INT64", "value": repeat.interval.clamp(1, 1_000) },
- "FirstDayOfTheWeek": { "type": "NUMBER_INT64", "value": 0 },
- "OccurrenceCount": { "type": "NUMBER_INT64", "value": 0 },
- "Imported": { "type": "NUMBER_INT64", "value": 0 },
- "Deleted": { "type": "NUMBER_INT64", "value": 0 },
- "Reminder": client.reference_to(ZONE, &reminder.guid),
- }),
+ rule_fields(
+ &repeat,
+ end_at,
+ days,
+ client.reference_to(ZONE, &reminder.guid),
+ ),
)
.await?;
vec![id]
@@ -1664,7 +1729,9 @@ async fn edit_once(
"AllDay".into(),
serde_json::json!({ "type": "NUMBER_INT64", "value": i64::from(all_day) }),
);
- if due.is_some() && !all_day {
+ // A reminder already kept in a zone keeps it, as the phone does when its time is
+ // changed: the field is left out, so Apple's copy stays exactly as it was.
+ if due.is_some() && !all_day && reminder.timezone.is_none() {
let zone = jiff::tz::TimeZone::system();
fields.insert(
"TimeZone".into(),
@@ -2086,6 +2153,29 @@ pub async fn set_completed_cloudkit(
} else {
format!("RecurrenceRule/{rule}")
};
+ // The last tick of a repeat that ends (End Repeat On Date): the phone completes it
+ // rather than moving it past its end. Read from Apple's rule as it is now, and from
+ // when it is due at Apple now.
+ let rule_now = client.lookup_record(ZONE, &rule).await?;
+ let end = rule_now
+ .as_ref()
+ .and_then(|r| field::timestamp_seconds(r, "EndDate"));
+ let days = rule_now
+ .as_ref()
+ .and_then(|r| field::string(r, "DaysOfTheWeek"))
+ .and_then(|b| quince_core::reminders::days_of_week_from(&b))
+ .unwrap_or_default();
+ let mut at_apple = reminder.clone();
+ at_apple.due_at = field::timestamp_seconds(&current, "DueDate").or(reminder.due_at);
+ if at_apple.tick_ends_series_on(end, &days, now_millis() / 1000) {
+ return complete_once(
+ &client,
+ reminder,
+ current.get("recordChangeTag").and_then(Value::as_str),
+ true,
+ )
+ .await;
+ }
let zone = reminder.timezone.clone().unwrap_or_else(|| {
jiff::tz::TimeZone::system()
.iana_name()
@@ -2114,26 +2204,30 @@ pub async fn set_completed_cloudkit(
return Ok(());
}
+ complete_once(&client, reminder, reminder.etag.as_deref(), done).await
+}
+
+/// Set or clear `Completed` on the reminder itself, with when, as the phone records it.
+async fn complete_once(
+ client: &ZoneClient<'_>,
+ reminder: &Reminder,
+ tag: Option<&str>,
+ done: bool,
+) -> Result<()> {
client
- .update_record_signed(
- ZONE,
- &reminder.guid,
- "Reminder",
- reminder.etag.as_deref(),
- {
- let mut fields = serde_json::json!({
- "Completed": { "value": i64::from(done), "type": "NUMBER_INT64" },
- "LastModifiedDate": { "value": now_millis(), "type": "TIMESTAMP" },
- });
- // When it was ticked, as the phone records it: without it a reminder ticked
- // again here kept the date it was first completed on, everywhere.
- if done {
- fields["CompletionDate"] =
- serde_json::json!({ "value": now_millis(), "type": "TIMESTAMP" });
- }
- fields
- },
- )
+ .update_record_signed(ZONE, &reminder.guid, "Reminder", tag, {
+ let mut fields = serde_json::json!({
+ "Completed": { "value": i64::from(done), "type": "NUMBER_INT64" },
+ "LastModifiedDate": { "value": now_millis(), "type": "TIMESTAMP" },
+ });
+ // When it was ticked, as the phone records it: without it a reminder ticked
+ // again here kept the date it was first completed on, everywhere.
+ if done {
+ fields["CompletionDate"] =
+ serde_json::json!({ "value": now_millis(), "type": "TIMESTAMP" });
+ }
+ fields
+ })
.await?;
Ok(())
}
@@ -5114,3 +5208,527 @@ mod atomic_apply_tests {
assert!(library.conn().is_autocommit());
}
}
+
+/// Writes compared field for field with what the iPhone wrote on the founder's own "Skykeep
+/// Test" reminder (personal text replaced): a write sends only what changed, so every field
+/// Skykeep does not touch — tags, the place, the person, Urgent — stays exactly as the phone
+/// left it.
+#[cfg(test)]
+mod parity_write_tests {
+ use super::*;
+ use serde_json::json;
+ use wiremock::matchers::{method, path_regex};
+ use wiremock::{Mock, MockServer, ResponseTemplate};
+
+ const GUID: &str = "Reminder/B51EAE34-018C-4F06-B97C-130C02E98799";
+
+ /// The phone's record, as `reminders_more` tests hold it, plus the fields every write
+ /// must leave alone.
+ fn phone_record() -> Value {
+ json!({
+ "recordName": GUID,
+ "recordType": "Reminder",
+ "recordChangeTag": "jfv",
+ "fields": {
+ "AlarmIDs": { "type": "STRING_LIST", "value": ["18154128-7CA1-46FA-9AB3-1E597CF2D3DC", "4FB1FED5-72D2-486C-A9F9-4F2123118C4A"] },
+ "AllDay": { "type": "NUMBER_INT64", "value": 0 },
+ "AttachmentIDs": { "type": "STRING_LIST", "value": ["1274F1BE-5C0B-4C15-AB91-0BBF5D252476"] },
+ "Completed": { "type": "NUMBER_INT64", "value": 0 },
+ "ContactHandles": { "isEncrypted": true, "type": "STRING", "value": "{\"emails\":[\"[email protected]\"]}" },
+ "DueDate": { "type": "TIMESTAMP", "value": 1_792_681_200_000_i64 },
+ "Flagged": { "type": "NUMBER_INT64", "value": 1 },
+ "HashtagIDs": { "type": "STRING_LIST", "value": ["E805CCFA-D039-4FC5-ABEB-780FA9B9A3B8"] },
+ "Priority": { "type": "NUMBER_INT64", "value": 5 },
+ "RecurrenceRuleIDs": { "type": "STRING_LIST", "value": ["049EF968-7FAE-4585-94FB-E22D108B537D"] },
+ "TimeZone": { "type": "STRING", "value": "America/New_York" },
+ "TitleDocument": { "type": "ENCRYPTED_BYTES", "value": crate::ckdocument::text_to_base64("Test") },
+ "UrgentPresentationAlarmsChecksum": { "isEncrypted": true, "type": "STRING", "value": "ddfd7f9a" }
+ }
+ })
+ }
+
+ fn reminder() -> Reminder {
+ Reminder {
+ guid: GUID.into(),
+ list_guid: "List/FED5023E-668F-4670-89CB-2B7765A41F53".into(),
+ title: "Test".into(),
+ notes: None,
+ due_at: Some(1_792_681_200),
+ completed_at: None,
+ priority: 5,
+ parent_guid: None,
+ flagged: true,
+ recur_frequency: Some(0),
+ recur_interval: Some(1),
+ etag: Some("jfv".into()),
+ raw: Some(phone_record().to_string()),
+ timezone: Some("America/New_York".into()),
+ section_guid: None,
+ all_day: false,
+ }
+ }
+
+ async fn phone() -> MockServer {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path_regex(r".*/records/lookup$"))
+ .respond_with(
+ ResponseTemplate::new(200).set_body_json(json!({ "records": [phone_record()] })),
+ )
+ .mount(&server)
+ .await;
+ Mock::given(method("POST"))
+ .and(path_regex(r".*/records/modify$"))
+ .respond_with(
+ ResponseTemplate::new(200)
+ .set_body_json(json!({ "records": [{ "recordName": GUID }] })),
+ )
+ .mount(&server)
+ .await;
+ server
+ }
+
+ async fn operations(server: &MockServer) -> Vec<Value> {
+ server
+ .received_requests()
+ .await
+ .unwrap()
+ .iter()
+ .filter(|r| r.url.path().ends_with("/records/modify"))
+ .map(|r| serde_json::from_slice::<Value>(&r.body).unwrap()["operations"][0].clone())
+ .collect()
+ }
+
+ fn keys(fields: &Value) -> Vec<String> {
+ let mut k: Vec<String> = fields.as_object().unwrap().keys().cloned().collect();
+ k.sort();
+ k
+ }
+
+ /// The phone's daily rule, field for field (less the reminder reference).
+ #[test]
+ fn a_daily_rule_is_the_phones_daily_rule() {
+ let written = rule_fields(
+ &Repeat {
+ frequency: 0,
+ interval: 1,
+ },
+ None,
+ &[],
+ json!("ref"),
+ );
+ let phone = json!({
+ "Deleted": { "type": "NUMBER_INT64", "value": 0 },
+ "FirstDayOfTheWeek": { "type": "NUMBER_INT64", "value": 0 },
+ "Frequency": { "type": "NUMBER_INT64", "value": 0 },
+ "Imported": { "type": "NUMBER_INT64", "value": 0 },
+ "Interval": { "type": "NUMBER_INT64", "value": 1 },
+ "OccurrenceCount": { "type": "NUMBER_INT64", "value": 0 },
+ "Reminder": "ref"
+ });
+ assert_eq!(written, phone);
+ }
+
+ /// Hourly ending on a date, as the phone wrote one: frequency 4 and a TIMESTAMP end.
+ #[test]
+ fn an_hourly_rule_ending_on_a_date_is_the_phones() {
+ let written = rule_fields(
+ &Repeat {
+ frequency: 4,
+ interval: 1,
+ },
+ Some(1_791_557_520),
+ &[],
+ json!("ref"),
+ );
+ assert_eq!(written["Frequency"]["value"], 4);
+ assert_eq!(
+ written["EndDate"],
+ json!({ "type": "TIMESTAMP", "value": 1_791_557_520_000_i64 })
+ );
+ assert_eq!(
+ keys(&written),
+ [
+ "Deleted",
+ "EndDate",
+ "FirstDayOfTheWeek",
+ "Frequency",
+ "Imported",
+ "Interval",
+ "OccurrenceCount",
+ "Reminder"
+ ]
+ );
+ }
+
+ /// "Repeating 1" as the phone wrote it — Weekdays, ending on a date — field for field.
+ #[test]
+ fn weekdays_ending_on_a_date_is_the_phones_rule() {
+ let written = rule_fields(
+ &Repeat {
+ frequency: 1,
+ interval: 1,
+ },
+ Some(1_792_656_031),
+ &[2, 3, 4, 5, 6],
+ json!("ref"),
+ );
+ let phone = json!({
+ "DaysOfTheWeek": { "type": "BYTES", "value": "W3siZGF5T2ZUaGVXZWVrIjoyLCJ3ZWVrTnVtYmVyIjowfSx7ImRheU9mVGhlV2VlayI6Mywid2Vla051bWJlciI6MH0seyJkYXlPZlRoZVdlZWsiOjQsIndlZWtOdW1iZXIiOjB9LHsiZGF5T2ZUaGVXZWVrIjo1LCJ3ZWVrTnVtYmVyIjowfSx7ImRheU9mVGhlV2VlayI6Niwid2Vla051bWJlciI6MH1d" },
+ "Deleted": { "type": "NUMBER_INT64", "value": 0 },
+ "EndDate": { "type": "TIMESTAMP", "value": 1_792_656_031_000_i64 },
+ "FirstDayOfTheWeek": { "type": "NUMBER_INT64", "value": 0 },
+ "Frequency": { "type": "NUMBER_INT64", "value": 1 },
+ "Imported": { "type": "NUMBER_INT64", "value": 0 },
+ "Interval": { "type": "NUMBER_INT64", "value": 1 },
+ "OccurrenceCount": { "type": "NUMBER_INT64", "value": 0 },
+ "Reminder": "ref"
+ });
+ assert_eq!(written, phone);
+ }
+
+ /// "Rep 4" — Weekends — and the plain presets ("Rep 5" weekly, "Rep 6" biweekly, "Rep 7"
+ /// monthly, "Repeating a" hourly) carry no days.
+ #[test]
+ fn weekends_and_plain_presets_are_the_phones_rules() {
+ let weekends = rule_fields(
+ &Repeat {
+ frequency: 1,
+ interval: 1,
+ },
+ None,
+ &[1, 7],
+ json!("ref"),
+ );
+ assert_eq!(
+ weekends["DaysOfTheWeek"]["value"],
+ "W3siZGF5T2ZUaGVXZWVrIjoxLCJ3ZWVrTnVtYmVyIjowfSx7ImRheU9mVGhlV2VlayI6Nywid2Vla051bWJlciI6MH1d"
+ );
+ for (f, i) in [(1, 1), (1, 2), (2, 1), (4, 1)] {
+ let w = rule_fields(
+ &Repeat {
+ frequency: f,
+ interval: i,
+ },
+ None,
+ &[],
+ json!("ref"),
+ );
+ assert!(w.get("DaysOfTheWeek").is_none());
+ assert_eq!(
+ keys(&w),
+ [
+ "Deleted",
+ "FirstDayOfTheWeek",
+ "Frequency",
+ "Imported",
+ "Interval",
+ "OccurrenceCount",
+ "Reminder"
+ ]
+ );
+ }
+ // Days only mean something weekly; anything else is written without them.
+ let monthly = rule_fields(
+ &Repeat {
+ frequency: 2,
+ interval: 1,
+ },
+ None,
+ &[2],
+ json!("ref"),
+ );
+ assert!(monthly.get("DaysOfTheWeek").is_none());
+ }
+
+ /// The phone's presets are frequency and interval: Biweekly, Every 3 and 6 Months.
+ #[test]
+ fn presets_are_a_frequency_and_an_interval() {
+ for (frequency, interval) in [(1, 2), (2, 3), (2, 6), (3, 1)] {
+ let w = rule_fields(
+ &Repeat {
+ frequency,
+ interval,
+ },
+ None,
+ &[],
+ json!("ref"),
+ );
+ assert_eq!(
+ (
+ w["Frequency"]["value"].as_i64(),
+ w["Interval"]["value"].as_i64()
+ ),
+ (Some(frequency), Some(interval))
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn repeating_hourly_until_a_date_writes_the_rule_and_only_relinks_the_reminder() {
+ let server = phone().await;
+ set_repeat_until_cloudkit(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &reminder(),
+ Some(Repeat {
+ frequency: 4,
+ interval: 1,
+ }),
+ Some(1_792_900_000),
+ &[],
+ )
+ .await
+ .unwrap();
+ let ops = operations(&server).await;
+ assert_eq!(ops[0]["record"]["recordType"], "RecurrenceRule");
+ assert_eq!(ops[0]["record"]["fields"]["Frequency"]["value"], 4);
+ assert_eq!(
+ ops[0]["record"]["fields"]["EndDate"]["value"],
+ 1_792_900_000_000_i64
+ );
+ // The reminder: its rule list and its clock, nothing of the phone's touched.
+ let link = &ops[1]["record"]["fields"];
+ assert_eq!(ops[1]["operationType"], "update");
+ let sent = keys(link);
+ for untouched in [
+ "HashtagIDs",
+ "AlarmIDs",
+ "ContactHandles",
+ "TimeZone",
+ "Flagged",
+ "Priority",
+ "AttachmentIDs",
+ ] {
+ assert!(
+ !sent.contains(&untouched.to_string()),
+ "{untouched} must not be sent: {sent:?}"
+ );
+ }
+ // The old rule is retired only after.
+ assert!(ops[2]["recordName"]
+ .as_str()
+ .or(ops[2]["record"]["recordName"].as_str())
+ .is_some_and(|n| n.contains("049EF968")));
+ }
+
+ #[tokio::test]
+ async fn an_end_before_the_due_date_is_refused_before_anything_is_sent() {
+ let server = phone().await;
+ let refused = set_repeat_until_cloudkit(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &reminder(),
+ Some(Repeat {
+ frequency: 0,
+ interval: 1,
+ }),
+ Some(1_792_000_000),
+ &[],
+ )
+ .await;
+ assert!(refused.is_err());
+ assert!(operations(&server).await.is_empty());
+ }
+
+ #[tokio::test]
+ async fn a_new_time_keeps_new_york_and_sends_only_the_date() {
+ let server = phone().await;
+ edit_cloudkit(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &reminder(),
+ &ReminderEdit {
+ due_at: Some(Some(1_792_684_800)),
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+ let fields = &operations(&server).await[0]["record"]["fields"];
+ assert_eq!(fields["DueDate"]["value"], 1_792_684_800_000_i64);
+ assert!(
+ fields.get("TimeZone").is_none(),
+ "New York stays as the phone set it"
+ );
+ let mut sent = keys(fields);
+ sent.retain(|k| k != "ResolutionTokenMap");
+ assert_eq!(sent, ["AllDay", "DueDate", "LastModifiedDate"]);
+ }
+
+ #[tokio::test]
+ async fn flag_priority_and_completion_send_only_themselves() {
+ let server = phone().await;
+ edit_cloudkit(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &reminder(),
+ &ReminderEdit {
+ flagged: Some(false),
+ priority: Some(9),
+ completed: Some(true),
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+ let fields = &operations(&server).await[0]["record"]["fields"];
+ assert_eq!(fields["Flagged"]["value"], 0);
+ assert_eq!(fields["Priority"]["value"], 9, "Low, on Apple's scale");
+ assert_eq!(fields["Completed"]["value"], 1);
+ let mut sent = keys(fields);
+ sent.retain(|k| k != "ResolutionTokenMap");
+ assert_eq!(
+ sent,
+ ["Completed", "Flagged", "LastModifiedDate", "Priority"]
+ );
+ }
+
+ #[tokio::test]
+ async fn a_new_title_rewrites_the_phones_document_and_nothing_else() {
+ let server = phone().await;
+ edit_cloudkit(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &reminder(),
+ &ReminderEdit {
+ title: Some("Renamed".into()),
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+ let fields = &operations(&server).await[0]["record"]["fields"];
+ let doc = fields["TitleDocument"]["value"].as_str().unwrap();
+ assert_eq!(
+ crate::ckdocument::text_from_base64(doc).as_deref(),
+ Some("Renamed")
+ );
+ let mut sent = keys(fields);
+ sent.retain(|k| k != "ResolutionTokenMap");
+ assert_eq!(sent, ["LastModifiedDate", "TitleDocument"]);
+ }
+
+ #[tokio::test]
+ async fn a_day_with_no_time_is_all_day_at_utc_midnight() {
+ let server = phone().await;
+ edit_cloudkit(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &reminder(),
+ &ReminderEdit {
+ due_at: Some(Some(1_792_627_200)),
+ all_day: Some(true),
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+ let fields = &operations(&server).await[0]["record"]["fields"];
+ assert_eq!(fields["AllDay"]["value"], 1);
+ assert_eq!(fields["DueDate"]["value"], 1_792_627_200_000_i64);
+ assert!(fields.get("TimeZone").is_none());
+ }
+
+ /// The founder's daily rule, ending on a date, as Apple would answer a lookup of it.
+ async fn ending_phone(end_ms: i64) -> MockServer {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path_regex(r".*/records/lookup$"))
+ .and(wiremock::matchers::body_string_contains("RecurrenceRule/"))
+ .respond_with(
+ ResponseTemplate::new(200).set_body_json(json!({ "records": [{
+ "recordName": "RecurrenceRule/049EF968-7FAE-4585-94FB-E22D108B537D",
+ "recordType": "RecurrenceRule",
+ "recordChangeTag": "r1",
+ "fields": {
+ "Frequency": { "type": "NUMBER_INT64", "value": 0 },
+ "Interval": { "type": "NUMBER_INT64", "value": 1 },
+ "EndDate": { "type": "TIMESTAMP", "value": end_ms }
+ }
+ }] })),
+ )
+ .with_priority(1)
+ .mount(&server)
+ .await;
+ Mock::given(method("POST"))
+ .and(path_regex(r".*/records/lookup$"))
+ .respond_with(
+ ResponseTemplate::new(200).set_body_json(json!({ "records": [phone_record()] })),
+ )
+ .mount(&server)
+ .await;
+ Mock::given(method("POST"))
+ .and(path_regex(r".*/records/(modify|query)$"))
+ .respond_with(
+ ResponseTemplate::new(200)
+ .set_body_json(json!({ "records": [{ "recordName": GUID }] })),
+ )
+ .mount(&server)
+ .await;
+ server
+ }
+
+ async fn paths(server: &MockServer) -> Vec<String> {
+ server
+ .received_requests()
+ .await
+ .unwrap()
+ .iter()
+ .map(|r| r.url.path().rsplit('/').next().unwrap_or("").to_string())
+ .filter(|p| p != "lookup")
+ .collect()
+ }
+
+ /// Past End Repeat there is no next one: ticked, it is completed on the record, as the
+ /// phone completes it — not sent to Apple to be moved past its end.
+ #[tokio::test]
+ async fn the_last_tick_before_end_repeat_completes_it() {
+ // Due 22 Oct 15:00 UTC; ends that evening — tomorrow's is past it. (The tick is made
+ // now, after the due date, so the next one counted is after now: still past the end.)
+ let server = ending_phone((1_792_681_200 + 8 * 3600) * 1000).await;
+ set_completed_cloudkit(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &reminder(),
+ true,
+ )
+ .await
+ .unwrap();
+ assert_eq!(paths(&server).await, ["modify"], "completed, not moved on");
+ let fields = &operations(&server).await[0]["record"]["fields"];
+ assert_eq!(fields["Completed"]["value"], 1);
+ assert!(fields.get("CompletionDate").is_some());
+ assert!(
+ fields.get("DueDate").is_none(),
+ "its date stays the last one"
+ );
+ }
+
+ /// With time left before its end, it is moved on by Apple, as every repeat is.
+ #[tokio::test]
+ async fn a_tick_with_time_left_still_moves_on() {
+ let server = ending_phone(4_102_444_800_000).await;
+ set_completed_cloudkit(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &reminder(),
+ true,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ paths(&server).await,
+ ["query"],
+ "CompleteRecurringReminder, as before"
+ );
+ }
+}
diff --git a/crates/quince-icloud/src/reminders_details.rs b/crates/quince-icloud/src/reminders_details.rs
index 61be4c3..8eb8f7d 100644
--- a/crates/quince-icloud/src/reminders_details.rs
+++ b/crates/quince-icloud/src/reminders_details.rs
@@ -37,10 +37,11 @@ use serde_json::{json, Value};
const CONTAINER: &str = "com.apple.reminders";
const ZONE: &str = "Reminders";
-/// Writes of tags, links, early alerts and sections stay off until each has been tried once,
-/// supervised, against a real account and seen to arrive on a phone as written. Until then
-/// every write function refuses before touching the network. Reading is unaffected.
-pub const REMINDER_DETAIL_WRITES: bool = false;
+/// Writes of tags, links, early alerts and sections. On: each was tried once, supervised, on
+/// his account (2026-10-22) and seen on his iPhone as written — a tag added and removed, a
+/// link changed, a 15-minute early alert, a section made, renamed, a reminder moved into it,
+/// and the section removed. While off, every write function refuses before the network.
+pub const REMINDER_DETAIL_WRITES: bool = true;
/// The version Apple writes into each of these JSON blobs, as measured.
const MINIMUM_SUPPORTED_VERSION: i64 = 20_230_430;
@@ -60,7 +61,7 @@ fn gate(enabled: bool) -> Result<()> {
}
fn writes() -> Result<()> {
- gate(REMINDER_DETAIL_WRITES || cfg!(test) || crate::supervised_live_test())
+ gate(REMINDER_DETAIL_WRITES)
}
fn apple_now() -> f64 {
@@ -305,41 +306,48 @@ pub fn early_alert_json(
}
/// The list's membership file with one reminder placed in `section` (a section record name),
-/// or out of every one. Every other entry, and any key Apple added, is kept as it was; the
-/// entry changed carries `modified_on` (Apple's seconds), which is what devices merge by.
+/// or out of every one. Only that reminder's entry is written: every other entry, and every
+/// other byte of the file Apple wrote — its key order, its numbers as Apple formatted them —
+/// is kept exactly ([`splice_memberships`]). The entry changed carries `modified_on` (Apple's
+/// seconds), which is what devices merge by.
pub fn place_in_section(
file: Option<&[u8]>,
reminder_guid: &str,
section: Option<&str>,
modified_on: f64,
) -> Result<Vec<u8>> {
- let mut doc: Value = match file.filter(|b| !b.is_empty()) {
+ let refused = || {
+ Error::Refused(
+ "This list's sections are in a form Skykeep doesn't read, so nothing was moved.".into(),
+ )
+ };
+ let original = file.filter(|b| !b.is_empty());
+ let mut doc: Value = match original {
None => json!({ "minimumSupportedVersion": MINIMUM_SUPPORTED_VERSION, "memberships": [] }),
- Some(bytes) => serde_json::from_slice(bytes).map_err(|_| {
- Error::Refused(
- "This list's sections are in a form Skykeep doesn't read, so nothing was moved."
- .into(),
- )
- })?,
+ Some(bytes) => serde_json::from_slice(bytes).map_err(|_| refused())?,
};
if !doc.is_object() {
- return Err(Error::Refused(
- "This list's sections are in a form Skykeep doesn't read, so nothing was moved.".into(),
- ));
+ return Err(refused());
}
- if !doc.get("memberships").is_some_and(Value::is_array) {
+ if doc.get("memberships").is_some_and(|m| !m.is_array()) {
+ return Err(refused());
+ }
+ if doc.get("memberships").is_none() {
doc["memberships"] = json!([]);
}
let member = bare(reminder_guid).to_string();
let entries = doc["memberships"]
.as_array_mut()
- .expect("made an array above");
+ .expect("checked an array above");
let at = entries.iter().position(|m| {
m.get("memberID")
.and_then(Value::as_str)
.is_some_and(|id| id.eq_ignore_ascii_case(&member))
});
let mut entry = at.map_or_else(|| json!({ "memberID": member }), |i| entries[i].clone());
+ if !entry.is_object() {
+ return Err(refused());
+ }
match section {
Some(s) => entry["groupID"] = json!(bare(s)),
None => {
@@ -350,10 +358,216 @@ pub fn place_in_section(
}
entry["modifiedOn"] = json!(modified_on);
match at {
- Some(i) => entries[i] = entry,
- None => entries.push(entry),
+ Some(i) => entries[i] = entry.clone(),
+ None => entries.push(entry.clone()),
}
- serde_json::to_vec(&doc).map_err(|e| Error::Protocol(e.to_string()))
+ let Some(bytes) = original else {
+ return serde_json::to_vec(&doc).map_err(|e| Error::Protocol(e.to_string()));
+ };
+ let (changed, appended) = match at {
+ Some(i) => (vec![(i, entry)], None),
+ None => (Vec::new(), Some(entry)),
+ };
+ splice_memberships(bytes, &changed, appended.as_ref(), &doc).ok_or_else(refused)
+}
+
+/// Where a membership file's entries sit in its bytes: the `memberships` array's closing
+/// bracket and each entry's span, or no array at all (`None` inside). `None` for a file this
+/// cannot walk exactly.
+struct MembershipSpans {
+ /// Index of the array's `]`, or of the object's closing `}` when there is no array.
+ close: usize,
+ /// Whether the array (or, with no array, the object) already holds something.
+ has_items: bool,
+ array: bool,
+ entries: Vec<(usize, usize)>,
+}
+
+fn json_ws(b: &[u8], mut i: usize) -> usize {
+ while i < b.len() && matches!(b[i], b' ' | b'\t' | b'\n' | b'\r') {
+ i += 1;
+ }
+ i
+}
+
+/// Past the string starting at `i` (its opening quote).
+fn json_string_end(b: &[u8], i: usize) -> Option<usize> {
+ if b.get(i) != Some(&b'"') {
+ return None;
+ }
+ let mut j = i + 1;
+ while j < b.len() {
+ match b[j] {
+ b'\\' => j += 2,
+ b'"' => return Some(j + 1),
+ _ => j += 1,
+ }
+ }
+ None
+}
+
+/// Past the value starting at `i`.
+fn json_value_end(b: &[u8], i: usize) -> Option<usize> {
+ match *b.get(i)? {
+ b'"' => json_string_end(b, i),
+ b'{' | b'[' => {
+ let mut depth = 0usize;
+ let mut j = i;
+ while j < b.len() {
+ match b[j] {
+ b'"' => {
+ j = json_string_end(b, j)?;
+ continue;
+ }
+ b'{' | b'[' => depth += 1,
+ b'}' | b']' => {
+ depth = depth.checked_sub(1)?;
+ if depth == 0 {
+ return Some(j + 1);
+ }
+ }
+ _ => {}
+ }
+ j += 1;
+ }
+ None
+ }
+ _ => {
+ let mut j = i;
+ while j < b.len() && !matches!(b[j], b',' | b'}' | b']' | b' ' | b'\t' | b'\n' | b'\r')
+ {
+ j += 1;
+ }
+ (j > i).then_some(j)
+ }
+ }
+}
+
+fn membership_spans(b: &[u8]) -> Option<MembershipSpans> {
+ let mut i = json_ws(b, 0);
+ if b.get(i) != Some(&b'{') {
+ return None;
+ }
+ i = json_ws(b, i + 1);
+ let mut members = 0usize;
+ loop {
+ if b.get(i) == Some(&b'}') {
+ if json_ws(b, i + 1) != b.len() {
+ return None;
+ }
+ return Some(MembershipSpans {
+ close: i,
+ has_items: members > 0,
+ array: false,
+ entries: Vec::new(),
+ });
+ }
+ if members > 0 {
+ if b.get(i) != Some(&b',') {
+ return None;
+ }
+ i = json_ws(b, i + 1);
+ }
+ let key_end = json_string_end(b, i)?;
+ let key: String = serde_json::from_slice(&b[i..key_end]).ok()?;
+ i = json_ws(b, key_end);
+ if b.get(i) != Some(&b':') {
+ return None;
+ }
+ i = json_ws(b, i + 1);
+ let value_end = json_value_end(b, i)?;
+ if key == "memberships" {
+ if b.get(i) != Some(&b'[') {
+ return None;
+ }
+ let mut entries = Vec::new();
+ let mut j = json_ws(b, i + 1);
+ loop {
+ if b.get(j) == Some(&b']') {
+ if j + 1 != value_end {
+ return None;
+ }
+ let has_items = !entries.is_empty();
+ return Some(MembershipSpans {
+ close: j,
+ has_items,
+ array: true,
+ entries,
+ });
+ }
+ if !entries.is_empty() {
+ if b.get(j) != Some(&b',') {
+ return None;
+ }
+ j = json_ws(b, j + 1);
+ }
+ let end = json_value_end(b, j)?;
+ entries.push((j, end));
+ j = json_ws(b, end);
+ }
+ }
+ members += 1;
+ i = json_ws(b, value_end);
+ }
+}
+
+/// Apple's membership file with only the named entries rewritten (`changed`, by index) and
+/// one appended, every other byte kept exactly. The result must read back as `expected` — the
+/// whole edit made on the parsed file — or nothing is answered, so a file this walks wrongly
+/// is refused rather than written.
+fn splice_memberships(
+ bytes: &[u8],
+ changed: &[(usize, Value)],
+ appended: Option<&Value>,
+ expected: &Value,
+) -> Option<Vec<u8>> {
+ let spans = membership_spans(bytes)?;
+ let parsed: Value = serde_json::from_slice(bytes).ok()?;
+ let count = parsed
+ .get("memberships")
+ .and_then(Value::as_array)
+ .map_or(0, Vec::len);
+ if spans.array && spans.entries.len() != count {
+ return None;
+ }
+ let mut out = Vec::with_capacity(bytes.len() + 128);
+ let mut from = 0usize;
+ let mut changed: Vec<&(usize, Value)> = changed.iter().collect();
+ changed.sort_by_key(|(i, _)| *i);
+ for (i, entry) in changed {
+ let (start, end) = *spans.entries.get(*i)?;
+ out.extend_from_slice(&bytes[from..start]);
+ out.extend(serde_json::to_vec(entry).ok()?);
+ from = end;
+ }
+ if let Some(entry) = appended {
+ let text = serde_json::to_vec(entry).ok()?;
+ if spans.array {
+ match spans.entries.last() {
+ Some(&(_, end)) => {
+ out.extend_from_slice(&bytes[from..end]);
+ out.push(b',');
+ from = end;
+ }
+ None => {
+ out.extend_from_slice(&bytes[from..spans.close]);
+ from = spans.close;
+ }
+ }
+ out.extend(text);
+ } else {
+ out.extend_from_slice(&bytes[from..spans.close]);
+ from = spans.close;
+ if spans.has_items {
+ out.push(b',');
+ }
+ out.extend_from_slice(b"\"memberships\":[");
+ out.extend(text);
+ out.push(b']');
+ }
+ }
+ out.extend_from_slice(&bytes[from..]);
+ (serde_json::from_slice::<Value>(&out).ok()? == *expected).then_some(out)
}
/// The checksum written beside the membership file: SHA-512 of its bytes, in hex.
@@ -490,12 +704,16 @@ pub async fn add_tag_cloudkit(
ZONE,
&guid,
"Hashtag",
+ // As a phone writes one (measured on his account, 2026-10-22): the name encrypted,
+ // as every name a person types into Reminders is, `Type` 0 (a tag a person typed),
+ // `CreationDate`, `Imported` 0. No `ResolutionTokenMap`: Apple's carry none.
json!({
- // Encrypted as every other name a person types into Reminders is (a list's, a
- // section's, a smart list's).
"Name": { "type": "STRING", "value": name, "isEncrypted": true },
"Reminder": zc.reference_to(ZONE, reminder_guid),
+ "Type": { "type": "NUMBER_INT64", "value": 0 },
+ "CreationDate": { "type": "TIMESTAMP", "value": now_millis() },
"Deleted": { "type": "NUMBER_INT64", "value": 0 },
+ "Imported": { "type": "NUMBER_INT64", "value": 0 },
}),
)
.await?;
@@ -536,15 +754,11 @@ pub async fn remove_tag_cloudkit(
without_ids(r, "HashtagIDs", &ids)
})
.await?;
+ // Removed as a phone removes one: the Hashtag record deleted outright. Measured on his
+ // account (2026-10-22): 253 Hashtag tombstones in the zone and not one Hashtag an Apple
+ // device left with `Deleted` 1; a tag only marked `Deleted` 1 still showed on his iPhone.
for guid in &matching {
- zc.update_record(
- ZONE,
- guid,
- "Hashtag",
- None,
- json!({ "Deleted": { "type": "NUMBER_INT64", "value": 1 } }),
- )
- .await?;
+ zc.delete_record(ZONE, guid).await?;
}
Ok(())
}
@@ -568,8 +782,9 @@ pub async fn set_url_cloudkit(
.filter(|a| field::string(a, "Type").as_deref() == Some("URL"))
.filter_map(field::record_name)
.collect();
- let url_field =
- |u: &str| json!({ "type": "ENCRYPTED_BYTES", "value": B64.encode(u.as_bytes()) });
+ // An encrypted STRING, as the phone writes it (measured on his account, 2026-10-22: a
+ // URL attachment made on an iPhone). Bytes here would not be the field Apple reads.
+ let url_field = |u: &str| json!({ "type": "STRING", "value": u, "isEncrypted": true });
match (url, existing.first()) {
(Some(u), Some(guid)) => {
zc.update_record(
@@ -706,7 +921,10 @@ pub async fn create_section_cloudkit(
let zc = client(http, root, params);
let guid = format!("ListSection/{}", new_id());
let stamp = now_millis();
- zc.create_record_signed(
+ // A phone's new section carries a token for exactly these four (measured on his account:
+ // `Deleted` and `Imported` get none, `minimumSupportedVersion` one with no field of its
+ // own), so they are stamped and nothing else.
+ zc.create_record(
ZONE,
&guid,
"ListSection",
@@ -716,6 +934,11 @@ pub async fn create_section_cloudkit(
"CreationDate": { "type": "TIMESTAMP", "value": stamp },
"Deleted": { "type": "NUMBER_INT64", "value": 0 },
"Imported": { "type": "NUMBER_INT64", "value": 0 },
+ "ResolutionTokenMap": stamp_only(
+ &json!({}),
+ &["minimumSupportedVersion", "list", "creationDate", "displayName"],
+ apple_now(),
+ ),
}),
)
.await?;
@@ -860,6 +1083,105 @@ pub async fn move_to_section_cloudkit(
_ => return Err(Error::Refused("That section isn't in this list.".into())),
}
}
+ edit_memberships(http, root, &params, list_guid, |current, now| {
+ place_in_section(current, reminder_guid, section, now).map(Some)
+ })
+ .await
+}
+
+/// The list's membership file with every reminder in `section` taken out of it (its entry
+/// kept, without a `groupID`, as Apple keeps a reminder in no section), or `None` when none
+/// is in it. Every other entry and key is kept as it was.
+pub fn out_of_section(
+ file: Option<&[u8]>,
+ section: &str,
+ modified_on: f64,
+) -> Result<Option<Vec<u8>>> {
+ let Some(bytes) = file.filter(|b| !b.is_empty()) else {
+ return Ok(None);
+ };
+ let unreadable = || {
+ Error::Refused(
+ "This list's sections are in a form Skykeep doesn't read, so nothing was changed."
+ .into(),
+ )
+ };
+ let mut doc: Value = serde_json::from_slice(bytes).map_err(|_| unreadable())?;
+ let group = bare(section);
+ let mut changed = Vec::new();
+ for (i, entry) in doc
+ .get_mut("memberships")
+ .and_then(Value::as_array_mut)
+ .ok_or_else(unreadable)?
+ .iter_mut()
+ .enumerate()
+ {
+ let here = entry
+ .get("groupID")
+ .and_then(Value::as_str)
+ .is_some_and(|g| g.eq_ignore_ascii_case(group));
+ if here {
+ if let Some(o) = entry.as_object_mut() {
+ o.remove("groupID");
+ o.insert("modifiedOn".into(), json!(modified_on));
+ changed.push((i, entry.clone()));
+ }
+ }
+ }
+ if changed.is_empty() {
+ return Ok(None);
+ }
+ splice_memberships(bytes, &changed, None, &doc)
+ .map(Some)
+ .ok_or_else(unreadable)
+}
+
+/// Remove a section from its list, as a phone removes one (measured on his account: a
+/// section deleted on an iPhone keeps its record with `Deleted` 1 and no `List`, and only
+/// the `list` token advanced). Its reminders are taken out of it first, so none is left in a
+/// section that is gone; they stay in the list.
+pub async fn delete_section_cloudkit(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+ list_guid: &str,
+ section_guid: &str,
+) -> Result<()> {
+ writes()?;
+ let zc = client(http, root, params.clone());
+ match zc.lookup_record(ZONE, section_guid).await? {
+ Some(s) if !deleted(&s) && field::reference(&s, "List").as_deref() == Some(list_guid) => {}
+ _ => return Err(Error::Refused("That section isn't in this list.".into())),
+ }
+ edit_memberships(http, root, &params, list_guid, |current, now| {
+ out_of_section(current, section_guid, now)
+ })
+ .await?;
+ zc.edit_record(ZONE, section_guid, "ListSection", |s| {
+ if deleted(s) {
+ return None;
+ }
+ Some(json!({
+ "Deleted": { "type": "NUMBER_INT64", "value": 1 },
+ "List": { "type": "REFERENCE", "value": null },
+ "ResolutionTokenMap": stamp_only(s, &["list"], apple_now()),
+ }))
+ })
+ .await?;
+ Ok(())
+}
+
+/// Rewrite a list's membership file: `edit` gets the file as Apple holds it now (or none)
+/// and answers the new one, or `None` for no change. Uploaded and written onto the list over
+/// exactly the version read; another device's write meanwhile is read again and kept.
+async fn edit_memberships(
+ http: &reqwest::Client,
+ root: &str,
+ params: &[(String, String)],
+ list_guid: &str,
+ edit: impl Fn(Option<&[u8]>, f64) -> Result<Option<Vec<u8>>>,
+) -> Result<()> {
+ let zc = client(http, root, params.to_vec());
for _ in 0..5 {
let Some(list) = zc.lookup_record(ZONE, list_guid).await? else {
return Err(Error::Refused("That list is no longer in iCloud.".into()));
@@ -884,18 +1206,12 @@ pub async fn move_to_section_cloudkit(
}
};
let now = apple_now();
- let file = place_in_section(current.as_deref(), reminder_guid, section, now)?;
+ let Some(file) = edit(current.as_deref(), now)? else {
+ return Ok(());
+ };
let sum = membership_checksum(&file);
- let receipt = upload_asset(
- http,
- root,
- &params,
- "List",
- list_guid,
- MEMBERSHIP_FILE,
- file,
- )
- .await?;
+ let receipt =
+ upload_asset(http, root, params, "List", list_guid, MEMBERSHIP_FILE, file).await?;
let changes = json!({
MEMBERSHIP_FILE: { "type": "ASSETID", "value": receipt },
MEMBERSHIP_SUM: { "type": "STRING", "value": sum, "isEncrypted": true },
@@ -920,10 +1236,115 @@ mod tests {
B64.encode(s.as_bytes())
}
- /// The gate refuses when off, and is off: flipping it is for a supervised live test.
+ /// Apple's own file shape: keys in either order, numbers in 17 significant digits that
+ /// a shortest-form writer would shorten.
+ const APPLE_FILE: &[u8] = br#"{"minimumSupportedVersion":20230430,"memberships":[{"modifiedOn":776521004.53464794,"memberID":"A4722061-AEE0-4B0A-AC0E-595C5FE268BC"},{"memberID":"BA60D351-AF45-451B-AC56-84D5F30BA1BB","modifiedOn":777393833.63318706},{"memberID":"C0FFEE00-0000-0000-0000-000000000001","groupID":"S1","modifiedOn":785142271.29329395}]}"#;
+
+ /// A no-op edit gives back Apple's bytes exactly.
+ #[test]
+ fn a_no_op_splice_is_byte_identical() {
+ let doc: Value = serde_json::from_slice(APPLE_FILE).unwrap();
+ assert_eq!(
+ splice_memberships(APPLE_FILE, &[], None, &doc).unwrap(),
+ APPLE_FILE
+ );
+ // Spaced and newlined, too.
+ let spaced = b"{ \"memberships\" : [ {\"memberID\":\"A\", \"modifiedOn\":1.10000000000000009} ,\n {\"memberID\":\"B\"} ] , \"x\":\"]}\\\"\" }";
+ let doc: Value = serde_json::from_slice(spaced).unwrap();
+ assert_eq!(splice_memberships(spaced, &[], None, &doc).unwrap(), spaced);
+ // Nothing to take out: nothing to write.
+ assert!(out_of_section(Some(APPLE_FILE), "ListSection/S9", 9.0)
+ .unwrap()
+ .is_none());
+ }
+
+ /// Moving one reminder changes only its entry's span: every byte before and after it is
+ /// Apple's. A new member is appended after the last entry and nothing else moves.
#[test]
- fn writes_stay_off_until_a_supervised_live_test() {
- const { assert!(!REMINDER_DETAIL_WRITES) };
+ fn a_move_changes_only_that_entrys_span() {
+ let second = br#"{"memberID":"BA60D351-AF45-451B-AC56-84D5F30BA1BB","modifiedOn":777393833.63318706}"#;
+ let start = APPLE_FILE
+ .windows(second.len())
+ .position(|w| w == second)
+ .unwrap();
+ let end = start + second.len();
+ let out = place_in_section(
+ Some(APPLE_FILE),
+ "Reminder/BA60D351-AF45-451B-AC56-84D5F30BA1BB",
+ Some("ListSection/S2"),
+ 9.5,
+ )
+ .unwrap();
+ assert_eq!(out[..start], APPLE_FILE[..start]);
+ let tail = &APPLE_FILE[end..];
+ assert_eq!(out[out.len() - tail.len()..], *tail);
+ let entry: Value = serde_json::from_slice(&out[start..out.len() - tail.len()]).unwrap();
+ assert_eq!(
+ entry,
+ json!({"memberID":"BA60D351-AF45-451B-AC56-84D5F30BA1BB","groupID":"S2","modifiedOn":9.5})
+ );
+
+ // A new member: Apple's text up to the array's end, then the one entry.
+ let close = APPLE_FILE.len() - 2;
+ let added = place_in_section(
+ Some(APPLE_FILE),
+ "Reminder/NEW",
+ Some("ListSection/S2"),
+ 9.5,
+ )
+ .unwrap();
+ assert_eq!(added[..close], APPLE_FILE[..close]);
+ assert_eq!(
+ &added[close..],
+ br#",{"groupID":"S2","memberID":"NEW","modifiedOn":9.5}]}"#
+ );
+
+ // Out of a section: only the entries in it change.
+ let s1 = br#"{"memberID":"C0FFEE00-0000-0000-0000-000000000001","groupID":"S1","modifiedOn":785142271.29329395}"#;
+ let at = APPLE_FILE.windows(s1.len()).position(|w| w == s1).unwrap();
+ let out = out_of_section(Some(APPLE_FILE), "ListSection/S1", 10.0)
+ .unwrap()
+ .unwrap();
+ assert_eq!(out[..at], APPLE_FILE[..at]);
+ assert_eq!(
+ &out[at..],
+ br#"{"memberID":"C0FFEE00-0000-0000-0000-000000000001","modifiedOn":10.0}]}"#
+ );
+ }
+
+ /// Removing a section takes every reminder in it out of it — the entry kept, without a
+ /// `groupID`, as Apple keeps a reminder in no section — and touches nothing else.
+ #[test]
+ fn removing_a_section_takes_its_reminders_out_of_it() {
+ let file = br#"{"minimumSupportedVersion":20230430,"memberships":[
+ {"memberID":"A","groupID":"S1","modifiedOn":1.5},
+ {"memberID":"B","groupID":"S2","modifiedOn":2.5},
+ {"memberID":"C","modifiedOn":3.5}]}"#;
+ let out = out_of_section(Some(file), "ListSection/S1", 9.0)
+ .unwrap()
+ .unwrap();
+ let v: Value = serde_json::from_slice(&out).unwrap();
+ assert_eq!(v["minimumSupportedVersion"], 20_230_430);
+ let m = v["memberships"].as_array().unwrap();
+ assert_eq!(m[0], json!({ "memberID": "A", "modifiedOn": 9.0 }));
+ assert_eq!(
+ m[1],
+ json!({ "memberID": "B", "groupID": "S2", "modifiedOn": 2.5 })
+ );
+ assert_eq!(m[2], json!({ "memberID": "C", "modifiedOn": 3.5 }));
+ // Nobody in it: nothing to write.
+ assert!(out_of_section(Some(file), "ListSection/S9", 9.0)
+ .unwrap()
+ .is_none());
+ assert!(out_of_section(None, "ListSection/S1", 9.0)
+ .unwrap()
+ .is_none());
+ }
+
+ /// The gate refuses when off; it is on since the supervised live test (2026-10-22).
+ #[test]
+ fn the_gate_refuses_when_off() {
+ const { assert!(REMINDER_DETAIL_WRITES) };
assert!(matches!(gate(false), Err(Error::Refused(_))));
assert!(gate(true).is_ok());
}
@@ -1247,6 +1668,44 @@ mod tests {
);
}
+ /// Removing a tag unlists it from the reminder and deletes its Hashtag record outright,
+ /// as a phone does: a tag only marked `Deleted` still shows on an iPhone.
+ #[tokio::test]
+ async fn removing_a_tag_deletes_its_record() {
+ let server = MockServer::start().await;
+ let mut r = reminder();
+ r["fields"]["HashtagIDs"] = json!({ "type": "STRING_LIST", "value": ["T1", "T2"] });
+ lookup(&server, "Reminder/R1", r).await;
+ lookup(&server, "Hashtag/T1", json!({ "recordName": "Hashtag/T1", "recordType": "Hashtag",
+ "recordChangeTag": "h1", "fields": { "Name": { "type": "STRING", "value": "Errands" },
+ "Deleted": { "type": "NUMBER_INT64", "value": 0 } } })).await;
+ lookup(
+ &server,
+ "Hashtag/T2",
+ json!({ "recordName": "Hashtag/T2", "recordType": "Hashtag",
+ "recordChangeTag": "h2", "fields": { "Name": { "type": "STRING", "value": "Home" },
+ "Deleted": { "type": "NUMBER_INT64", "value": 0 } } }),
+ )
+ .await;
+ modify_ok(&server).await;
+ let http = reqwest::Client::new();
+ remove_tag_cloudkit(&http, &server.uri(), vec![], "Reminder/R1", "#errands")
+ .await
+ .unwrap();
+ let ops = modifies(&server.received_requests().await.unwrap());
+ assert_eq!(ops.len(), 2, "{ops:?}");
+ assert_eq!(ops[0]["operationType"], "update");
+ assert_eq!(
+ ops[0]["record"]["fields"]["HashtagIDs"]["value"],
+ json!(["T2"])
+ );
+ assert_eq!(ops[1]["operationType"], "forceDelete");
+ assert_eq!(ops[1]["record"]["recordName"], "Hashtag/T1");
+ assert!(ops
+ .iter()
+ .all(|o| o["record"]["recordName"] != "Hashtag/T2"));
+ }
+
#[tokio::test]
async fn a_link_is_a_new_url_attachment() {
let server = MockServer::start().await;
@@ -1266,7 +1725,11 @@ mod tests {
let made = &ops[0]["record"];
assert_eq!(made["recordType"], "Attachment");
assert_eq!(made["fields"]["Type"]["value"], "URL");
- assert_eq!(made["fields"]["URL"]["value"], b64("https://apple.com"));
+ // An encrypted string, as a phone writes it, not bytes.
+ assert_eq!(
+ made["fields"]["URL"],
+ json!({ "type": "STRING", "value": "https://apple.com", "isEncrypted": true })
+ );
let id = bare(made["recordName"].as_str().unwrap()).to_string();
assert_eq!(
ops[1]["record"]["fields"]["AttachmentIDs"]["value"],
diff --git a/crates/quince-icloud/src/reminders_more.rs b/crates/quince-icloud/src/reminders_more.rs
new file mode 100644
index 0000000..eb6aad4
--- /dev/null
+++ b/crates/quince-icloud/src/reminders_more.rs
@@ -0,0 +1,719 @@
+//! The rest of what the phone's Details screen shows for a reminder: its repeat whole (with
+//! its end), its time zone, Urgent, a place it rings at, and the person it comes up for when
+//! messaging. Read from the reminder record and the records Apple keeps beside it.
+//!
+//! Shapes, all measured on a real account (the "Skykeep Test" reminder made on an iPhone):
+//!
+//! * `RecurrenceRule` — `Frequency` (0 daily, 1 weekly, 2 monthly, 3 yearly, 4 hourly),
+//! `Interval`, `FirstDayOfTheWeek` 0, `OccurrenceCount` 0, and `EndDate` (a `TIMESTAMP`)
+//! when the repeat ends on a date. A reminder lists its rules' bare ids in
+//! `RecurrenceRuleIDs`.
+//! * A place is an `AlarmTrigger` of `Type` `Location`: `Title` ("Alex's Home"),
+//! `Proximity` 1 arriving (2 leaving), `Latitude`, `Longitude`, `Radius`, `LocationUID`.
+//! * When Messaging is the reminder's `ContactHandles`: JSON `{"emails":[…],"phones":[…]}`.
+//! * Urgent is a small JSON file (`UrgentPresentationAlarmsAsData`):
+//! `{"account":[{"isEnabled":true,…}],"minimumSupportedVersion":…}`. Most reminders on a
+//! phone carry one with `isEnabled` false; only `true` is Urgent.
+
+use crate::cloudkit::{field, ZoneClient};
+use crate::Result;
+use quince_core::reminders::{MessagingPerson, PlaceAlarm, ReminderMore, ReminderPart, RepeatRule};
+use serde_json::Value;
+
+/// The rule fields this app reads. Anything else on a rule is kept and named.
+const RULE_FIELDS: [&str; 9] = [
+ "DaysOfTheWeek",
+ "Frequency",
+ "Interval",
+ "FirstDayOfTheWeek",
+ "OccurrenceCount",
+ "EndDate",
+ "Imported",
+ "Deleted",
+ "Reminder",
+];
+
+/// Apple's frequencies, highest first in Apple's numbering: 0 daily … 4 hourly.
+pub const MOST_FREQUENCY: i64 = 4;
+
+/// A record worth keeping beside its reminder: a repeat rule, or a trigger that is a place
+/// rather than a moment (moments are the alarm tables' business).
+#[must_use]
+pub fn part_from_record(record: &Value) -> Option<ReminderPart> {
+ let kind = field::record_type(record)?;
+ let keep = match kind.as_str() {
+ "RecurrenceRule" => true,
+ "AlarmTrigger" => field::string(record, "Type").is_some_and(|t| t != "Date"),
+ _ => false,
+ };
+ if !keep || field::flag(record, "Deleted") {
+ return None;
+ }
+ Some(ReminderPart {
+ name: field::record_name(record)?,
+ reminder_guid: field::reference(record, "Reminder"),
+ kind,
+ raw: serde_json::to_string(record).ok()?,
+ })
+}
+
+/// A rule record as the phone's Repeat and End Repeat rows read it.
+#[must_use]
+pub fn rule_from_record(record: &Value) -> Option<RepeatRule> {
+ let frequency = field::int(record, "Frequency")?;
+ let fields = record.get("fields").and_then(Value::as_object)?;
+ // Weekdays, Weekends and days chosen in Custom. A week of the month ("the first Monday")
+ // is not read here, so it is named among the fields kept as they are.
+ let days = field::string(record, "DaysOfTheWeek")
+ .map(|b| quince_core::reminders::days_of_week_from(&b));
+ let mut other: Vec<String> = fields
+ .iter()
+ .filter(|(name, v)| {
+ !RULE_FIELDS.contains(&name.as_str())
+ && !v.get("value").is_none_or(|x| {
+ x.is_null() || x.as_array().is_some_and(Vec::is_empty) || x.as_str() == Some("")
+ })
+ })
+ .map(|(name, _)| name.clone())
+ .collect();
+ if matches!(days, Some(None)) {
+ other.push("DaysOfTheWeek".into());
+ }
+ other.sort();
+ Some(RepeatRule {
+ days_of_week: days.flatten().unwrap_or_default(),
+ frequency,
+ interval: field::int(record, "Interval").unwrap_or(1).max(1),
+ end_at: field::timestamp_seconds(record, "EndDate"),
+ occurrence_count: field::int(record, "OccurrenceCount").unwrap_or(0),
+ other,
+ })
+}
+
+/// A place trigger as the phone's Location row reads it.
+#[must_use]
+pub fn place_from_record(record: &Value) -> Option<PlaceAlarm> {
+ let kind = field::string(record, "Type")?;
+ if kind == "Date" {
+ return None;
+ }
+ Some(PlaceAlarm {
+ title: field::string(record, "Title").filter(|t| !t.trim().is_empty()),
+ proximity: match field::int(record, "Proximity") {
+ Some(1) => Some("arriving".into()),
+ Some(2) => Some("leaving".into()),
+ _ => None,
+ },
+ kind,
+ })
+}
+
+/// The email addresses and numbers in a reminder's `ContactHandles`, emails first.
+#[must_use]
+pub fn contact_handles(reminder: &Value) -> Vec<String> {
+ let Some(raw) = field::string(reminder, "ContactHandles") else {
+ return Vec::new();
+ };
+ let Ok(parsed) = serde_json::from_str::<Value>(&raw) else {
+ return Vec::new();
+ };
+ ["emails", "phones"]
+ .iter()
+ .filter_map(|k| parsed.get(*k).and_then(Value::as_array))
+ .flatten()
+ .filter_map(Value::as_str)
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty())
+ .collect()
+}
+
+/// Whether an Urgent file says the alarm is on. A file that does not read says nothing.
+#[must_use]
+pub fn urgent_from_file(bytes: &[u8]) -> Option<bool> {
+ let parsed: Value = serde_json::from_slice(bytes).ok()?;
+ let accounts = parsed.get("account")?.as_array()?;
+ Some(
+ accounts
+ .iter()
+ .any(|a| a.get("isEnabled").and_then(Value::as_bool) == Some(true)),
+ )
+}
+
+/// Everything the Details screen shows beyond tags, a link and early alerts, from what the
+/// library holds. Urgent is left unknown: it lives in a file, read by [`urgent_cloudkit`].
+#[must_use]
+pub fn more_from(
+ guid: &str,
+ raw: Option<&str>,
+ timezone: Option<&str>,
+ parts: &[ReminderPart],
+) -> ReminderMore {
+ let record: Option<Value> = raw.and_then(|r| serde_json::from_str(r).ok());
+ let parsed: Vec<Value> = parts
+ .iter()
+ .filter_map(|p| serde_json::from_str(&p.raw).ok())
+ .collect();
+ // The rule the reminder names now; a rule left behind by an older repeat is not it.
+ let named: Vec<String> = record
+ .as_ref()
+ .and_then(|r| r.pointer("/fields/RecurrenceRuleIDs/value"))
+ .and_then(Value::as_array)
+ .map(|ids| {
+ ids.iter()
+ .filter_map(Value::as_str)
+ .map(ToString::to_string)
+ .collect()
+ })
+ .unwrap_or_default();
+ let repeat = parsed
+ .iter()
+ .filter(|p| field::record_type(p).as_deref() == Some("RecurrenceRule"))
+ .find(|p| {
+ let name = field::record_name(p).unwrap_or_default();
+ let bare = name.rsplit('/').next().unwrap_or(&name);
+ named.iter().any(|id| id.eq_ignore_ascii_case(bare))
+ })
+ .and_then(rule_from_record);
+ let location = parsed
+ .iter()
+ .filter(|p| field::record_type(p).as_deref() == Some("AlarmTrigger"))
+ .find_map(place_from_record);
+ let handles = record.as_ref().map(contact_handles).unwrap_or_default();
+ ReminderMore {
+ guid: guid.to_string(),
+ repeat,
+ time_zone: timezone.map(ToString::to_string).filter(|z| !z.is_empty()),
+ urgent: None,
+ location,
+ messaging: (!handles.is_empty()).then_some(MessagingPerson {
+ name: None,
+ handles,
+ }),
+ }
+}
+
+/// Urgent files already read, by the checksum Apple keeps beside each: the file changes only
+/// when its checksum does, so each is downloaded once a run.
+static URGENT_SEEN: std::sync::Mutex<Option<std::collections::HashMap<String, bool>>> =
+ std::sync::Mutex::new(None);
+
+fn urgent_checksum(record: &Value) -> Option<String> {
+ field::string(record, "UrgentPresentationAlarmsChecksum").filter(|c| !c.is_empty())
+}
+
+/// Whether a reminder is Urgent, from what the library holds when its file was read already.
+#[must_use]
+pub fn urgent_known(raw: Option<&str>) -> Option<bool> {
+ let record: Value = serde_json::from_str(raw?).ok()?;
+ if record
+ .pointer("/fields/UrgentPresentationAlarmsAsData")
+ .is_none()
+ {
+ // No file at all: never made Urgent.
+ return Some(false);
+ }
+ let sum = urgent_checksum(&record)?;
+ URGENT_SEEN.lock().ok()?.as_ref()?.get(&sum).copied()
+}
+
+/// A picture attached to a reminder, its file as the phone stored it (`FileAsset`, named by
+/// `FileName`). Read only: the attachment record is looked up for a fresh link, which lapses
+/// within the hour, and the file fetched. `None` when Apple has no such picture.
+pub async fn attachment_file(
+ http: &reqwest::Client,
+ ckdatabasews_root: &str,
+ params: Vec<(String, String)>,
+ attachment: &str,
+) -> Result<Option<Vec<u8>>> {
+ let client = ZoneClient::new(http, ckdatabasews_root, "com.apple.reminders", params);
+ let Some(record) = client.lookup_record("Reminders", attachment).await? else {
+ return Ok(None);
+ };
+ let Some(url) = record
+ .pointer("/fields/FileAsset/value/downloadURL")
+ .and_then(Value::as_str)
+ else {
+ return Ok(None);
+ };
+ let name = record
+ .pointer("/fields/FileName/value")
+ .and_then(Value::as_str)
+ .unwrap_or("picture");
+ let response = http
+ .get(url.replace("${f}", name))
+ .send()
+ .await
+ .map_err(|e| crate::Error::Protocol(e.to_string()))?;
+ if !response.status().is_success() {
+ return Ok(None);
+ }
+ let bytes = response
+ .bytes()
+ .await
+ .map_err(|e| crate::Error::Protocol(e.to_string()))?;
+ Ok(Some(bytes.to_vec()))
+}
+
+/// Read a reminder's Urgent file from Apple. Read only: the record is looked up for a fresh
+/// link (the one a sync stored expires within the hour) and the small file fetched.
+pub async fn urgent_cloudkit(
+ http: &reqwest::Client,
+ ckdatabasews_root: &str,
+ params: Vec<(String, String)>,
+ guid: &str,
+) -> Result<Option<bool>> {
+ let client = ZoneClient::new(http, ckdatabasews_root, "com.apple.reminders", params);
+ let Some(record) = client.lookup_record("Reminders", guid).await? else {
+ return Ok(None);
+ };
+ let Some(url) = record
+ .pointer("/fields/UrgentPresentationAlarmsAsData/value/downloadURL")
+ .and_then(Value::as_str)
+ else {
+ return Ok(Some(false));
+ };
+ let response = http
+ .get(url.replace("${f}", "urgent"))
+ .send()
+ .await
+ .map_err(|e| crate::Error::Protocol(e.to_string()))?;
+ if !response.status().is_success() {
+ return Ok(None);
+ }
+ let bytes = response
+ .bytes()
+ .await
+ .map_err(|e| crate::Error::Protocol(e.to_string()))?;
+ let urgent = urgent_from_file(&bytes);
+ if let (Some(on), Some(sum)) = (urgent, urgent_checksum(&record)) {
+ if let Ok(mut seen) = URGENT_SEEN.lock() {
+ seen.get_or_insert_with(Default::default).insert(sum, on);
+ }
+ }
+ Ok(urgent)
+}
+
+/// Whether a reminder is Urgent, read from Apple: the file's link from the record as synced
+/// first (good for about an hour), and only if that has lapsed, a fresh lookup. Read only.
+pub async fn urgent_for(
+ http: &reqwest::Client,
+ ckdatabasews_root: &str,
+ params: Vec<(String, String)>,
+ guid: &str,
+ raw: &str,
+) -> Option<bool> {
+ let record: Value = serde_json::from_str(raw).ok()?;
+ let url = record
+ .pointer("/fields/UrgentPresentationAlarmsAsData/value/downloadURL")
+ .and_then(Value::as_str)?;
+ if let Ok(response) = http.get(url.replace("${f}", "urgent")).send().await {
+ if response.status().is_success() {
+ if let Ok(bytes) = response.bytes().await {
+ let urgent = urgent_from_file(&bytes);
+ if let (Some(on), Some(sum)) = (urgent, urgent_checksum(&record)) {
+ if let Ok(mut seen) = URGENT_SEEN.lock() {
+ seen.get_or_insert_with(Default::default).insert(sum, on);
+ }
+ }
+ return urgent;
+ }
+ }
+ }
+ urgent_cloudkit(http, ckdatabasews_root, params, guid)
+ .await
+ .ok()
+ .flatten()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ /// The founder's "Skykeep Test" as the phone wrote it, personal text replaced.
+ fn skykeep_test() -> Value {
+ json!({
+ "recordName": "Reminder/B51EAE34-018C-4F06-B97C-130C02E98799",
+ "recordType": "Reminder",
+ "recordChangeTag": "jfv",
+ "fields": {
+ "AlarmIDs": { "type": "STRING_LIST", "value": ["18154128-7CA1-46FA-9AB3-1E597CF2D3DC", "4FB1FED5-72D2-486C-A9F9-4F2123118C4A"] },
+ "AllDay": { "type": "NUMBER_INT64", "value": 0 },
+ "ContactHandles": { "isEncrypted": true, "type": "STRING", "value": "{\"emails\":[\"[email protected]\"],\"phones\":[\"+910000000000\"]}" },
+ "DueDate": { "type": "TIMESTAMP", "value": 1_792_681_200_000_i64 },
+ "Flagged": { "type": "NUMBER_INT64", "value": 1 },
+ "HashtagIDs": { "type": "STRING_LIST", "value": ["E805CCFA-D039-4FC5-ABEB-780FA9B9A3B8"] },
+ "Priority": { "type": "NUMBER_INT64", "value": 5 },
+ "RecurrenceRuleIDs": { "type": "STRING_LIST", "value": ["049EF968-7FAE-4585-94FB-E22D108B537D"] },
+ "TimeZone": { "type": "STRING", "value": "America/New_York" },
+ "UrgentPresentationAlarmsAsData": { "type": "ASSETID", "value": { "size": 155, "downloadURL": "https://example.invalid/${f}" } },
+ "UrgentPresentationAlarmsChecksum": { "isEncrypted": true, "type": "STRING", "value": "ddfd7f9a" }
+ }
+ })
+ }
+
+ fn daily_rule(name: &str) -> Value {
+ json!({
+ "recordName": format!("RecurrenceRule/{name}"),
+ "recordType": "RecurrenceRule",
+ "fields": {
+ "Deleted": { "type": "NUMBER_INT64", "value": 0 },
+ "FirstDayOfTheWeek": { "type": "NUMBER_INT64", "value": 0 },
+ "Frequency": { "type": "NUMBER_INT64", "value": 0 },
+ "Imported": { "type": "NUMBER_INT64", "value": 0 },
+ "Interval": { "type": "NUMBER_INT64", "value": 1 },
+ "OccurrenceCount": { "type": "NUMBER_INT64", "value": 0 },
+ "Reminder": { "type": "REFERENCE", "value": { "recordName": "Reminder/B51EAE34-018C-4F06-B97C-130C02E98799", "action": "VALIDATE" } }
+ }
+ })
+ }
+
+ fn home_arriving() -> Value {
+ json!({
+ "recordName": "AlarmTrigger/61D17FA2-277F-41FB-B959-7F5A1C4FDDE9",
+ "recordType": "AlarmTrigger",
+ "fields": {
+ "Alarm": { "type": "REFERENCE", "value": { "recordName": "Alarm/4FB1FED5-72D2-486C-A9F9-4F2123118C4A", "action": "VALIDATE" } },
+ "Deleted": { "type": "NUMBER_INT64", "value": 0 },
+ "Imported": { "type": "NUMBER_INT64", "value": 0 },
+ "Latitude": { "isEncrypted": true, "type": "NUMBER_DOUBLE", "value": 0.0 },
+ "LocationUID": { "type": "STRING", "value": "A2ED6D26-D7B3-483D-B1D1-6B3C97F3A638" },
+ "Longitude": { "isEncrypted": true, "type": "NUMBER_DOUBLE", "value": 0.0 },
+ "Proximity": { "type": "NUMBER_INT64", "value": 1 },
+ "Radius": { "type": "NUMBER_DOUBLE", "value": 100.0 },
+ "ReferenceFrameString": { "isEncrypted": true, "type": "STRING", "value": "1" },
+ "Title": { "isEncrypted": true, "type": "STRING", "value": "Someone\u{2019}s Home" },
+ "Type": { "type": "STRING", "value": "Location" }
+ }
+ })
+ }
+
+ fn date_trigger() -> Value {
+ json!({
+ "recordName": "AlarmTrigger/E76736A9-2B02-486D-AEC8-574702186709",
+ "recordType": "AlarmTrigger",
+ "fields": {
+ "DateComponentsData": { "type": "BYTES", "value": "e30=" },
+ "Type": { "type": "STRING", "value": "Date" }
+ }
+ })
+ }
+
+ fn parts() -> Vec<ReminderPart> {
+ [
+ daily_rule("049EF968-7FAE-4585-94FB-E22D108B537D"),
+ home_arriving(),
+ date_trigger(),
+ ]
+ .iter()
+ .filter_map(part_from_record)
+ .collect()
+ }
+
+ #[test]
+ fn the_rule_and_the_place_are_kept_and_the_moment_is_not() {
+ let kept: Vec<String> = parts().into_iter().map(|p| p.name).collect();
+ assert_eq!(
+ kept,
+ [
+ "RecurrenceRule/049EF968-7FAE-4585-94FB-E22D108B537D",
+ "AlarmTrigger/61D17FA2-277F-41FB-B959-7F5A1C4FDDE9"
+ ]
+ );
+ assert_eq!(
+ parts()[0].reminder_guid.as_deref(),
+ Some("Reminder/B51EAE34-018C-4F06-B97C-130C02E98799")
+ );
+ }
+
+ #[test]
+ fn the_founders_reminder_reads_as_the_phone_shows_it() {
+ let record = skykeep_test();
+ let more = more_from(
+ "Reminder/B51EAE34-018C-4F06-B97C-130C02E98799",
+ Some(&record.to_string()),
+ Some("America/New_York"),
+ &parts(),
+ );
+ let repeat = more.repeat.expect("repeats");
+ assert_eq!(
+ (repeat.frequency, repeat.interval, repeat.end_at),
+ (0, 1, None)
+ );
+ assert!(repeat.other.is_empty());
+ assert_eq!(more.time_zone.as_deref(), Some("America/New_York"));
+ let place = more.location.expect("a place");
+ assert_eq!(place.title.as_deref(), Some("Someone\u{2019}s Home"));
+ assert_eq!(place.proximity.as_deref(), Some("arriving"));
+ assert_eq!(
+ more.messaging.expect("a person").handles,
+ ["[email protected]", "+910000000000"]
+ );
+ assert_eq!(more.urgent, None, "Urgent lives in a file, read apart");
+ }
+
+ #[test]
+ fn a_rule_the_reminder_no_longer_names_is_not_its_repeat() {
+ let mut record = skykeep_test();
+ record["fields"]["RecurrenceRuleIDs"] = json!({ "type": "EMPTY_LIST", "value": [] });
+ let more = more_from(
+ "Reminder/B51EAE34-018C-4F06-B97C-130C02E98799",
+ Some(&record.to_string()),
+ None,
+ &parts(),
+ );
+ assert!(more.repeat.is_none());
+ }
+
+ #[test]
+ fn an_hourly_rule_with_an_end_date_reads_whole() {
+ let mut rule = daily_rule("H");
+ rule["fields"]["Frequency"]["value"] = json!(4);
+ rule["fields"]["EndDate"] = json!({ "type": "TIMESTAMP", "value": 1_791_557_520_000_i64 });
+ let read = rule_from_record(&rule).unwrap();
+ assert_eq!((read.frequency, read.end_at), (4, Some(1_791_557_520)));
+ }
+
+ #[test]
+ fn fields_this_app_does_not_read_are_named_not_lost() {
+ let mut rule = daily_rule("W");
+ rule["fields"]["Frequency"]["value"] = json!(1);
+ rule["fields"]["DaysOfTheWeek"] = json!({ "type": "STRING", "value": "[2,3,4,5,6]" });
+ rule["fields"]["SetPositions"] = json!({ "type": "EMPTY_LIST", "value": [] });
+ assert_eq!(rule_from_record(&rule).unwrap().other, ["DaysOfTheWeek"]);
+ }
+
+ #[test]
+ fn leaving_is_read_and_a_place_with_no_side_says_none() {
+ let mut t = home_arriving();
+ t["fields"]["Proximity"]["value"] = json!(2);
+ assert_eq!(
+ place_from_record(&t).unwrap().proximity.as_deref(),
+ Some("leaving")
+ );
+ t["fields"]["Proximity"]["value"] = json!(0);
+ assert_eq!(place_from_record(&t).unwrap().proximity, None);
+ }
+
+ /// Through a real pass: the list, the reminder, its rule, its two alarms and their
+ /// triggers, walked as Apple sends them, then read back as the Details screen asks.
+ #[test]
+ fn a_sync_pass_keeps_what_the_details_screen_needs() {
+ let list = json!({
+ "recordName": "List/FED5023E-668F-4670-89CB-2B7765A41F53",
+ "recordType": "List",
+ "fields": { "Name": { "type": "STRING", "value": "To-Do" } }
+ });
+ let mut reminder = skykeep_test();
+ reminder["fields"]["List"] = json!({ "type": "REFERENCE", "value": { "recordName": "List/FED5023E-668F-4670-89CB-2B7765A41F53", "action": "VALIDATE" } });
+ reminder["fields"]["TitleDocument"] = json!({ "type": "ENCRYPTED_BYTES", "value": crate::ckdocument::text_to_base64("Test") });
+ let alarm = |id: &str, trigger: &str| {
+ json!({
+ "recordName": format!("Alarm/{id}"),
+ "recordType": "Alarm",
+ "fields": {
+ "Reminder": { "type": "REFERENCE", "value": { "recordName": "Reminder/B51EAE34-018C-4F06-B97C-130C02E98799", "action": "VALIDATE" } },
+ "TriggerID": { "type": "STRING", "value": trigger }
+ }
+ })
+ };
+ let mut library = quince_core::Library::in_memory().unwrap();
+ crate::reminders::apply_cloudkit(
+ &mut library,
+ crate::reminders::RemindersFetch {
+ memberships: std::collections::HashMap::new(),
+ records: vec![
+ list,
+ reminder,
+ daily_rule("049EF968-7FAE-4585-94FB-E22D108B537D"),
+ alarm(
+ "4FB1FED5-72D2-486C-A9F9-4F2123118C4A",
+ "61D17FA2-277F-41FB-B959-7F5A1C4FDDE9",
+ ),
+ alarm(
+ "18154128-7CA1-46FA-9AB3-1E597CF2D3DC",
+ "E76736A9-2B02-486D-AEC8-574702186709",
+ ),
+ home_arriving(),
+ date_trigger(),
+ ],
+ token: Some("t".into()),
+ incremental: false,
+ },
+ )
+ .unwrap();
+ let guid = "Reminder/B51EAE34-018C-4F06-B97C-130C02E98799";
+ let stored = library.reminder(guid).unwrap().unwrap();
+ assert_eq!(
+ (stored.recur_frequency, stored.recur_interval),
+ (Some(0), Some(1))
+ );
+ assert_eq!((stored.priority, stored.flagged), (5, true));
+ let parts = library.reminder_parts(guid).unwrap();
+ let raw = library.reminder_raw(guid).unwrap();
+ let more = more_from(guid, raw.as_deref(), stored.timezone.as_deref(), &parts);
+ assert_eq!(more.repeat.map(|r| (r.frequency, r.interval)), Some((0, 1)));
+ assert_eq!(more.time_zone.as_deref(), Some("America/New_York"));
+ assert_eq!(
+ more.location.and_then(|l| l.proximity).as_deref(),
+ Some("arriving")
+ );
+ assert!(more.messaging.is_some());
+ }
+
+ // ---- The founder's samples, made on his iPhone for this: one per Repeat option, early
+ // reminders and Urgent. Ids and dates as the phone wrote them; no personal text.
+
+ /// "Repeating 1" and "Repeating 3": Weekdays — the phone wrote the keys in either order.
+ const WEEKDAYS_A: &str = "W3siZGF5T2ZUaGVXZWVrIjoyLCJ3ZWVrTnVtYmVyIjowfSx7ImRheU9mVGhlV2VlayI6Mywid2Vla051bWJlciI6MH0seyJkYXlPZlRoZVdlZWsiOjQsIndlZWtOdW1iZXIiOjB9LHsiZGF5T2ZUaGVXZWVrIjo1LCJ3ZWVrTnVtYmVyIjowfSx7ImRheU9mVGhlV2VlayI6Niwid2Vla051bWJlciI6MH1d";
+ const WEEKDAYS_B: &str = "W3sid2Vla051bWJlciI6MCwiZGF5T2ZUaGVXZWVrIjoyfSx7IndlZWtOdW1iZXIiOjAsImRheU9mVGhlV2VlayI6M30seyJ3ZWVrTnVtYmVyIjowLCJkYXlPZlRoZVdlZWsiOjR9LHsid2Vla051bWJlciI6MCwiZGF5T2ZUaGVXZWVrIjo1fSx7IndlZWtOdW1iZXIiOjAsImRheU9mVGhlV2VlayI6Nn1d";
+ /// "Rep 4": Weekends.
+ const WEEKENDS: &str = "W3siZGF5T2ZUaGVXZWVrIjoxLCJ3ZWVrTnVtYmVyIjowfSx7ImRheU9mVGhlV2VlayI6Nywid2Vla051bWJlciI6MH1d";
+
+ fn sample_rule(
+ frequency: i64,
+ interval: i64,
+ days: Option<&str>,
+ end_ms: Option<i64>,
+ ) -> Value {
+ let mut r = daily_rule("SAMPLE");
+ r["fields"]["Frequency"]["value"] = json!(frequency);
+ r["fields"]["Interval"]["value"] = json!(interval);
+ if let Some(d) = days {
+ r["fields"]["DaysOfTheWeek"] = json!({ "type": "BYTES", "value": d });
+ }
+ if let Some(e) = end_ms {
+ r["fields"]["EndDate"] = json!({ "type": "TIMESTAMP", "value": e });
+ }
+ r
+ }
+
+ #[test]
+ fn every_repeat_the_phone_wrote_reads_as_its_menu_shows_it() {
+ // (sample, frequency, interval, days, end) — Repeating 1, a, 3; Rep 4, 5, 6, 7, 8.
+ let cases = [
+ (
+ sample_rule(1, 1, Some(WEEKDAYS_A), Some(1_792_656_031_000)),
+ 1,
+ 1,
+ vec![2, 3, 4, 5, 6],
+ Some(1_792_656_031),
+ ),
+ (sample_rule(4, 1, None, None), 4, 1, vec![], None),
+ (
+ sample_rule(1, 1, Some(WEEKDAYS_B), None),
+ 1,
+ 1,
+ vec![2, 3, 4, 5, 6],
+ None,
+ ),
+ (
+ sample_rule(1, 1, Some(WEEKENDS), None),
+ 1,
+ 1,
+ vec![1, 7],
+ None,
+ ),
+ (sample_rule(1, 1, None, None), 1, 1, vec![], None),
+ (sample_rule(1, 2, None, None), 1, 2, vec![], None),
+ (sample_rule(2, 1, None, None), 2, 1, vec![], None),
+ (
+ sample_rule(2, 3, None, Some(1_792_656_137_000)),
+ 2,
+ 3,
+ vec![],
+ Some(1_792_656_137),
+ ),
+ ];
+ for (record, frequency, interval, days, end) in cases {
+ let read = rule_from_record(&record).unwrap();
+ assert_eq!(
+ (
+ read.frequency,
+ read.interval,
+ read.days_of_week,
+ read.end_at
+ ),
+ (frequency, interval, days, end)
+ );
+ assert!(
+ read.other.is_empty(),
+ "nothing on the phone's rules is left unread"
+ );
+ }
+ }
+
+ /// Written back, Weekdays and Weekends are the phone's own bytes.
+ #[test]
+ fn weekdays_and_weekends_are_written_as_the_phone_wrote_them() {
+ assert_eq!(
+ quince_core::reminders::days_of_week_to(&[2, 3, 4, 5, 6]),
+ WEEKDAYS_A
+ );
+ assert_eq!(quince_core::reminders::days_of_week_to(&[7, 1]), WEEKENDS);
+ // Monday, Wednesday, Friday, chosen in Custom: the same form.
+ let mwf = quince_core::reminders::days_of_week_to(&[2, 4, 6]);
+ assert_eq!(
+ quince_core::reminders::days_of_week_from(&mwf),
+ Some(vec![2, 4, 6])
+ );
+ }
+
+ /// A week of the month ("the first Monday") is not a weekday choice: kept, and named.
+ #[test]
+ fn a_week_of_the_month_is_kept_not_misread() {
+ use base64::Engine;
+ let first_monday = base64::engine::general_purpose::STANDARD
+ .encode(r#"[{"dayOfTheWeek":2,"weekNumber":1}]"#);
+ let read = rule_from_record(&sample_rule(2, 1, Some(&first_monday), None)).unwrap();
+ assert!(read.days_of_week.is_empty());
+ assert_eq!(read.other, ["DaysOfTheWeek"]);
+ }
+
+ /// The early reminders the phone wrote ("Repeating 1": 1 day before; "Rep 7": 2 days
+ /// before), read by the details reader as count and unit (2 = days).
+ #[test]
+ fn the_phones_early_reminders_read_as_days_before() {
+ use base64::Engine;
+ let blob = |count: i64| {
+ base64::engine::general_purpose::STANDARD.encode(format!(
+ r#"{{"reminderIdentifier":"C7191213-7FE3-47D2-A60A-FB4C1BF98EF6","dueDateDeltaAlerts":[{{"minimumSupportedAppVersion":0,"identifier":"20813BA8-FF88-4487-94F0-4205C37F5A90","dueDateDeltaCount":{count},"creationDate":814348968.97073495,"dueDateDeltaUnit":2}}],"accountIdentifier":"6D050766-549E-4C2C-93F1-53CE17E5798F","minimumSupportedVersion":20230430}}"#
+ ))
+ };
+ for count in [-1, -2] {
+ let record = json!({ "fields": { "DueDateDeltaAlertsData": { "type": "BYTES", "value": blob(count) } } });
+ let (_, alerts) = crate::reminders::details::early_alerts_from_record(&record);
+ assert_eq!((alerts[0].count, alerts[0].unit), (-count, 2));
+ }
+ }
+
+ /// "Rep 5" and "Rep 8" are Urgent; the other six are not.
+ #[test]
+ fn the_phones_urgent_files_read_on_and_off() {
+ let on = br#"{"minimumSupportedVersion":20251103,"account":[{"modifiedOn":814348900.87413299,"personID":"P","isEnabled":true}]}"#;
+ let off = br#"{"account":[{"modifiedOn":814348852.927158,"personID":"P","isEnabled":false}],"minimumSupportedVersion":20251103}"#;
+ assert_eq!(urgent_from_file(on), Some(true));
+ assert_eq!(urgent_from_file(off), Some(false));
+ }
+
+ #[test]
+ fn urgent_is_on_only_when_the_file_says_so() {
+ let on = br#"{"minimumSupportedVersion":20251103,"account":[{"personID":"x","modifiedOn":814338293.79,"isEnabled":true}]}"#;
+ let off = br#"{"account":[{"isEnabled":false,"modifiedOn":788163438.85,"personID":"x"}],"minimumSupportedVersion":20251103}"#;
+ assert_eq!(urgent_from_file(on), Some(true));
+ assert_eq!(urgent_from_file(off), Some(false));
+ assert_eq!(urgent_from_file(b"not json"), None);
+ }
+
+ #[test]
+ fn a_reminder_with_no_urgent_file_was_never_urgent() {
+ let mut record = skykeep_test();
+ record["fields"]
+ .as_object_mut()
+ .unwrap()
+ .remove("UrgentPresentationAlarmsAsData");
+ assert_eq!(urgent_known(Some(&record.to_string())), Some(false));
+ // With a file not yet read, it is not known.
+ assert_eq!(urgent_known(Some(&skykeep_test().to_string())), None);
+ }
+}
diff --git a/crates/quince-icloud/src/table.rs b/crates/quince-icloud/src/table.rs
index f422071..3acfe03 100644
--- a/crates/quince-icloud/src/table.rs
+++ b/crates/quince-icloud/src/table.rs
@@ -950,6 +950,17 @@ fn edit_table_text(
put_len(4, writers, &mut lent);
let edited = edit(&lent)?;
let new_writers = bytes(&fields(&edited)?, 4).next()?.to_vec();
+ // A writer new to the table must come last: this text alone is renumbered by the edit,
+ // and the table's other texts would keep the old numbers.
+ let (before, after) = (
+ TableWriters::read(writers),
+ TableWriters::read(&new_writers),
+ );
+ if let (Some(b), Some(a)) = (&before, &after) {
+ if a.0.len() != b.0.len() && a.0.get(..b.0.len()) != Some(&b.0[..]) {
+ return None;
+ }
+ }
// Apple keeps this list sorted by uuid and reads a writer number as a place in that
// order; a writer appended out of order would hand the phone's characters to another
// writer (docs/notes-tables-crdt.md). Row and column writes do not renumber, so they are
diff --git a/crates/quince-icloud/src/topotext.rs b/crates/quince-icloud/src/topotext.rs
index ca4e9a5..fc8ada5 100644
--- a/crates/quince-icloud/src/topotext.rs
+++ b/crates/quince-icloud/src/topotext.rs
@@ -336,6 +336,15 @@ impl Topo {
}
/// This app's place in the list of writers, adding it if it is not there yet.
+ ///
+ /// Apple keeps the list sorted by uuid, and a phone reads a writer number as a place in
+ /// that sorted list (docs/notes-tables-crdt.md: a table whose list this app had appended
+ /// to came back from a Mac sorted, every number left as it was, and the phone's own
+ /// characters attributed to someone else — doubled text and conflict copies). Every
+ /// multi-writer note body an Apple device last wrote is sorted (census, 2026-10-22). So a
+ /// writer new to a sorted list goes in at its sorted place, and every number from that
+ /// place up moves up one, which reads the same whether the list is taken in order or
+ /// sorted. A list already out of order (an older build's append) is appended to, as before.
fn own_writer(&mut self) -> usize {
let me = writer();
if let Some(i) = self.writers.iter().position(|w| w.uuid == me) {
@@ -344,11 +353,31 @@ impl Topo {
}
return i;
}
- self.writers.push(Writer {
- uuid: me.to_vec(),
- clocks: vec![0, 0],
- });
- self.writers.len() - 1
+ let sorted = self.writers.windows(2).all(|w| w[0].uuid < w[1].uuid);
+ let at = if sorted {
+ self.writers
+ .partition_point(|w| w.uuid.as_slice() < me.as_slice())
+ } else {
+ self.writers.len()
+ };
+ self.writers.insert(
+ at,
+ Writer {
+ uuid: me.to_vec(),
+ clocks: vec![0, 0],
+ },
+ );
+ // Numbers are 1-based; the markers' 0 is nobody's and stays.
+ let from = at as u64 + 1;
+ for s in &mut self.substrings {
+ if s.writer >= from {
+ s.writer += 1;
+ }
+ if s.stamp_writer >= from {
+ s.stamp_writer += 1;
+ }
+ }
+ at
}
/// New text of `length` units at `at`, as a substring of this app's own.
@@ -551,6 +580,54 @@ mod tests {
assert_eq!(roundtrip(&t), t);
}
+ /// A writer new to a sorted list goes in at its sorted place, and every number from there
+ /// up moves with its writer — the phone's characters stay the phone's however the list is
+ /// read.
+ #[test]
+ fn a_new_writer_takes_its_sorted_place_and_numbers_follow() {
+ let marker = |clock| Substring {
+ writer: 0,
+ clock,
+ length: 0,
+ stamp_writer: 0,
+ stamp_clock: clock,
+ deleted: false,
+ };
+ let text = |writer, length| Substring {
+ writer,
+ clock: 0,
+ length,
+ stamp_writer: writer,
+ stamp_clock: 0,
+ deleted: false,
+ };
+ let mut t = Topo {
+ substrings: vec![marker(0), text(1, 3), text(2, 4), marker(END)],
+ writers: vec![
+ Writer {
+ uuid: vec![0x00; 16],
+ clocks: vec![3, 1],
+ },
+ Writer {
+ uuid: vec![0xFF; 16],
+ clocks: vec![4, 1],
+ },
+ ],
+ };
+ t.edit(7, 0, 2);
+ assert_eq!(t.writers.len(), 3);
+ assert!(t.writers.windows(2).all(|w| w[0].uuid < w[1].uuid));
+ assert_eq!(t.writers[1].uuid, writer().to_vec());
+ let ids: Vec<u64> = t.live_ids().iter().map(|&(w, _)| w).collect();
+ assert_eq!(ids, [1, 1, 1, 3, 3, 3, 3, 2, 2]);
+ assert!(t
+ .substrings
+ .iter()
+ .filter(|s| s.length > 0)
+ .all(|s| s.stamp_writer == s.writer));
+ assert_eq!(roundtrip(&t), t);
+ }
+
#[test]
fn typing_in_the_middle_keeps_everyone_elses_characters() {
let mut t = Topo::fresh(10);
diff --git a/crates/quince-media/src/lib.rs b/crates/quince-media/src/lib.rs
index fa820eb..c5698bb 100644
--- a/crates/quince-media/src/lib.rs
+++ b/crates/quince-media/src/lib.rs
@@ -178,32 +178,58 @@ pub fn rgb_lightness(data: &[u8], w: u32, h: u32, stride: usize) -> f64 {
}
}
-/// Whether a picture shows nothing: every part of it black, as Apple's poster for a video
-/// whose first frame is black (a screen recording's) is — 0.0 on average, to the last pixel.
+/// Whether a picture shows nothing: black all but a speck, as Apple's poster for a video whose
+/// first frame is black (a screen recording's, a film that fades in) is. A few bright pixels —
+/// a recording's status-bar dot, a JPEG's ringing at an edge — still read as black: at most
+/// one pixel in 200 may be lit.
#[must_use]
pub fn is_blank(bytes: &[u8]) -> bool {
let Ok(picture) = image::load_from_memory(bytes) else {
return false;
};
let gray = picture.to_luma8();
- let brightest = gray.pixels().map(|p| p.0[0]).max().unwrap_or(0);
- brightest < 24
+ let total = u64::from(gray.width()) * u64::from(gray.height());
+ if total == 0 {
+ return false;
+ }
+ let lit = gray.pixels().filter(|p| p.0[0] >= 24).count() as u64;
+ lit * 200 <= total
}
-/// A video's turn as its file records it: the picture track's matrix (QuickTime/MP4 `tkhd`) as
-/// `[a, b, c, d]`, each -1, 0 or 1, and where in the file the matrix's 36 bytes are. A phone
-/// records upright video sideways and says how to turn it here; the front camera's is also a
-/// mirror (`[0, 1, 1, 0]`). `None` for a file with no picture track or no such header.
-///
-/// # Errors
-/// When the file cannot be read.
-pub fn video_matrix(path: &std::path::Path) -> std::io::Result<Option<(u64, [i32; 4])>> {
+#[cfg(test)]
+mod blank_tests {
+ fn jpeg(w: u32, h: u32, lit: u32) -> Vec<u8> {
+ let mut img = image::GrayImage::new(w, h);
+ for i in 0..lit {
+ img.put_pixel(i % w, i / w, image::Luma([255]));
+ }
+ let mut out = Vec::new();
+ image::DynamicImage::ImageLuma8(img)
+ .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
+ .unwrap();
+ out
+ }
+
+ #[test]
+ fn black_with_a_speck_is_blank_and_a_picture_is_not() {
+ assert!(super::is_blank(&jpeg(100, 100, 0)));
+ assert!(super::is_blank(&jpeg(100, 100, 30)), "a status-bar dot");
+ assert!(
+ !super::is_blank(&jpeg(100, 100, 2000)),
+ "a dark picture with something in it"
+ );
+ }
+}
+
+/// The `moov` box of the film at `path`, wherever among the top-level boxes it is, and where
+/// it starts. `None` for a file with none (or one too large to be a film's tables).
+fn read_moov(path: &std::path::Path) -> std::io::Result<Option<(u64, Vec<u8>)>> {
use std::io::{Read, Seek, SeekFrom};
let mut file = std::fs::File::open(path)?;
let len = file.metadata()?.len();
// The `moov` box, wherever among the top-level boxes it is (after the film, often).
let mut at = 0u64;
- let (moov_at, moov) = loop {
+ let found = loop {
if at + 8 > len {
return Ok(None);
}
@@ -235,6 +261,63 @@ pub fn video_matrix(path: &std::path::Path) -> std::io::Result<Option<(u64, [i32
}
at += size;
};
+ Ok(Some(found))
+}
+
+/// How much larger a film's picture is than the part of it meant to be seen: a Live Photo's
+/// moving part is recorded with a margin round it (its `clap`, the clean aperture — 872 × 654 of
+/// a 960 × 720 picture in his library), and the still is that inner part. Drawn whole, the film
+/// showed a wider view than the still, smaller within it. 1.0 when the film says nothing of it.
+///
+/// # Errors
+/// When the file cannot be read.
+pub fn video_zoom(path: &std::path::Path) -> std::io::Result<f64> {
+ let Some((_, moov)) = read_moov(path)? else {
+ return Ok(1.0);
+ };
+ let u32_at = |i: usize| -> Option<u32> {
+ Some(u32::from_be_bytes(moov.get(i..i + 4)?.try_into().ok()?))
+ };
+ let Some(clap) = moov.windows(4).position(|w| w == b"clap") else {
+ return Ok(1.0);
+ };
+ // The picture's own width, from the sample entry the aperture belongs to.
+ let entry = moov[..clap]
+ .windows(4)
+ .rposition(|w| matches!(w, b"avc1" | b"avc3" | b"hvc1" | b"hev1"));
+ let (Some(entry), Some(wn), Some(wd)) = (entry, u32_at(clap + 4), u32_at(clap + 8)) else {
+ return Ok(1.0);
+ };
+ // Sample entry: size, type, 6 reserved, data reference (2), 16 pre-defined: then width.
+ let Some(width) = moov
+ .get(entry + 28..entry + 30)
+ .map(|b| f64::from(u16::from_be_bytes([b[0], b[1]])))
+ else {
+ return Ok(1.0);
+ };
+ if wd == 0 || wn == 0 {
+ return Ok(1.0);
+ }
+ let seen = f64::from(wn) / f64::from(wd);
+ let zoom = width / seen;
+ Ok(if (1.0..=1.5).contains(&zoom) {
+ zoom
+ } else {
+ 1.0
+ })
+}
+
+/// A video's turn as its file records it: the picture track's matrix (QuickTime/MP4 `tkhd`) as
+/// `[a, b, c, d]`, each -1, 0 or 1, and where in the file the matrix's 36 bytes are. A phone
+/// records upright video sideways and says how to turn it here; the front camera's is also a
+/// mirror (`[0, 1, 1, 0]`). `None` for a file with no picture track or no such header.
+///
+/// # Errors
+/// When the file cannot be read.
+pub fn video_matrix(path: &std::path::Path) -> std::io::Result<Option<(u64, [i32; 4])>> {
+ let Some((moov_at, moov)) = read_moov(path)? else {
+ return Ok(None);
+ };
let boxes = |from: usize, to: usize| {
let mut out = Vec::new();
let mut at = from;
@@ -772,3 +855,47 @@ mod tests {
assert!(avatar(b"", None, 64).is_err());
}
}
+
+#[cfg(test)]
+mod zoom_tests {
+ fn boxed(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
+ let mut out = u32::try_from(body.len() + 8)
+ .unwrap()
+ .to_be_bytes()
+ .to_vec();
+ out.extend_from_slice(kind);
+ out.extend_from_slice(body);
+ out
+ }
+
+ /// A Live Photo's film as Apple writes it: a 960 × 720 picture whose clean aperture is
+ /// 872 × 654. Drawn 960 / 872 larger, only what the still shows is seen.
+ #[test]
+ fn a_films_margin_is_read_from_its_clean_aperture() {
+ let mut clap = Vec::new();
+ for v in [872u32, 1, 654, 1, 0, 1, 0, 1] {
+ clap.extend_from_slice(&v.to_be_bytes());
+ }
+ let mut entry = vec![0u8; 24];
+ entry.extend_from_slice(&960u16.to_be_bytes());
+ entry.extend_from_slice(&720u16.to_be_bytes());
+ entry.extend_from_slice(&[0u8; 50]);
+ entry.extend(boxed(b"clap", &clap));
+ let moov = boxed(b"moov", &boxed(b"stsd", &boxed(b"avc1", &entry)));
+ let mut file = boxed(b"ftyp", b"qt \0\0\0\0");
+ file.extend(moov);
+ let dir = std::env::temp_dir().join(format!("quince-zoom-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("live.mov");
+ std::fs::write(&path, &file).unwrap();
+ let z = super::video_zoom(&path).unwrap();
+ assert!((z - 960.0 / 872.0).abs() < 1e-9, "{z}");
+ // No aperture said: drawn as it is.
+ let plain = dir.join("plain.mov");
+ let mut f = boxed(b"ftyp", b"qt \0\0\0\0");
+ f.extend(boxed(b"moov", &boxed(b"stsd", &[0u8; 16])));
+ std::fs::write(&plain, &f).unwrap();
+ assert!((super::video_zoom(&plain).unwrap() - 1.0).abs() < 1e-9);
+ std::fs::remove_dir_all(&dir).ok();
+ }
+}
diff --git a/docs/media/README.md b/docs/media/README.md
index 23b1785..9b227c3 100644
--- a/docs/media/README.md
+++ b/docs/media/README.md
@@ -1,79 +1,30 @@
# Media for the README
-Every image the top-level `README.md` shows lives in this folder. Until a file exists, its spot in the README shows a broken image, so capture these before the repository goes public.
-
-> [!IMPORTANT]
-> **Use a demo account only.** Every screenshot and clip uses synthetic data: invented notes, reminders, events, contacts and files. No real names, emails, phone numbers, account pictures, and nothing that identifies a person or a school, including in window titles, the tray, notifications and file paths. Check every frame of each GIF.
-
-## General settings
-
-- **Window size:** 1440 × 900 logical pixels (the app window, not the whole screen), captured at 2× scale, so files are **2880 × 1800**. Then export a copy scaled to **1440 × 900** and commit that one (keeps the repo small, still sharp on GitHub).
-- **Capture the window only,** with its own rounded corners and shadow, on a plain background. No desktop wallpaper or other apps, except where noted.
-- **Light and dark:** set the appearance in Settings → Appearance (Light / Dark), not by theme hacks.
-- **Format:** PNG for screenshots, optimised (`oxipng -o 4` or `pngquant --quality 80-95`). Aim for under 600 KB each.
-- **Cursor:** hidden in screenshots unless it explains something.
-- **Time and date:** a plausible weekday morning (for example 9:41), with the calendar on a week that has events.
-
-## Screenshots the README expects
-
-| File | App | Mode | What to show |
-|---|---|---|---|
-| `notes-light.png` | Notes | Light | A note with a heading, a checklist (some ticked), a small table and a picture. Folders in the sidebar, a few pinned notes in the list. |
-| `notes-dark.png` | Notes | Dark | Same scene. |
-| `reminders-light.png` | Reminders | Light | **Today** with 5–7 reminders: one with a subtask, one flagged, one with a due time, one priority. Lists with colours in the sidebar. |
-| `reminders-dark.png` | Reminders | Dark | Same scene. |
-| `calendar-light.png` | Calendar | Light | **Week** view with 8–12 events in three or four calendar colours, a reminder on the schedule, and a birthday. |
-| `calendar-dark.png` | Calendar | Dark | Same scene. |
-| `drive-light.png` | Drive | Light | Skykeep Drive in grid view with thumbnails, **beside** a file manager window (Nautilus or Dolphin) open on `~/iCloud Drive` showing the same files. Capture both windows together on a plain background. |
-| `drive-dark.png` | Drive | Dark | Same scene, file manager also in dark mode. |
-| `contacts-light.png` | Contacts | Light | A card with a (stock, licence-free or generated) photo, several phones/emails, an address and a birthday; lists in the sidebar. |
-| `photos-dark.png` | Photos | Dark | The library by month with a mix of photos, one video and one Live Photo badge. Use licence-free images. Labelled **preview** in the README. |
-| `settings-light.png` | Settings | Light | Account (demo name and generated avatar), storage bar, per-app sync times with Sync Now, appearance. This is the trust screenshot. |
-| `signin-light.png` | Sign-in | Light | The two-factor code step, showing the flow is Apple's own sign-in. Demo email only. |
-
-Optional, for later:
-
-| File | What |
-|---|---|
-| `logo-dark.png` | A dark-mode variant of the mark, if the transparent mark ever reads poorly on GitHub's dark theme. Swap it into the first `<source>` of the README hero. |
-| `windows-light.png` | Skykeep on Windows 11, once Windows leaves beta. |
-| `social-preview.png` | The 1280 × 640 social preview (see `docs/github-setup.md`). Kept here as the source; it's uploaded in GitHub's settings, not shown in the README. |
-
-## GIFs
-
-All GIFs: **under 8 seconds, looping, 1200 px wide (or less), under 5 MB**, 15–20 fps. Record as video first (OBS or `wf-recorder` at 60 fps), then convert:
+Every image the top-level `README.md` shows lives here. They are made from the real interface by `.uiverify/readme-shots.mjs`, on an invented demo library (`.uiverify/readme-fixture.mjs`) with drawn pictures (`.uiverify/readme-pictures.mjs`).
```sh
-ffmpeg -i in.mp4 -vf "fps=18,scale=1200:-1:flags=lanczos,split[a][b];[a]palettegen=stats_mode=diff[p];[b][p]paletteuse=dither=bayer:bayer_scale=4" -loop 0 out.gif
-gifsicle -O3 --lossy=60 out.gif -o out.gif
+node .uiverify/readme-shots.mjs # every still, plus the hero animation
+node .uiverify/readme-shots.mjs notes calendar # only those scenes
+PORT=4330 node .uiverify/readme-shots.mjs # preview on another port
```
-| File | Used where | What |
-|---|---|---|
-| `hero-sync.gif` | README hero (required) | The magic moment. Storyboard below. |
-| `offline.gif` | Optional, release notes | Wi-Fi off, edit a reminder, Wi-Fi on, it syncs; the pending indicator shows the state. |
-| `reminders.gif` | Optional, release notes | Tick a reminder, make a subtask with Tab, a desktop notification rings with Complete and Snooze. |
-| `drive-folder.gif` | Optional, release notes | Drag a file into `~/iCloud Drive` in the file manager; it appears in Files on the iPhone. |
-| `calendar-keys.gif` | Optional, release notes | Calendar driven by keys: Ctrl+Shift+T Go to Date, Ctrl+1–4 views, T for today. |
-
-### Hero GIF storyboard (`hero-sync.gif`, about 7 s)
+Needs ImageMagick and ffmpeg. PNGs are written 1600 px wide, stripped, and optimised with pngquant and oxipng when installed, or the same engines through `uv`.
-Real devices, no mockups: a real iPhone filmed on a tripod (or its screen mirrored), beside the desktop. Composite side by side: **iPhone on the left (about 30% of the width), Skykeep Notes on the right**, on a plain background, 1200 × 600.
+## Files
-| Time | Shot |
+| File | Shows |
|---|---|
-| 0.0–1.0 s | Both screens at rest. The same note ("Weekend plans") is open on the iPhone and in Skykeep, light mode. |
-| 1.0–3.0 s | On the iPhone, type a new checklist line: "Book the train". |
-| 3.0–4.0 s | About a second later, the line appears in Skykeep. No cut: one continuous take, so the timing is real. |
-| 4.0–5.5 s | In Skykeep, tick "Book the train". |
-| 5.5–6.5 s | The tick appears on the iPhone. |
-| 6.5–7.0 s | Brief hold, then loop. |
-
-Optional caption bar under the frame: *"Edit on your phone. See it here in a second."* Keep it out of the GIF if it makes the file too large; the README's alt text carries the message.
-
-## After capturing
-
-1. Put the files here with exactly the names above.
-2. Run the privacy check on every image: zoom in on sidebars, title bars, avatars and notifications.
-3. Strip metadata: `exiftool -all= -overwrite_original docs/media/*.png docs/media/*.gif`.
-4. Commit only this folder's media and this README (`git add docs/media`). The rest of `docs/` holds internal notes that are not meant for the public repository.
+| `notes-light.png`, `notes-dark.png` | A note with a picture, a checklist and a table |
+| `reminders-light.png`, `reminders-dark.png` | Today, with coloured lists, priorities and flags |
+| `calendar-light.png`, `calendar-dark.png` | A week with four calendars, reminders and a birthday |
+| `contacts-light.png`, `contacts-dark.png` | A full contact card and lists |
+| `drive-light.png`, `drive-dark.png` | A folder in grid view with thumbnails |
+| `photos-light.png`, `photos-dark.png` | The library by month, with a video and favourites |
+| `settings-light.png`, `settings-dark.png` | Account, storage and sync |
+| `signin-light.png`, `signin-dark.png` | Signing in with a demo Apple Account |
+
+## Rules for every image
+
+- **Demo data only.** Invented names, `example.com` emails and 555-01xx phone numbers. Nothing real from anyone's library, no school or workplace names.
+- **Pictures** are drawn by the harness, plus four Unsplash images from the harness's `UNSPLASH` list, resized with metadata stripped. Never a personal photo.
+- Look over every frame before committing: sidebars, avatars, toasts and window titles.
diff --git a/docs/media/calendar-dark.png b/docs/media/calendar-dark.png
new file mode 100644
index 0000000..a647ca7
Binary files /dev/null and b/docs/media/calendar-dark.png differ
diff --git a/docs/media/calendar-light.png b/docs/media/calendar-light.png
new file mode 100644
index 0000000..4a1fb71
Binary files /dev/null and b/docs/media/calendar-light.png differ
diff --git a/docs/media/contacts-dark.png b/docs/media/contacts-dark.png
new file mode 100644
index 0000000..7ac841a
Binary files /dev/null and b/docs/media/contacts-dark.png differ
diff --git a/docs/media/contacts-light.png b/docs/media/contacts-light.png
new file mode 100644
index 0000000..3c4ac87
Binary files /dev/null and b/docs/media/contacts-light.png differ
diff --git a/docs/media/drive-dark.png b/docs/media/drive-dark.png
new file mode 100644
index 0000000..ebaf4c7
Binary files /dev/null and b/docs/media/drive-dark.png differ
diff --git a/docs/media/drive-light.png b/docs/media/drive-light.png
new file mode 100644
index 0000000..1680757
Binary files /dev/null and b/docs/media/drive-light.png differ
diff --git a/docs/media/notes-dark.png b/docs/media/notes-dark.png
new file mode 100644
index 0000000..2dc499d
Binary files /dev/null and b/docs/media/notes-dark.png differ
diff --git a/docs/media/notes-light.png b/docs/media/notes-light.png
new file mode 100644
index 0000000..46e7108
Binary files /dev/null and b/docs/media/notes-light.png differ
diff --git a/docs/media/photos-dark.png b/docs/media/photos-dark.png
new file mode 100644
index 0000000..2419005
Binary files /dev/null and b/docs/media/photos-dark.png differ
diff --git a/docs/media/photos-light.png b/docs/media/photos-light.png
new file mode 100644
index 0000000..0394353
Binary files /dev/null and b/docs/media/photos-light.png differ
diff --git a/docs/media/reminders-dark.png b/docs/media/reminders-dark.png
new file mode 100644
index 0000000..2d62032
Binary files /dev/null and b/docs/media/reminders-dark.png differ
diff --git a/docs/media/reminders-light.png b/docs/media/reminders-light.png
new file mode 100644
index 0000000..532d3ba
Binary files /dev/null and b/docs/media/reminders-light.png differ
diff --git a/docs/media/settings-dark.png b/docs/media/settings-dark.png
new file mode 100644
index 0000000..5c7a863
Binary files /dev/null and b/docs/media/settings-dark.png differ
diff --git a/docs/media/settings-light.png b/docs/media/settings-light.png
new file mode 100644
index 0000000..6a9a0b8
Binary files /dev/null and b/docs/media/settings-light.png differ
diff --git a/docs/media/signin-dark.png b/docs/media/signin-dark.png
new file mode 100644
index 0000000..e711097
Binary files /dev/null and b/docs/media/signin-dark.png differ
diff --git a/docs/media/signin-light.png b/docs/media/signin-light.png
new file mode 100644
index 0000000..00dc1aa
Binary files /dev/null and b/docs/media/signin-light.png differ
diff --git a/packaging/arch/PKGBUILD b/packaging/arch/PKGBUILD
index d057ed4..3c7e3b4 100644
--- a/packaging/arch/PKGBUILD
+++ b/packaging/arch/PKGBUILD
@@ -18,16 +18,15 @@ license=('GPL-3.0-only')
# 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, libheif for HEIC photos (nothing
# else pulls it in: without it the app does not start; Arch's carries the libde265 decoder),
-# GStreamer for videos — 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.
+# GStreamer for videos. The tray needs no library: it is a StatusNotifierItem spoken over
+# D-Bus by the app itself (ksni), so libayatana-appindicator is no longer asked for.
# The GStreamer plugins are loaded at run time too, so ldd can't see them either. The window's
# player (playbin3) and the poster reader (poster.rs: decodebin, videoconvert, videoflip,
# appsink) need gst-plugins-base for the elements, gst-plugins-good for qtdemux (an iPhone's
# .mov/.mp4) and videoflip, and gst-libav for the H.264/HEVC decoders. Without them a video
# shows a black frame and won't play.
depends=('webkit2gtk-4.1' 'gtk3' 'libsecret' 'libheif' 'gstreamer' 'gst-plugins-base-libs'
- 'gst-plugins-base' 'gst-plugins-good' 'gst-libav' 'libayatana-appindicator')
+ 'gst-plugins-base' 'gst-plugins-good' 'gst-libav')
# The iCloud Drive and Photos folders are mounted through fusermount3.
optdepends=('fuse3: iCloud Drive and Photos as folders in the file manager')
makedepends=('rust' 'nodejs' 'npm' 'pkgconf')
@@ -92,15 +91,25 @@ package() {
> "$srcdir/io.github.yashwanthkamireddi.Skykeep.desktop"
install -Dm644 "$srcdir/io.github.yashwanthkamireddi.Skykeep.desktop" \
"$pkgdir/usr/share/applications/io.github.yashwanthkamireddi.Skykeep.desktop"
- install -Dm644 src-tauri/icons/icon.png \
- "$pkgdir/usr/share/icons/hicolor/512x512/apps/io.github.yashwanthkamireddi.Skykeep.png"
+ # The icon at every size the launchers and panels ask for, under the name they ask for.
+ local size src
+ for size in 16x16:16x16 24x24:24x24 32x32:32x32 48x48:48x48 64x64:64x64 128x128:128x128 \
+ 256x256:128x128@2x 512x512:icon; do
+ src=${size#*:}
+ install -Dm644 "src-tauri/icons/$src.png" \
+ "$pkgdir/usr/share/icons/hicolor/${size%%:*}/apps/io.github.yashwanthkamireddi.Skykeep.png"
+ done
# The six apps, each its own launcher entry (skykeep --app notes, …).
for entry in packaging/apps/*.desktop; do
install -Dm644 "$entry" "$pkgdir/usr/share/applications/$(basename "$entry")"
done
# In the desktop's own search: GNOME Shell's provider, KRunner's D-Bus plugin, and the bus
# entry that starts Skykeep hidden when either searches and it is not running.
- install -Dm644 packaging/io.github.yashwanthkamireddi.Skykeep.search-provider.ini \
+ # The provider names the .deb's launcher (Skykeep.desktop); here it is the app ID's.
+ sed 's|^DesktopId=Skykeep.desktop$|DesktopId=io.github.yashwanthkamireddi.Skykeep.desktop|' \
+ packaging/io.github.yashwanthkamireddi.Skykeep.search-provider.ini \
+ > "$srcdir/io.github.yashwanthkamireddi.Skykeep.search-provider.ini"
+ install -Dm644 "$srcdir/io.github.yashwanthkamireddi.Skykeep.search-provider.ini" \
"$pkgdir/usr/share/gnome-shell/search-providers/io.github.yashwanthkamireddi.Skykeep.search-provider.ini"
install -Dm644 packaging/io.github.yashwanthkamireddi.Skykeep.SearchProvider.service \
"$pkgdir/usr/share/dbus-1/services/io.github.yashwanthkamireddi.Skykeep.SearchProvider.service"
diff --git a/packaging/aur/PKGBUILD b/packaging/aur/PKGBUILD
index b249dfc..36c16bb 100644
--- a/packaging/aur/PKGBUILD
+++ b/packaging/aur/PKGBUILD
@@ -15,16 +15,15 @@ license=('GPL-3.0-only')
# 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, libheif for HEIC photos (nothing
# else pulls it in: without it the app does not start; Arch's carries the libde265 decoder),
-# GStreamer for videos — 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.
+# GStreamer for videos. The tray needs no library: it is a StatusNotifierItem spoken over
+# D-Bus by the app itself (ksni), so libayatana-appindicator is no longer asked for.
# The GStreamer plugins are loaded at run time too, so ldd can't see them either. The window's
# player (playbin3) and the poster reader (poster.rs: decodebin, videoconvert, videoflip,
# appsink) need gst-plugins-base for the elements, gst-plugins-good for qtdemux (an iPhone's
# .mov/.mp4) and videoflip, and gst-libav for the H.264/HEVC decoders. Without them a video
# shows a black frame and won't play.
depends=('webkit2gtk-4.1' 'gtk3' 'libsecret' 'libheif' 'gstreamer' 'gst-plugins-base-libs'
- 'gst-plugins-base' 'gst-plugins-good' 'gst-libav' 'libayatana-appindicator')
+ 'gst-plugins-base' 'gst-plugins-good' 'gst-libav')
# The iCloud Drive and Photos folders are mounted through fusermount3.
optdepends=('fuse3: iCloud Drive and Photos as folders in the file manager')
makedepends=('rust' 'nodejs' 'npm' 'pkgconf' 'git')
@@ -100,15 +99,25 @@ package() {
> "$srcdir/io.github.yashwanthkamireddi.Skykeep.desktop"
install -Dm644 "$srcdir/io.github.yashwanthkamireddi.Skykeep.desktop" \
"$pkgdir/usr/share/applications/io.github.yashwanthkamireddi.Skykeep.desktop"
- install -Dm644 src-tauri/icons/icon.png \
- "$pkgdir/usr/share/icons/hicolor/512x512/apps/io.github.yashwanthkamireddi.Skykeep.png"
+ # The icon at every size the launchers and panels ask for, under the name they ask for.
+ local size src
+ for size in 16x16:16x16 24x24:24x24 32x32:32x32 48x48:48x48 64x64:64x64 128x128:128x128 \
+ 256x256:128x128@2x 512x512:icon; do
+ src=${size#*:}
+ install -Dm644 "src-tauri/icons/$src.png" \
+ "$pkgdir/usr/share/icons/hicolor/${size%%:*}/apps/io.github.yashwanthkamireddi.Skykeep.png"
+ done
# The six apps, each its own launcher entry (skykeep --app notes, …).
for entry in packaging/apps/*.desktop; do
install -Dm644 "$entry" "$pkgdir/usr/share/applications/$(basename "$entry")"
done
# In the desktop's own search: GNOME Shell's provider, KRunner's D-Bus plugin, and the bus
# entry that starts Skykeep hidden when either searches and it is not running.
- install -Dm644 packaging/io.github.yashwanthkamireddi.Skykeep.search-provider.ini \
+ # The provider names the .deb's launcher (Skykeep.desktop); here it is the app ID's.
+ sed 's|^DesktopId=Skykeep.desktop$|DesktopId=io.github.yashwanthkamireddi.Skykeep.desktop|' \
+ packaging/io.github.yashwanthkamireddi.Skykeep.search-provider.ini \
+ > "$srcdir/io.github.yashwanthkamireddi.Skykeep.search-provider.ini"
+ install -Dm644 "$srcdir/io.github.yashwanthkamireddi.Skykeep.search-provider.ini" \
"$pkgdir/usr/share/gnome-shell/search-providers/io.github.yashwanthkamireddi.Skykeep.search-provider.ini"
install -Dm644 packaging/io.github.yashwanthkamireddi.Skykeep.SearchProvider.service \
"$pkgdir/usr/share/dbus-1/services/io.github.yashwanthkamireddi.Skykeep.SearchProvider.service"
diff --git a/packaging/flatpak/README.md b/packaging/flatpak/README.md
index 6749682..51834d8 100644
--- a/packaging/flatpak/README.md
+++ b/packaging/flatpak/README.md
@@ -30,7 +30,8 @@ lives under `~/.var/app/<id>/`), so a Flatpak starts with an empty library and f
plugin comes from `org.freedesktop.Platform.codecs-extra`, which the runtime downloads by itself.
HEIC decoding inside the sandbox is unverified.
- **fuse3**: not bundled. `fuser` is built with `default-features = false`, which links no libfuse.
-- **libayatana-appindicator** (tray): from Flathub's `shared-modules`.
+- **Tray**: no library. The app speaks StatusNotifierItem over D-Bus itself (`ksni`), without a
+ well-known bus name inside the sandbox.
## Permissions
@@ -96,13 +97,11 @@ flatpak install --user flathub org.gnome.Platform//51 org.gnome.Sdk//51 \
# (`flatpak info org.gnome.Sdk//51` shows it).
cd packaging/flatpak
-git clone --depth 1 https://github.com/flathub/shared-modules.git
-
flatpak-builder --user --install --force-clean build-dir io.github.yashwanthkamireddi.Skykeep.yml
flatpak run io.github.yashwanthkamireddi.Skykeep
```
-`build-dir/`, `.flatpak-builder/` and `shared-modules/` are build output. Don't commit them.
+`build-dir/` and `.flatpak-builder/` are build output. Don't commit them.
Lint before submitting:
diff --git a/packaging/flatpak/io.github.yashwanthkamireddi.Skykeep.yml b/packaging/flatpak/io.github.yashwanthkamireddi.Skykeep.yml
index 09210d3..40f8561 100644
--- a/packaging/flatpak/io.github.yashwanthkamireddi.Skykeep.yml
+++ b/packaging/flatpak/io.github.yashwanthkamireddi.Skykeep.yml
@@ -46,7 +46,7 @@ finish-args:
- --talk-name=org.freedesktop.secrets
# Reminder alerts (notify-rust, org.freedesktop.Notifications over D-Bus).
- --talk-name=org.freedesktop.Notifications
- # The tray icon (libayatana-appindicator, StatusNotifierItem).
+ # The tray icon (a StatusNotifierItem, spoken by the app over D-Bus).
- --talk-name=org.kde.StatusNotifierWatcher
# Files saved from Drive and Photos land in ~/Downloads: the app writes there directly
# (main.rs, photos.rs: download_dir()), not through the file-chooser portal, so without this
@@ -67,10 +67,8 @@ finish-args:
# - --system-talk-name=org.freedesktop.login1
modules:
- # The tray. libayatana-appindicator is not in the GNOME runtime; Flathub's shared module
- # builds it. Clone flathub/shared-modules here first (README, "Build locally"); in the
- # Flathub repository it is a git submodule at this path.
- - shared-modules/libayatana-appindicator/libayatana-appindicator-gtk3.json
+ # No tray library: the tray is a StatusNotifierItem the app speaks over D-Bus itself (ksni),
+ # registered with the host through --talk-name=org.kde.StatusNotifierWatcher above.
- name: skykeep
buildsystem: simple
@@ -116,14 +114,18 @@ modules:
# KRunner's D-Bus plugin, and the bus entry that starts Skykeep hidden to answer. The
# bus name is under the app ID, which the sandbox may own by default; Flatpak exports
# all three and rewrites the service's Exec to `flatpak run`.
- - install -Dm644 packaging/${FLATPAK_ID}.search-provider.ini ${FLATPAK_DEST}/share/gnome-shell/search-providers/${FLATPAK_ID}.search-provider.ini
+ # The provider names the .deb's launcher (Skykeep.desktop); here it is the app ID's.
+ - sed 's|^DesktopId=Skykeep.desktop$|DesktopId=${FLATPAK_ID}.desktop|' packaging/${FLATPAK_ID}.search-provider.ini > ${FLATPAK_ID}.search-provider.ini
+ - install -Dm644 ${FLATPAK_ID}.search-provider.ini ${FLATPAK_DEST}/share/gnome-shell/search-providers/${FLATPAK_ID}.search-provider.ini
- desktop-file-validate packaging/${FLATPAK_ID}.krunner.desktop
- install -Dm644 packaging/${FLATPAK_ID}.krunner.desktop ${FLATPAK_DEST}/share/krunner/dbusplugins/${FLATPAK_ID}.krunner.desktop
- sed 's|^Exec=/usr/bin/skykeep|Exec=${FLATPAK_DEST}/bin/skykeep|' packaging/${FLATPAK_ID}.SearchProvider.service > ${FLATPAK_ID}.SearchProvider.service
- install -Dm644 ${FLATPAK_ID}.SearchProvider.service ${FLATPAK_DEST}/share/dbus-1/services/${FLATPAK_ID}.SearchProvider.service
- # Icons: the vector original, and the rendered sizes.
- - install -Dm644 src-tauri/icons/icon.png ${FLATPAK_DEST}/share/icons/hicolor/512x512/apps/${FLATPAK_ID}.png
+ # Icons: the rendered sizes, 48x48 the one the icon theme spec asks every app for.
+ - install -Dm644 src-tauri/icons/16x16.png ${FLATPAK_DEST}/share/icons/hicolor/16x16/apps/${FLATPAK_ID}.png
+ - install -Dm644 src-tauri/icons/24x24.png ${FLATPAK_DEST}/share/icons/hicolor/24x24/apps/${FLATPAK_ID}.png
+ - install -Dm644 src-tauri/icons/48x48.png ${FLATPAK_DEST}/share/icons/hicolor/48x48/apps/${FLATPAK_ID}.png
- install -Dm644 src-tauri/icons/32x32.png ${FLATPAK_DEST}/share/icons/hicolor/32x32/apps/${FLATPAK_ID}.png
- install -Dm644 src-tauri/icons/64x64.png ${FLATPAK_DEST}/share/icons/hicolor/64x64/apps/${FLATPAK_ID}.png
- install -Dm644 src-tauri/icons/128x128.png ${FLATPAK_DEST}/share/icons/hicolor/128x128/apps/${FLATPAK_ID}.png
diff --git a/packaging/icons/skykeep-1024.png b/packaging/icons/skykeep-1024.png
index 8c7dd6c..f312c75 100644
Binary files a/packaging/icons/skykeep-1024.png and b/packaging/icons/skykeep-1024.png differ
diff --git a/packaging/icons/skykeep-tray.svg b/packaging/icons/skykeep-tray.svg
index 4872b8b..6f3c0fc 100644
--- a/packaging/icons/skykeep-tray.svg
+++ b/packaging/icons/skykeep-tray.svg
@@ -1 +1 @@
-<svg xmlns="http://www.w3.org/2000/svg" viewBox="-100 -100 1300 1300"><g transform="translate(74 70) scale(1.34)"><path d="M262 74C226 18 66 10 50 96C34 176 252 178 250 270C248 362 72 372 32 304" fill="none" stroke="#151A22" stroke-width="170.14925373134326" stroke-linecap="round" stroke-linejoin="round"/><path d="M262 74C226 18 66 10 50 96C34 176 252 178 250 270C248 362 72 372 32 304" fill="none" stroke="#EEF2F7" stroke-width="98.50746268656715" stroke-linecap="round" stroke-linejoin="round"/></g><g transform="translate(590 540)"><path d="M0 -176V332" fill="none" stroke="#151A22" stroke-width="228" stroke-linecap="round" stroke-linejoin="round"/><path d="M236 24L36 232" fill="none" stroke="#151A22" stroke-width="228" stroke-linecap="round" stroke-linejoin="round"/><path d="M104 168L246 332" fill="none" stroke="#151A22" stroke-width="228" stroke-linecap="round" stroke-linejoin="round"/><path d="M0 -176V332" fill="none" stroke="#2F9BFF" stroke-width="132" stroke-linecap="round" stroke-linejoin="round"/><path d="M236 24L36 232" fill="none" stroke="#2F9BFF" stroke-width="132" stroke-linecap="round" stroke-linejoin="round"/><path d="M104 168L246 332" fill="none" stroke="#2F9BFF" stroke-width="132" stroke-linecap="round" stroke-linejoin="round"/></g></svg>
\ No newline at end of file
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="-100 -100 1400 1400"><g transform="translate(74 70) scale(1.34)"><path d="M262 74C226 18 66 10 50 96C34 176 252 178 250 270C248 362 72 372 32 304" fill="none" stroke="#151A22" stroke-width="156.71641791044775" stroke-linecap="round" stroke-linejoin="round"/><path d="M262 74C226 18 66 10 50 96C34 176 252 178 250 270C248 362 72 372 32 304" fill="none" stroke="#EEF2F7" stroke-width="111.94029850746269" stroke-linecap="round" stroke-linejoin="round"/></g><g transform="translate(700 620)"><path d="M0 -176V332" fill="none" stroke="#151A22" stroke-width="210" stroke-linecap="round" stroke-linejoin="round"/><path d="M236 24L36 232" fill="none" stroke="#151A22" stroke-width="210" stroke-linecap="round" stroke-linejoin="round"/><path d="M104 168L246 332" fill="none" stroke="#151A22" stroke-width="210" stroke-linecap="round" stroke-linejoin="round"/><path d="M0 -176V332" fill="none" stroke="#2F9BFF" stroke-width="150" stroke-linecap="round" stroke-linejoin="round"/><path d="M236 24L36 232" fill="none" stroke="#2F9BFF" stroke-width="150" stroke-linecap="round" stroke-linejoin="round"/><path d="M104 168L246 332" fill="none" stroke="#2F9BFF" stroke-width="150" stroke-linecap="round" stroke-linejoin="round"/></g></svg>
\ No newline at end of file
diff --git a/packaging/icons/skykeep.svg b/packaging/icons/skykeep.svg
index d1b18b4..7631292 100644
--- a/packaging/icons/skykeep.svg
+++ b/packaging/icons/skykeep.svg
@@ -1 +1,3 @@
-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><circle cx="548" cy="508" r="400" fill="#2F9BFF"/><g transform="translate(74 70) scale(1.34)"><path d="M262 74C226 18 66 10 50 96C34 176 252 178 250 270C248 362 72 372 32 304" fill="none" stroke="#151A22" stroke-width="158.2089552238806" stroke-linecap="round" stroke-linejoin="round"/><path d="M262 74C226 18 66 10 50 96C34 176 252 178 250 270C248 362 72 372 32 304" fill="none" stroke="#EEF2F7" stroke-width="98.50746268656715" stroke-linecap="round" stroke-linejoin="round"/></g><g transform="translate(560 560)"><path d="M0 -176V332" fill="none" stroke="#EEF2F7" stroke-width="212" stroke-linecap="round" stroke-linejoin="round"/><path d="M236 24L36 232" fill="none" stroke="#EEF2F7" stroke-width="212" stroke-linecap="round" stroke-linejoin="round"/><path d="M104 168L246 332" fill="none" stroke="#EEF2F7" stroke-width="212" stroke-linecap="round" stroke-linejoin="round"/><path d="M0 -176V332" fill="none" stroke="#151A22" stroke-width="132" stroke-linecap="round" stroke-linejoin="round"/><path d="M236 24L36 232" fill="none" stroke="#151A22" stroke-width="132" stroke-linecap="round" stroke-linejoin="round"/><path d="M104 168L246 332" fill="none" stroke="#151A22" stroke-width="132" stroke-linecap="round" stroke-linejoin="round"/></g></svg>
\ No newline at end of file
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><defs><clipPath id="cb"><path d="M150.0 631.0 L149.8 636.0 L149.8 642.0 L150.0 646.8 L150.2 651.0 L150.8 657.0 L151.5 663.0 L152.5 669.0 L153.1 672.0 L154.4 678.0 L156.0 684.0 L156.9 687.0 L158.9 693.0 L160.0 696.0 L162.0 700.8 L163.9 705.0 L165.4 708.0 L168.0 712.9 L170.4 717.0 L172.3 720.0 L174.3 723.0 L177.0 726.8 L180.0 730.6 L183.0 734.2 L186.0 737.5 L189.0 740.5 L192.0 743.4 L195.0 746.0 L198.0 748.5 L201.0 750.8 L204.0 753.0 L208.6 756.0 L213.0 758.6 L216.0 760.2 L219.5 762.0 L225.0 764.4 L228.0 765.6 L234.0 767.7 L237.0 768.6 L243.0 770.1 L247.2 771.0 L252.0 771.8 L258.0 772.5 L264.0 772.9 L270.0 773.0 L276.0 773.0 L282.0 773.1 L288.0 773.1 L294.0 773.0 L300.0 773.0 L306.0 772.9 L312.0 772.8 L318.0 772.6 L324.0 772.5 L330.0 772.3 L336.0 772.2 L342.0 772.1 L348.0 772.0 L354.0 772.0 L360.0 772.0 L366.0 772.0 L372.0 772.0 L378.0 772.0 L384.0 772.0 L390.0 772.0 L396.0 772.0 L402.0 772.0 L408.0 772.0 L414.0 772.0 L420.0 772.0 L426.0 772.0 L432.0 772.0 L438.0 772.0 L444.0 772.0 L450.0 772.0 L456.0 772.0 L462.0 772.0 L468.0 772.0 L474.0 772.0 L480.0 772.0 L486.0 772.0 L492.0 772.0 L498.0 772.0 L504.0 772.0 L510.0 772.0 L516.0 772.0 L522.0 772.0 L528.0 772.0 L534.0 772.0 L540.0 772.0 L546.0 772.0 L552.0 772.0 L558.0 772.0 L564.0 772.0 L570.0 772.0 L576.0 772.0 L582.0 772.0 L588.0 772.0 L594.0 772.0 L600.0 772.0 L606.0 772.0 L612.0 772.0 L618.0 772.0 L624.0 772.0 L630.0 772.0 L636.0 772.0 L642.0 772.0 L648.0 772.0 L654.0 772.0 L660.0 772.0 L666.0 772.0 L672.0 772.0 L678.0 772.0 L684.0 772.0 L690.0 772.0 L696.0 772.0 L702.0 772.0 L708.0 772.0 L714.0 772.0 L720.0 772.0 L726.0 772.0 L732.0 772.0 L738.0 772.0 L744.0 772.0 L750.0 772.0 L756.0 772.0 L762.0 772.0 L768.0 772.0 L774.0 772.0 L780.0 772.0 L786.0 772.1 L792.0 772.1 L798.0 772.1 L804.0 772.0 L810.0 771.6 L814.4 771.0 L819.0 770.2 L825.0 769.0 L828.6 768.0 L834.0 766.3 L837.8 765.0 L843.0 762.9 L846.0 761.6 L851.2 759.0 L855.0 756.9 L858.0 755.1 L861.3 753.0 L865.7 750.0 L869.7 747.0 L873.0 744.3 L876.0 741.7 L879.0 738.9 L882.0 735.9 L885.0 732.8 L888.0 729.4 L890.8 726.0 L893.1 723.0 L895.3 720.0 L897.4 717.0 L900.0 712.9 L902.9 708.0 L904.5 705.0 L906.1 702.0 L908.9 696.0 L910.2 693.0 L912.0 688.5 L913.6 684.0 L915.0 679.6 L916.3 675.0 L917.8 669.0 L918.4 666.0 L919.4 660.0 L920.2 654.0 L920.6 648.0 L920.9 642.0 L920.8 636.0 L920.5 630.0 L919.9 624.0 L919.0 618.0 L918.0 612.8 L917.1 609.0 L915.5 603.0 L914.5 600.0 L912.3 594.0 L911.1 591.0 L909.0 586.4 L906.8 582.0 L905.2 579.0 L903.0 575.4 L900.0 570.8 L897.3 567.0 L895.0 564.0 L892.6 561.0 L890.0 558.0 L887.2 555.0 L884.3 552.0 L881.1 549.0 L877.8 546.0 L874.2 543.0 L870.5 540.0 L867.0 537.4 L864.0 535.2 L861.0 533.0 L858.0 530.9 L854.0 528.0 L849.9 525.0 L846.1 522.0 L843.0 519.2 L840.0 516.1 L837.5 513.0 L835.5 510.0 L833.8 507.0 L831.0 501.0 L829.9 498.0 L828.0 492.5 L827.0 489.0 L825.5 483.0 L824.8 480.0 L823.4 474.0 L822.0 468.6 L820.9 465.0 L819.0 459.1 L817.9 456.0 L816.0 451.2 L814.2 447.0 L812.8 444.0 L810.0 438.3 L808.2 435.0 L806.6 432.0 L804.0 427.7 L801.0 423.1 L798.9 420.0 L796.7 417.0 L794.5 414.0 L792.0 410.9 L789.0 407.3 L786.0 403.9 L783.0 400.8 L780.0 397.7 L777.0 394.9 L774.0 392.1 L771.0 389.6 L767.9 387.0 L764.0 384.0 L759.9 381.0 L756.0 378.4 L753.0 376.4 L750.0 374.6 L745.5 372.0 L741.0 369.6 L738.0 368.1 L733.4 366.0 L729.0 364.1 L726.0 362.9 L720.0 360.7 L717.0 359.7 L711.0 357.9 L707.7 357.0 L702.0 355.6 L696.0 354.5 L693.0 354.0 L687.0 353.1 L681.0 352.5 L675.0 352.1 L669.0 352.0 L663.0 352.1 L657.0 352.4 L651.0 352.6 L645.0 352.8 L639.0 352.7 L633.0 352.4 L627.0 351.7 L622.7 351.0 L618.0 350.0 L612.0 348.2 L609.0 347.1 L604.0 345.0 L600.0 343.0 L597.0 341.4 L593.1 339.0 L588.7 336.0 L585.0 333.4 L582.0 331.1 L579.0 328.7 L576.0 326.2 L573.0 323.8 L569.3 321.0 L565.2 318.0 L561.0 315.1 L558.0 313.1 L555.0 311.2 L551.3 309.0 L546.0 306.0 L543.0 304.4 L540.0 302.9 L534.0 300.0 L531.0 298.6 L527.2 297.0 L522.0 294.9 L519.0 293.8 L513.0 291.7 L510.0 290.8 L504.0 289.0 L500.1 288.0 L495.0 286.8 L489.0 285.5 L486.0 285.0 L480.0 284.0 L474.0 283.2 L468.0 282.6 L462.0 282.3 L456.0 282.0 L450.0 282.0 L444.0 282.2 L438.0 282.5 L432.0 283.0 L426.0 283.7 L420.0 284.6 L417.0 285.1 L411.0 286.3 L405.0 287.7 L402.0 288.5 L396.0 290.2 L393.0 291.1 L387.0 293.1 L384.0 294.2 L378.0 296.5 L375.0 297.8 L370.0 300.0 L366.0 301.9 L363.0 303.4 L358.0 306.0 L354.0 308.3 L351.0 310.0 L347.8 312.0 L343.2 315.0 L339.0 317.9 L336.0 320.0 L333.0 322.3 L330.0 324.6 L327.0 327.0 L323.5 330.0 L320.1 333.0 L316.9 336.0 L313.8 339.0 L310.9 342.0 L308.0 345.0 L305.3 348.0 L302.7 351.0 L300.0 354.3 L297.0 358.0 L294.0 362.0 L291.1 366.0 L289.1 369.0 L287.1 372.0 L285.0 375.4 L282.0 380.5 L280.0 384.0 L278.4 387.0 L276.0 391.8 L274.0 396.0 L272.6 399.0 L270.1 405.0 L268.9 408.0 L267.0 413.3 L265.7 417.0 L264.0 422.6 L263.0 426.0 L261.5 432.0 L260.8 435.0 L259.5 441.0 L258.2 447.0 L257.4 450.0 L255.7 456.0 L254.7 459.0 L252.3 465.0 L250.9 468.0 L249.0 471.6 L246.0 476.4 L243.4 480.0 L240.9 483.0 L238.1 486.0 L235.1 489.0 L231.8 492.0 L228.1 495.0 L225.0 497.5 L222.0 499.7 L219.0 501.9 L216.0 504.1 L211.8 507.0 L207.7 510.0 L204.0 512.9 L201.0 515.4 L198.0 518.1 L195.0 521.0 L192.0 524.1 L189.0 527.3 L186.0 530.9 L183.5 534.0 L181.3 537.0 L179.2 540.0 L177.0 543.3 L174.0 548.2 L171.8 552.0 L170.2 555.0 L168.0 559.4 L165.8 564.0 L164.5 567.0 L162.1 573.0 L160.9 576.0 L159.0 581.5 L157.9 585.0 L156.2 591.0 L155.4 594.0 L154.0 600.0 L153.0 605.0 L152.3 609.0 L151.4 615.0 L150.7 621.0 L150.2 627.0Z"/></clipPath></defs>
+<path d="M150.0 631.0 L149.8 636.0 L149.8 642.0 L150.0 646.8 L150.2 651.0 L150.8 657.0 L151.5 663.0 L152.5 669.0 L153.1 672.0 L154.4 678.0 L156.0 684.0 L156.9 687.0 L158.9 693.0 L160.0 696.0 L162.0 700.8 L163.9 705.0 L165.4 708.0 L168.0 712.9 L170.4 717.0 L172.3 720.0 L174.3 723.0 L177.0 726.8 L180.0 730.6 L183.0 734.2 L186.0 737.5 L189.0 740.5 L192.0 743.4 L195.0 746.0 L198.0 748.5 L201.0 750.8 L204.0 753.0 L208.6 756.0 L213.0 758.6 L216.0 760.2 L219.5 762.0 L225.0 764.4 L228.0 765.6 L234.0 767.7 L237.0 768.6 L243.0 770.1 L247.2 771.0 L252.0 771.8 L258.0 772.5 L264.0 772.9 L270.0 773.0 L276.0 773.0 L282.0 773.1 L288.0 773.1 L294.0 773.0 L300.0 773.0 L306.0 772.9 L312.0 772.8 L318.0 772.6 L324.0 772.5 L330.0 772.3 L336.0 772.2 L342.0 772.1 L348.0 772.0 L354.0 772.0 L360.0 772.0 L366.0 772.0 L372.0 772.0 L378.0 772.0 L384.0 772.0 L390.0 772.0 L396.0 772.0 L402.0 772.0 L408.0 772.0 L414.0 772.0 L420.0 772.0 L426.0 772.0 L432.0 772.0 L438.0 772.0 L444.0 772.0 L450.0 772.0 L456.0 772.0 L462.0 772.0 L468.0 772.0 L474.0 772.0 L480.0 772.0 L486.0 772.0 L492.0 772.0 L498.0 772.0 L504.0 772.0 L510.0 772.0 L516.0 772.0 L522.0 772.0 L528.0 772.0 L534.0 772.0 L540.0 772.0 L546.0 772.0 L552.0 772.0 L558.0 772.0 L564.0 772.0 L570.0 772.0 L576.0 772.0 L582.0 772.0 L588.0 772.0 L594.0 772.0 L600.0 772.0 L606.0 772.0 L612.0 772.0 L618.0 772.0 L624.0 772.0 L630.0 772.0 L636.0 772.0 L642.0 772.0 L648.0 772.0 L654.0 772.0 L660.0 772.0 L666.0 772.0 L672.0 772.0 L678.0 772.0 L684.0 772.0 L690.0 772.0 L696.0 772.0 L702.0 772.0 L708.0 772.0 L714.0 772.0 L720.0 772.0 L726.0 772.0 L732.0 772.0 L738.0 772.0 L744.0 772.0 L750.0 772.0 L756.0 772.0 L762.0 772.0 L768.0 772.0 L774.0 772.0 L780.0 772.0 L786.0 772.1 L792.0 772.1 L798.0 772.1 L804.0 772.0 L810.0 771.6 L814.4 771.0 L819.0 770.2 L825.0 769.0 L828.6 768.0 L834.0 766.3 L837.8 765.0 L843.0 762.9 L846.0 761.6 L851.2 759.0 L855.0 756.9 L858.0 755.1 L861.3 753.0 L865.7 750.0 L869.7 747.0 L873.0 744.3 L876.0 741.7 L879.0 738.9 L882.0 735.9 L885.0 732.8 L888.0 729.4 L890.8 726.0 L893.1 723.0 L895.3 720.0 L897.4 717.0 L900.0 712.9 L902.9 708.0 L904.5 705.0 L906.1 702.0 L908.9 696.0 L910.2 693.0 L912.0 688.5 L913.6 684.0 L915.0 679.6 L916.3 675.0 L917.8 669.0 L918.4 666.0 L919.4 660.0 L920.2 654.0 L920.6 648.0 L920.9 642.0 L920.8 636.0 L920.5 630.0 L919.9 624.0 L919.0 618.0 L918.0 612.8 L917.1 609.0 L915.5 603.0 L914.5 600.0 L912.3 594.0 L911.1 591.0 L909.0 586.4 L906.8 582.0 L905.2 579.0 L903.0 575.4 L900.0 570.8 L897.3 567.0 L895.0 564.0 L892.6 561.0 L890.0 558.0 L887.2 555.0 L884.3 552.0 L881.1 549.0 L877.8 546.0 L874.2 543.0 L870.5 540.0 L867.0 537.4 L864.0 535.2 L861.0 533.0 L858.0 530.9 L854.0 528.0 L849.9 525.0 L846.1 522.0 L843.0 519.2 L840.0 516.1 L837.5 513.0 L835.5 510.0 L833.8 507.0 L831.0 501.0 L829.9 498.0 L828.0 492.5 L827.0 489.0 L825.5 483.0 L824.8 480.0 L823.4 474.0 L822.0 468.6 L820.9 465.0 L819.0 459.1 L817.9 456.0 L816.0 451.2 L814.2 447.0 L812.8 444.0 L810.0 438.3 L808.2 435.0 L806.6 432.0 L804.0 427.7 L801.0 423.1 L798.9 420.0 L796.7 417.0 L794.5 414.0 L792.0 410.9 L789.0 407.3 L786.0 403.9 L783.0 400.8 L780.0 397.7 L777.0 394.9 L774.0 392.1 L771.0 389.6 L767.9 387.0 L764.0 384.0 L759.9 381.0 L756.0 378.4 L753.0 376.4 L750.0 374.6 L745.5 372.0 L741.0 369.6 L738.0 368.1 L733.4 366.0 L729.0 364.1 L726.0 362.9 L720.0 360.7 L717.0 359.7 L711.0 357.9 L707.7 357.0 L702.0 355.6 L696.0 354.5 L693.0 354.0 L687.0 353.1 L681.0 352.5 L675.0 352.1 L669.0 352.0 L663.0 352.1 L657.0 352.4 L651.0 352.6 L645.0 352.8 L639.0 352.7 L633.0 352.4 L627.0 351.7 L622.7 351.0 L618.0 350.0 L612.0 348.2 L609.0 347.1 L604.0 345.0 L600.0 343.0 L597.0 341.4 L593.1 339.0 L588.7 336.0 L585.0 333.4 L582.0 331.1 L579.0 328.7 L576.0 326.2 L573.0 323.8 L569.3 321.0 L565.2 318.0 L561.0 315.1 L558.0 313.1 L555.0 311.2 L551.3 309.0 L546.0 306.0 L543.0 304.4 L540.0 302.9 L534.0 300.0 L531.0 298.6 L527.2 297.0 L522.0 294.9 L519.0 293.8 L513.0 291.7 L510.0 290.8 L504.0 289.0 L500.1 288.0 L495.0 286.8 L489.0 285.5 L486.0 285.0 L480.0 284.0 L474.0 283.2 L468.0 282.6 L462.0 282.3 L456.0 282.0 L450.0 282.0 L444.0 282.2 L438.0 282.5 L432.0 283.0 L426.0 283.7 L420.0 284.6 L417.0 285.1 L411.0 286.3 L405.0 287.7 L402.0 288.5 L396.0 290.2 L393.0 291.1 L387.0 293.1 L384.0 294.2 L378.0 296.5 L375.0 297.8 L370.0 300.0 L366.0 301.9 L363.0 303.4 L358.0 306.0 L354.0 308.3 L351.0 310.0 L347.8 312.0 L343.2 315.0 L339.0 317.9 L336.0 320.0 L333.0 322.3 L330.0 324.6 L327.0 327.0 L323.5 330.0 L320.1 333.0 L316.9 336.0 L313.8 339.0 L310.9 342.0 L308.0 345.0 L305.3 348.0 L302.7 351.0 L300.0 354.3 L297.0 358.0 L294.0 362.0 L291.1 366.0 L289.1 369.0 L287.1 372.0 L285.0 375.4 L282.0 380.5 L280.0 384.0 L278.4 387.0 L276.0 391.8 L274.0 396.0 L272.6 399.0 L270.1 405.0 L268.9 408.0 L267.0 413.3 L265.7 417.0 L264.0 422.6 L263.0 426.0 L261.5 432.0 L260.8 435.0 L259.5 441.0 L258.2 447.0 L257.4 450.0 L255.7 456.0 L254.7 459.0 L252.3 465.0 L250.9 468.0 L249.0 471.6 L246.0 476.4 L243.4 480.0 L240.9 483.0 L238.1 486.0 L235.1 489.0 L231.8 492.0 L228.1 495.0 L225.0 497.5 L222.0 499.7 L219.0 501.9 L216.0 504.1 L211.8 507.0 L207.7 510.0 L204.0 512.9 L201.0 515.4 L198.0 518.1 L195.0 521.0 L192.0 524.1 L189.0 527.3 L186.0 530.9 L183.5 534.0 L181.3 537.0 L179.2 540.0 L177.0 543.3 L174.0 548.2 L171.8 552.0 L170.2 555.0 L168.0 559.4 L165.8 564.0 L164.5 567.0 L162.1 573.0 L160.9 576.0 L159.0 581.5 L157.9 585.0 L156.2 591.0 L155.4 594.0 L154.0 600.0 L153.0 605.0 L152.3 609.0 L151.4 615.0 L150.7 621.0 L150.2 627.0Z" fill="#1F7FE6"/>
+<g clip-path="url(#cb)"><path d="M150.0 631.0 L149.8 636.0 L149.8 642.0 L150.0 646.8 L150.2 651.0 L150.8 657.0 L151.5 663.0 L152.5 669.0 L153.1 672.0 L154.4 678.0 L156.0 684.0 L156.9 687.0 L158.9 693.0 L160.0 696.0 L162.0 700.8 L163.9 705.0 L165.4 708.0 L168.0 712.9 L170.4 717.0 L172.3 720.0 L174.3 723.0 L177.0 726.8 L180.0 730.6 L183.0 734.2 L186.0 737.5 L189.0 740.5 L192.0 743.4 L195.0 746.0 L198.0 748.5 L201.0 750.8 L204.0 753.0 L208.6 756.0 L213.0 758.6 L216.0 760.2 L219.5 762.0 L225.0 764.4 L228.0 765.6 L234.0 767.7 L237.0 768.6 L243.0 770.1 L247.2 771.0 L252.0 771.8 L258.0 772.5 L264.0 772.9 L270.0 773.0 L276.0 773.0 L282.0 773.1 L288.0 773.1 L294.0 773.0 L300.0 773.0 L306.0 772.9 L312.0 772.8 L318.0 772.6 L324.0 772.5 L330.0 772.3 L336.0 772.2 L342.0 772.1 L348.0 772.0 L354.0 772.0 L360.0 772.0 L366.0 772.0 L372.0 772.0 L378.0 772.0 L384.0 772.0 L390.0 772.0 L396.0 772.0 L402.0 772.0 L408.0 772.0 L414.0 772.0 L420.0 772.0 L426.0 772.0 L432.0 772.0 L438.0 772.0 L444.0 772.0 L450.0 772.0 L456.0 772.0 L462.0 772.0 L468.0 772.0 L474.0 772.0 L480.0 772.0 L486.0 772.0 L492.0 772.0 L498.0 772.0 L504.0 772.0 L510.0 772.0 L516.0 772.0 L522.0 772.0 L528.0 772.0 L534.0 772.0 L540.0 772.0 L546.0 772.0 L552.0 772.0 L558.0 772.0 L564.0 772.0 L570.0 772.0 L576.0 772.0 L582.0 772.0 L588.0 772.0 L594.0 772.0 L600.0 772.0 L606.0 772.0 L612.0 772.0 L618.0 772.0 L624.0 772.0 L630.0 772.0 L636.0 772.0 L642.0 772.0 L648.0 772.0 L654.0 772.0 L660.0 772.0 L666.0 772.0 L672.0 772.0 L678.0 772.0 L684.0 772.0 L690.0 772.0 L696.0 772.0 L702.0 772.0 L708.0 772.0 L714.0 772.0 L720.0 772.0 L726.0 772.0 L732.0 772.0 L738.0 772.0 L744.0 772.0 L750.0 772.0 L756.0 772.0 L762.0 772.0 L768.0 772.0 L774.0 772.0 L780.0 772.0 L786.0 772.1 L792.0 772.1 L798.0 772.1 L804.0 772.0 L810.0 771.6 L814.4 771.0 L819.0 770.2 L825.0 769.0 L828.6 768.0 L834.0 766.3 L837.8 765.0 L843.0 762.9 L846.0 761.6 L851.2 759.0 L855.0 756.9 L858.0 755.1 L861.3 753.0 L865.7 750.0 L869.7 747.0 L873.0 744.3 L876.0 741.7 L879.0 738.9 L882.0 735.9 L885.0 732.8 L888.0 729.4 L890.8 726.0 L893.1 723.0 L895.3 720.0 L897.4 717.0 L900.0 712.9 L902.9 708.0 L904.5 705.0 L906.1 702.0 L908.9 696.0 L910.2 693.0 L912.0 688.5 L913.6 684.0 L915.0 679.6 L916.3 675.0 L917.8 669.0 L918.4 666.0 L919.4 660.0 L920.2 654.0 L920.6 648.0 L920.9 642.0 L920.8 636.0 L920.5 630.0 L919.9 624.0 L919.0 618.0 L918.0 612.8 L917.1 609.0 L915.5 603.0 L914.5 600.0 L912.3 594.0 L911.1 591.0 L909.0 586.4 L906.8 582.0 L905.2 579.0 L903.0 575.4 L900.0 570.8 L897.3 567.0 L895.0 564.0 L892.6 561.0 L890.0 558.0 L887.2 555.0 L884.3 552.0 L881.1 549.0 L877.8 546.0 L874.2 543.0 L870.5 540.0 L867.0 537.4 L864.0 535.2 L861.0 533.0 L858.0 530.9 L854.0 528.0 L849.9 525.0 L846.1 522.0 L843.0 519.2 L840.0 516.1 L837.5 513.0 L835.5 510.0 L833.8 507.0 L831.0 501.0 L829.9 498.0 L828.0 492.5 L827.0 489.0 L825.5 483.0 L824.8 480.0 L823.4 474.0 L822.0 468.6 L820.9 465.0 L819.0 459.1 L817.9 456.0 L816.0 451.2 L814.2 447.0 L812.8 444.0 L810.0 438.3 L808.2 435.0 L806.6 432.0 L804.0 427.7 L801.0 423.1 L798.9 420.0 L796.7 417.0 L794.5 414.0 L792.0 410.9 L789.0 407.3 L786.0 403.9 L783.0 400.8 L780.0 397.7 L777.0 394.9 L774.0 392.1 L771.0 389.6 L767.9 387.0 L764.0 384.0 L759.9 381.0 L756.0 378.4 L753.0 376.4 L750.0 374.6 L745.5 372.0 L741.0 369.6 L738.0 368.1 L733.4 366.0 L729.0 364.1 L726.0 362.9 L720.0 360.7 L717.0 359.7 L711.0 357.9 L707.7 357.0 L702.0 355.6 L696.0 354.5 L693.0 354.0 L687.0 353.1 L681.0 352.5 L675.0 352.1 L669.0 352.0 L663.0 352.1 L657.0 352.4 L651.0 352.6 L645.0 352.8 L639.0 352.7 L633.0 352.4 L627.0 351.7 L622.7 351.0 L618.0 350.0 L612.0 348.2 L609.0 347.1 L604.0 345.0 L600.0 343.0 L597.0 341.4 L593.1 339.0 L588.7 336.0 L585.0 333.4 L582.0 331.1 L579.0 328.7 L576.0 326.2 L573.0 323.8 L569.3 321.0 L565.2 318.0 L561.0 315.1 L558.0 313.1 L555.0 311.2 L551.3 309.0 L546.0 306.0 L543.0 304.4 L540.0 302.9 L534.0 300.0 L531.0 298.6 L527.2 297.0 L522.0 294.9 L519.0 293.8 L513.0 291.7 L510.0 290.8 L504.0 289.0 L500.1 288.0 L495.0 286.8 L489.0 285.5 L486.0 285.0 L480.0 284.0 L474.0 283.2 L468.0 282.6 L462.0 282.3 L456.0 282.0 L450.0 282.0 L444.0 282.2 L438.0 282.5 L432.0 283.0 L426.0 283.7 L420.0 284.6 L417.0 285.1 L411.0 286.3 L405.0 287.7 L402.0 288.5 L396.0 290.2 L393.0 291.1 L387.0 293.1 L384.0 294.2 L378.0 296.5 L375.0 297.8 L370.0 300.0 L366.0 301.9 L363.0 303.4 L358.0 306.0 L354.0 308.3 L351.0 310.0 L347.8 312.0 L343.2 315.0 L339.0 317.9 L336.0 320.0 L333.0 322.3 L330.0 324.6 L327.0 327.0 L323.5 330.0 L320.1 333.0 L316.9 336.0 L313.8 339.0 L310.9 342.0 L308.0 345.0 L305.3 348.0 L302.7 351.0 L300.0 354.3 L297.0 358.0 L294.0 362.0 L291.1 366.0 L289.1 369.0 L287.1 372.0 L285.0 375.4 L282.0 380.5 L280.0 384.0 L278.4 387.0 L276.0 391.8 L274.0 396.0 L272.6 399.0 L270.1 405.0 L268.9 408.0 L267.0 413.3 L265.7 417.0 L264.0 422.6 L263.0 426.0 L261.5 432.0 L260.8 435.0 L259.5 441.0 L258.2 447.0 L257.4 450.0 L255.7 456.0 L254.7 459.0 L252.3 465.0 L250.9 468.0 L249.0 471.6 L246.0 476.4 L243.4 480.0 L240.9 483.0 L238.1 486.0 L235.1 489.0 L231.8 492.0 L228.1 495.0 L225.0 497.5 L222.0 499.7 L219.0 501.9 L216.0 504.1 L211.8 507.0 L207.7 510.0 L204.0 512.9 L201.0 515.4 L198.0 518.1 L195.0 521.0 L192.0 524.1 L189.0 527.3 L186.0 530.9 L183.5 534.0 L181.3 537.0 L179.2 540.0 L177.0 543.3 L174.0 548.2 L171.8 552.0 L170.2 555.0 L168.0 559.4 L165.8 564.0 L164.5 567.0 L162.1 573.0 L160.9 576.0 L159.0 581.5 L157.9 585.0 L156.2 591.0 L155.4 594.0 L154.0 600.0 L153.0 605.0 L152.3 609.0 L151.4 615.0 L150.7 621.0 L150.2 627.0Z" fill="#2F9BFF" transform="translate(0 -26)"/><path d="M171.0 585.9 L170.6 591.0 L170.3 597.0 L170.3 603.0 L170.6 609.0 L171.0 613.9 L171.4 618.0 L172.3 624.0 L174.0 629.9 L175.1 633.0 L177.0 637.9 L178.8 642.0 L180.3 645.0 L183.0 650.0 L185.4 654.0 L187.5 657.0 L189.6 660.0 L192.0 663.1 L195.0 666.6 L198.0 669.9 L201.0 672.9 L204.0 675.6 L207.0 678.2 L210.6 681.0 L214.9 684.0 L219.0 686.6 L222.0 688.4 L225.1 690.0 L231.0 692.8 L234.0 694.0 L239.5 696.0 L243.0 697.1 L249.0 698.6 L252.0 699.2 L258.0 700.1 L264.0 700.7 L270.0 700.9 L276.0 700.9 L282.0 700.6 L288.0 700.3 L294.0 699.7 L300.0 699.0 L303.0 698.6 L309.0 697.8 L315.0 696.8 L319.7 696.0 L324.0 695.3 L330.0 694.2 L336.0 693.2 L339.0 692.8 L345.0 691.9 L351.0 691.1 L357.0 690.6 L363.0 690.2 L369.0 690.0 L372.0 690.0 L366.0 690.1 L360.0 690.4 L354.0 690.8 L348.0 691.5 L342.0 692.3 L337.5 693.0 L333.0 693.7 L327.0 694.8 L321.0 695.8 L318.0 696.3 L312.0 697.3 L306.0 698.2 L300.1 699.0 L297.0 699.4 L291.0 700.0 L285.0 700.5 L279.0 700.8 L273.0 700.9 L267.0 700.9 L261.0 700.5 L255.0 699.7 L251.0 699.0 L246.0 697.9 L240.0 696.2 L237.0 695.1 L231.5 693.0 L228.0 691.4 L225.0 690.0 L219.6 687.0 L216.0 684.8 L213.0 682.7 L210.0 680.5 L206.8 678.0 L203.3 675.0 L200.1 672.0 L197.2 669.0 L194.4 666.0 L191.9 663.0 L189.0 659.2 L186.0 654.8 L183.6 651.0 L181.9 648.0 L180.0 644.4 L177.4 639.0 L176.2 636.0 L174.0 630.0 L173.1 627.0 L171.9 621.0 L171.1 615.0 L170.8 612.0 L170.4 606.0 L170.3 600.0 L170.4 594.0 L170.8 588.0Z" fill="#63B6FF"/></g><g transform="translate(530 590) scale(.70) translate(-450 -470)"><g transform="translate(74 70) scale(1.34)"><path d="M262 74C226 18 66 10 50 96C34 176 252 178 250 270C248 362 72 372 32 304" fill="none" stroke="#151A22" stroke-width="158.2089552238806" stroke-linecap="round" stroke-linejoin="round"/><path d="M262 74C226 18 66 10 50 96C34 176 252 178 250 270C248 362 72 372 32 304" fill="none" stroke="#EEF2F7" stroke-width="98.50746268656715" stroke-linecap="round" stroke-linejoin="round"/></g><g transform="translate(560 560)"><path d="M0 -176V332" fill="none" stroke="#EEF2F7" stroke-width="212" stroke-linecap="round" stroke-linejoin="round"/><path d="M236 24L36 232" fill="none" stroke="#EEF2F7" stroke-width="212" stroke-linecap="round" stroke-linejoin="round"/><path d="M104 168L246 332" fill="none" stroke="#EEF2F7" stroke-width="212" stroke-linecap="round" stroke-linejoin="round"/><path d="M0 -176V332" fill="none" stroke="#151A22" stroke-width="132" stroke-linecap="round" stroke-linejoin="round"/><path d="M236 24L36 232" fill="none" stroke="#151A22" stroke-width="132" stroke-linecap="round" stroke-linejoin="round"/><path d="M104 168L246 332" fill="none" stroke="#151A22" stroke-width="132" stroke-linecap="round" stroke-linejoin="round"/></g></g></svg>
\ No newline at end of file
diff --git a/packaging/io.github.yashwanthkamireddi.Skykeep.search-provider.ini b/packaging/io.github.yashwanthkamireddi.Skykeep.search-provider.ini
index 0ce3db9..9169c26 100644
--- a/packaging/io.github.yashwanthkamireddi.Skykeep.search-provider.ini
+++ b/packaging/io.github.yashwanthkamireddi.Skykeep.search-provider.ini
@@ -1,8 +1,11 @@
# GNOME Shell's search provider: what is typed in the Activities overview is asked of Skykeep
# too (src-tauri/src/search_provider.rs). Installed to /usr/share/gnome-shell/search-providers/.
# BusName starts Skykeep hidden if it is not running (the .SearchProvider.service beside this).
+# DesktopId names the launcher the .deb, .rpm and AppImage install (Tauri's Skykeep.desktop);
+# GNOME Shell drops a provider whose DesktopId is not an installed app. The Arch packages and
+# the Flatpak install the launcher under the app ID and rewrite this line to match.
[Shell Search Provider]
-DesktopId=io.github.yashwanthkamireddi.Skykeep.desktop
+DesktopId=Skykeep.desktop
BusName=io.github.yashwanthkamireddi.Skykeep.SearchProvider
ObjectPath=/io/github/yashwanthkamireddi/Skykeep/SearchProvider
Version=2
diff --git a/packaging/linux-compat/check.sh b/packaging/linux-compat/check.sh
new file mode 100644
index 0000000..1272074
--- /dev/null
+++ b/packaging/linux-compat/check.sh
@@ -0,0 +1,225 @@
+#!/bin/bash
+# Does Skykeep install and run on this distribution? Run as root in a clean container of it:
+#
+# check.sh <package> <distro_check> <test.heic>
+#
+# <package> a .deb, .rpm, .pkg.tar.zst or .AppImage — installed with the system's own
+# package manager (the .AppImage is only run), with recommends/weak
+# dependencies off, so only what the package itself asks for is there;
+# <distro_check> the probe's distro_check example (probe/examples/distro_check.rs);
+# <test.heic> a HEIC made for the test — never anybody's photo.
+#
+# Checked, each on its own line, PASS or FAIL:
+# ldd the program finds every library it links;
+# gst the GStreamer elements the player and poster reader load at run time are there;
+# heic a HEIC decodes through the system's libheif, the app's own way;
+# keyring a made-up session goes into a Secret Service (gnome-keyring) and back out
+# through the app's sign-in storage;
+# launch started headless under Xvfb on its own session bus, the page draws
+# (window_ready) and the program is still running 8 s later — with --background,
+# as the main launcher starts it, and as one app's launcher does (--app notes);
+# relaunch with no tray to click, launching again hands over to the running Skykeep and
+# its window shows;
+# desktop the launchers and the metainfo validate, the icon is in hicolor under the name
+# the launchers ask for (packages only).
+# Used by .github/workflows/linux-compat.yml, and runs the same by hand under docker.
+set -u
+pkg=$1 probe=$2 heic=$3
+. /etc/os-release
+like=" ${ID} ${ID_LIKE:-} "
+fails=0
+pass() { echo "PASS $1${2:+ — $2}"; }
+fail() { echo "FAIL $1${2:+ — $2}"; fails=$((fails + 1)); }
+
+# --- The test's own tools (never the app's dependencies: those come from the package) -------
+case "$like" in
+ *" debian "* | *" ubuntu "*)
+ export DEBIAN_FRONTEND=noninteractive
+ apt-get update -qq
+ tools="xvfb xauth dbus gnome-keyring gstreamer1.0-tools desktop-file-utils appstream"
+ # An AppImage carries its libraries but not the ones every desktop has (excludelist).
+ [[ $pkg == *.AppImage ]] && tools+=" libgl1 libegl1 libfontconfig1 fonts-dejavu-core"
+ # shellcheck disable=SC2086
+ apt-get install -y -qq --no-install-recommends $tools >/dev/null
+ [[ $pkg == *.deb ]] && { apt-get install -y -q --no-install-recommends "$pkg" || exit 1; }
+ ;;
+ *" fedora "*)
+ tools="xorg-x11-server-Xvfb xorg-x11-xauth dbus-daemon gnome-keyring gstreamer1 \
+ desktop-file-utils appstream which"
+ [[ $pkg == *.AppImage ]] && tools+=" mesa-libGL mesa-libEGL fontconfig dejavu-sans-fonts"
+ # shellcheck disable=SC2086
+ dnf -y -q install --setopt=install_weak_deps=False $tools
+ [[ $pkg == *.rpm ]] && { dnf -y install --setopt=install_weak_deps=False "$pkg" || exit 1; }
+ ;;
+ *" suse "* | *" opensuse "*)
+ tools="xvfb-run dbus-1 gnome-keyring gstreamer-utils desktop-file-utils AppStream which"
+ [[ $pkg == *.AppImage ]] && tools+=" Mesa-libGL1 Mesa-libEGL1 fontconfig dejavu-fonts"
+ # shellcheck disable=SC2086
+ zypper -q --non-interactive install --no-recommends $tools
+ [[ $pkg == *.rpm ]] && {
+ zypper --non-interactive install --no-recommends --allow-unsigned-rpm "$pkg" || exit 1
+ }
+ ;;
+ *" arch "*)
+ pacman -Syu --noconfirm --needed -q xorg-server-xvfb xorg-xauth dbus gnome-keyring \
+ gstreamer desktop-file-utils appstream which >/dev/null
+ [[ $pkg == *.pkg.tar.* ]] && { pacman -U --noconfirm "$pkg" || exit 1; }
+ ;;
+ *) echo "no installer for $ID"; exit 2 ;;
+esac
+command -v xvfb-run >/dev/null || { echo "no xvfb-run on $ID"; exit 2; }
+
+# --- Where the program is ---------------------------------------------------------------------
+if [[ $pkg == *.AppImage ]]; then
+ chmod +x "$pkg"
+ # No FUSE in a container: unpacked once and run from there, as --appimage-extract-and-run
+ # does, so ldd can look at what it carries.
+ cd /tmp && "$pkg" --appimage-extract >/dev/null && cd - >/dev/null || exit 1
+ root=/tmp/squashfs-root
+ prog="$root/AppRun"
+ bin="$root/usr/bin/skykeep"
+ libs="$root/usr/lib:$root/usr/lib/x86_64-linux-gnu"
+else
+ prog=/usr/bin/skykeep bin=/usr/bin/skykeep libs=
+fi
+[[ -x $bin ]] || { echo "FAIL install — no $bin"; exit 1; }
+echo "== $PRETTY_NAME — $(basename "$pkg")"
+
+# --- ldd ------------------------------------------------------------------------------------
+missing=$(LD_LIBRARY_PATH=$libs ldd "$bin" | grep "not found")
+[[ -z $missing ]] && pass ldd || fail ldd "$missing"
+
+# --- GStreamer elements (the package's, or the AppImage's own) ------------------------------
+# playbin3/decodebin/videoconvert/appsink: gst-plugins-base; qtdemux, videoflip: -good;
+# avdec_h264 / avdec_h265: gst-libav — an iPhone's .mov/.mp4 and its H.264/HEVC video.
+if [[ $pkg == *.AppImage ]]; then
+ gstdir=$(find "$root" -type d -name gstreamer-1.0 -path '*lib*' | head -1)
+ # As the AppImage's own GStreamer hook sets it up: its plugins, its scanner, a registry of
+ # its own — and its libraries (libavcodec for gst-libav) found the way its AppRun finds them.
+ export GST_PLUGIN_SYSTEM_PATH_1_0=$gstdir GST_PLUGIN_PATH_1_0= GST_REGISTRY_1_0=/tmp/appimage-registry.bin
+ scanner=$(find "$root" -type f -name gst-plugin-scanner | head -1)
+ [[ -n $scanner ]] && export GST_PLUGIN_SCANNER_1_0=$scanner
+fi
+media() {
+ local absent= e
+ for e in playbin3 decodebin videoconvert videoflip appsink qtdemux "avdec_h264|openh264dec" \
+ avdec_h265; do
+ LD_LIBRARY_PATH=$libs gst-inspect-1.0 "${e%%|*}" >/dev/null 2>&1 || { [[ $e == *"|"* ]] &&
+ LD_LIBRARY_PATH=$libs gst-inspect-1.0 "${e##*|}" >/dev/null 2>&1; } || absent+=" $e"
+ done
+ [[ -z $absent ]] && pass gst || $1 gst "missing:$absent"
+ if out=$(LD_LIBRARY_PATH=$libs "$probe" heic "$heic" 2>&1); then pass heic "$out"
+ else $1 heic "$out"; fi
+}
+# Fedora leaves HEVC out of its own repositories — libheif without its libde265 decoder, FFmpeg
+# without H.265 — so an iPhone's HEIC photos and HEVC videos need RPM Fusion there (the
+# README's Fedora and openSUSE note). Without it, those two are noted, not failed; then RPM
+# Fusion is added exactly as the README says, and with it both must pass.
+# openSUSE is the same: no libde265 and an FFmpeg without HEVC in its own repositories; H.264
+# comes from the openh264 repository it has enabled out of the box, HEVC from Packman.
+known() { echo "KNOWN $1 — ${2} (no HEVC decoder in $NAME's own repositories)"; }
+if [[ $like == *" fedora "* && $pkg != *.AppImage ]]; then
+ media known
+ rel=$(rpm -E %fedora)
+ # RPM Fusion's own instructions (rpmfusion.org/Howto/Multimedia): the full FFmpeg in place of
+ # ffmpeg-free, and libheif's HEVC decoder. ffmpeg-libs alone did not give gst-libav H.264.
+ dnf -y -q install "https://mirrors.rpmfusion.org/free/fedora/rpmfusion-free-release-$rel.noarch.rpm" &&
+ dnf -y -q swap ffmpeg-free ffmpeg --allowerasing &&
+ dnf -y -q install --setopt=install_weak_deps=False libheif-freeworld ||
+ fail rpmfusion "could not be added"
+ echo "-- with RPM Fusion:"
+ # GStreamer's registry remembers gst-libav with ffmpeg-free's decoders; read it afresh.
+ rm -rf "${XDG_CACHE_HOME:-$HOME/.cache}/gstreamer-1.0"
+ media fail
+elif [[ $like == *" suse "* && $pkg != *.AppImage ]]; then
+ media known
+ # Packman's FFmpeg and libheif, as Packman's own instructions put them in place.
+ zypper -q --non-interactive ar -cfp 90 \
+ "https://ftp.gwdg.de/pub/linux/misc/packman/suse/openSUSE_Tumbleweed/" packman &&
+ zypper -q --non-interactive --gpg-auto-import-keys refresh packman &&
+ zypper -q --non-interactive install --no-recommends --allow-vendor-change --from packman \
+ libavcodec62 libheif1 libde265-0 $(zypper -q se -r packman -x libheif-de265 >/dev/null 2>&1 && echo libheif-de265) ||
+ fail packman "could not be added"
+ echo "-- with Packman:"
+ rm -rf "${XDG_CACHE_HOME:-$HOME/.cache}/gstreamer-1.0"
+ media fail
+else
+ media fail
+fi
+unset GST_PLUGIN_SYSTEM_PATH_1_0 GST_PLUGIN_PATH_1_0
+
+# --- Keyring and launch, in one session bus with a keyring daemon on it ---------------------
+export HOME=$(mktemp -d) XDG_RUNTIME_DIR=$(mktemp -d) RUST_BACKTRACE=1 SKYKEEP_TIMING=1
+chmod 700 "$XDG_RUNTIME_DIR"
+cat >/tmp/session.sh <<'SH'
+#!/bin/bash
+# Inside dbus-run-session: a gnome-keyring with an unlocked login keyring (a throwaway
+# password), then the keyring check and the two launches.
+probe=$1 prog=$2 libs=$3
+echo -n throwaway | gnome-keyring-daemon --unlock --components=secrets >/dev/null 2>&1
+if out=$(LD_LIBRARY_PATH=$libs "$probe" keyring 2>&1); then echo "PASS keyring — $out"
+else echo "FAIL keyring — $out"; fi
+for how in --background launcher "--app notes"; do
+ log=$(mktemp)
+ # shellcheck disable=SC2206
+ args=(); [[ $how == --* ]] && args=($how)
+ window=main; [[ $how == "--app notes" ]] && window=app-notes
+ timeout --kill-after=5 8 xvfb-run -a -s "-screen 0 1280x800x24" "$prog" "${args[@]}" >"$log" 2>&1
+ rc=$?
+ drawn=$(grep -m1 -o "+[0-9.]*ms window_ready $window" "$log")
+ if [[ $rc -eq 124 && -n $drawn ]] && ! grep -q 'panicked at' "$log"; then
+ echo "PASS launch ($how) — page drawn at ${drawn%% *}, still running at 8 s"
+ else
+ echo "FAIL launch ($how) — exit $rc, drawn: ${drawn:-never}"; grep -v skykeep-timing "$log" | tail -20
+ fi
+done
+# Reachable with no tray to click (stock GNOME, and this container): launched again, as from
+# the launcher, the second process hands over to the running one and leaves; that one shows
+# its window.
+log=$(mktemp)
+timeout --kill-after=5 16 xvfb-run -a -s "-screen 0 1280x800x24" bash -c \
+ '"$0" --background & sleep 6; timeout 6 "$0"; echo "second launch exited $?"; sleep 2' \
+ "$prog" >"$log" 2>&1
+if grep -q 'second launch exited 0' "$log" && grep -q 'handed a launch' "$log" &&
+ grep -q 'main shown' "$log"; then
+ echo "PASS relaunch — a second launch reopened the running one's window"
+else
+ echo "FAIL relaunch"; grep -v skykeep-timing "$log" | tail -20
+fi
+SH
+chmod +x /tmp/session.sh
+results=$(dbus-run-session -- /tmp/session.sh "$probe" "$prog" "$libs")
+echo "$results"
+fails=$((fails + $(grep -c '^FAIL' <<<"$results")))
+
+# --- Desktop integration (packages) ---------------------------------------------------------
+if [[ $pkg != *.AppImage ]]; then
+ apps=/usr/share/applications
+ problems=
+ for f in "$apps"/*Skykeep*.desktop "$apps"/skykeep*.desktop; do
+ [[ -e $f ]] || continue
+ m=$(desktop-file-validate "$f" 2>&1 | grep -v 'hint:')
+ [[ -z $m ]] || problems+=" $(basename "$f"): $m"
+ icon=$(sed -n 's/^Icon=//p' "$f" | head -1)
+ sizes=$(find /usr/share/icons/hicolor -name "$icon.png" -o -name "$icon.svg" | wc -l)
+ [[ $sizes -gt 0 ]] || problems+=" $(basename "$f"): no hicolor icon '$icon'"
+ # The icon theme spec's one requirement of an app: a 48x48 in hicolor (or a scalable one).
+ [[ -e /usr/share/icons/hicolor/48x48/apps/$icon.png ||
+ -e /usr/share/icons/hicolor/scalable/apps/$icon.svg ]] ||
+ problems+=" $(basename "$f"): no 48x48 hicolor icon '$icon'"
+ done
+ m=$(appstreamcli validate --no-net --explain /usr/share/metainfo/*Skykeep*.xml 2>&1) ||
+ problems+=" metainfo: $(grep -E '^[EW]:' <<<"$m" | tr '\n' ' ')"
+ launchable=$(sed -n 's:.*<launchable type="desktop-id">\(.*\)</launchable>.*:\1:p' /usr/share/metainfo/*Skykeep*.xml)
+ [[ -e $apps/$launchable ]] || problems+=" metainfo launchable $launchable not installed"
+ # GNOME Shell drops a search provider whose DesktopId is not an installed launcher.
+ for ini in /usr/share/gnome-shell/search-providers/*Skykeep*.ini; do
+ id=$(sed -n 's/^DesktopId=//p' "$ini")
+ [[ -e $apps/$id ]] || problems+=" search provider DesktopId $id not installed"
+ done
+ icons=$(find /usr/share/icons/hicolor -path '*apps*' \( -iname '*skykeep*' \) | sed 's:/usr/share/icons/hicolor/::' | tr '\n' ' ')
+ [[ -z $problems ]] && pass desktop "icons: $icons" || fail desktop "$problems"
+fi
+
+echo "== $fails failed"
+exit $((fails > 0))
diff --git a/probe/examples/distro_check.rs b/probe/examples/distro_check.rs
new file mode 100644
index 0000000..20a4875
--- /dev/null
+++ b/probe/examples/distro_check.rs
@@ -0,0 +1,61 @@
+//! What an installed Skykeep needs from the distribution it is on, checked through the app's
+//! own code, with no account and no network (.github/workflows/linux-compat.yml):
+//!
+//! - `distro_check keyring`: a made-up session saved through `quince_auth::Store::keyring`
+//! (the path sign-in takes) into whatever Secret Service is on the session bus, read back,
+//! then forgotten. Its directory is a fresh temporary one, so its keyring entry is never the
+//! app's own;
+//! - `distro_check heic <file>`: the file decoded to a JPEG by `quince_media::heic_to_jpeg`
+//! through the system's libheif, as a HEIC photo is shown.
+use anyhow::{anyhow, bail, Result};
+use quince_auth::session::Session;
+
+fn main() -> Result<()> {
+ let args: Vec<String> = std::env::args().collect();
+ match args.get(1).map(String::as_str) {
+ Some("keyring") => keyring(),
+ Some("heic") => heic(args.get(2).ok_or_else(|| anyhow!("heic <file>"))?),
+ _ => bail!("usage: distro_check keyring | heic <file>"),
+ }
+}
+
+fn keyring() -> Result<()> {
+ let dir = std::env::temp_dir().join(format!("skykeep-distro-check-{}", std::process::id()));
+ let store = quince_auth::Store::keyring(&dir)?;
+ let session = Session {
+ client_id: Some("distro-check".into()),
+ trust_token: Some("distro-check-not-a-real-token".into()),
+ ..Session::default()
+ };
+ store.save(&session).map_err(|e| anyhow!("save: {e}"))?;
+ let back = store.try_load().map_err(|e| anyhow!("load: {e}"))?;
+ if back.trust_token != session.trust_token {
+ bail!("the keyring gave back {:?}", back.trust_token);
+ }
+ store.clear().map_err(|e| anyhow!("clear: {e}"))?;
+ let gone = store
+ .try_load()
+ .map_err(|e| anyhow!("load after clear: {e}"))?;
+ if gone.trust_token.is_some() {
+ bail!("the keyring kept the session after it was cleared");
+ }
+ std::fs::remove_dir_all(&dir).ok();
+ println!("keyring: saved, read back and cleared through the Secret Service");
+ Ok(())
+}
+
+fn heic(path: &str) -> Result<()> {
+ let bytes = std::fs::read(path)?;
+ if !quince_media::is_heif(&bytes) {
+ bail!("{path} is not a HEIF file");
+ }
+ let jpeg = quince_media::heic_to_jpeg(&bytes).map_err(|e| anyhow!("decode: {e}"))?;
+ let picture = image::load_from_memory_with_format(&jpeg, image::ImageFormat::Jpeg)?;
+ println!(
+ "heic: decoded to a {}x{} JPEG ({} bytes)",
+ picture.width(),
+ picture.height(),
+ jpeg.len()
+ );
+ Ok(())
+}
diff --git a/probe/examples/push_courier.rs b/probe/examples/push_courier.rs
new file mode 100644
index 0000000..b11e110
--- /dev/null
+++ b/probe/examples/push_courier.rs
@@ -0,0 +1,60 @@
+//! Read-only: the live push channel as icloud.com opens it today (quince_icloud::courier):
+//! the web push socket, a token, registration with the push registry, then pushes as they
+//! come. Prints statuses and container names only — never a token, cookie or JWT.
+//! Usage: push_courier [seconds]
+use anyhow::{anyhow, Result};
+use std::time::{Duration, Instant};
+#[tokio::main]
+async fn main() -> Result<()> {
+ let wait: u64 = std::env::args()
+ .nth(1)
+ .and_then(|s| s.parse().ok())
+ .unwrap_or(60);
+ 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 dsid = client
+ .session()
+ .dsid
+ .clone()
+ .ok_or_else(|| anyhow!("no dsid"))?;
+ let http = client.http().clone();
+ let containers = [
+ "com.apple.notes",
+ "com.apple.reminders",
+ "com.apple.photos.cloud",
+ ];
+ let mut id = quince_icloud::courier::Identity::new();
+ let t = Instant::now();
+ let mut courier = quince_icloud::courier::Courier::connect(
+ quince_icloud::courier::SERVER,
+ &mut id,
+ &containers,
+ )
+ .await
+ .map_err(|e| anyhow!("connect: {e}"))?;
+ println!("connected in {:?}", t.elapsed());
+ courier
+ .register(&http, quince_icloud::courier::REGISTRY, &id, &dsid)
+ .await
+ .map_err(|e| anyhow!("register: {e}"))?;
+ println!(
+ "registered in {:?}; waiting {wait}s for pushes…",
+ t.elapsed()
+ );
+ let end = Instant::now() + Duration::from_secs(wait);
+ while Instant::now() < end {
+ match courier.next(end - Instant::now()).await {
+ Ok(Some(e)) => println!("{:>7.1}s push: {e:?}", t.elapsed().as_secs_f32()),
+ Ok(None) => {}
+ Err(e) => {
+ println!("lost: {e}");
+ break;
+ }
+ }
+ }
+ courier.close().await;
+ Ok(())
+}
diff --git a/probe/examples/push_dbcheck.rs b/probe/examples/push_dbcheck.rs
new file mode 100644
index 0000000..1c2ed5a
--- /dev/null
+++ b/probe/examples/push_dbcheck.rs
@@ -0,0 +1,38 @@
+//! Read-only: the fallback poller's check (quince_icloud::push::database_changed) against each
+//! container — seed, then ask again. Prints whether it moved, never the token.
+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 = client.http().clone();
+ let params = client.service_params();
+ for c in [
+ "com.apple.notes",
+ "com.apple.reminders",
+ "com.apple.photos.cloud",
+ ] {
+ let t = std::time::Instant::now();
+ let (moved, token) =
+ quince_icloud::push::database_changed(&http, &root, &params, c, None).await?;
+ let seed = t.elapsed();
+ let t = std::time::Instant::now();
+ let again =
+ quince_icloud::push::database_changed(&http, &root, &params, c, token.as_deref())
+ .await?;
+ println!(
+ "{c}: seed moved={moved} token={} in {seed:?}; again moved={} in {:?}",
+ token.is_some(),
+ again.0,
+ t.elapsed()
+ );
+ }
+ Ok(())
+}
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index ba02324..4532c87 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -12,7 +12,10 @@ tauri-build = { version = "2", features = [] }
futures-util = { version = "0.3", default-features = false, features = ["std"] }
quince-vfs = { path = "../crates/quince-vfs" }
sha2 = "0.10"
-tauri = { version = "2", features = ["tray-icon", "image-png"] }
+# The tray is Tauri's on Windows and macOS. On Linux it is ksni's (main.rs, linux_tray): Tauri's
+# goes through libayatana-appindicator, which never passes a click on, so a left click could
+# only ever open the menu.
+tauri = { version = "2", features = ["image-png"] }
quince-auth = { path = "../crates/quince-auth" }
quince-core = { path = "../crates/quince-core" }
quince-media = { workspace = true }
@@ -31,6 +34,12 @@ notify-rust = "4"
tauri-plugin-single-instance = "2"
libc = "0.2"
tauri-plugin-window-state = "2"
+# A merged card's picture made small enough for Apple (contacts_merge.rs): the same build of
+# the crate quince-media already uses, so nothing new is compiled.
+image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
+
+[target.'cfg(not(target_os = "linux"))'.dependencies]
+tauri = { version = "2", features = ["tray-icon"] }
# Toasts with buttons on Windows (notify-rust sends none there): the same crate notify-rust uses.
[target.'cfg(windows)'.dependencies]
@@ -44,11 +53,18 @@ gstreamer = "0.25"
gstreamer-app = "0.25"
gstreamer-video = "0.25"
zbus = "5"
+# The tray, spoken as StatusNotifierItem over D-Bus itself: a left click (Activate) opens the
+# window. async-io, as zbus here runs on, not a second D-Bus runtime.
+ksni = { version = "0.3.7", default-features = false, features = ["async-io"] }
# Each app's window says its own app ID on Wayland (apps.rs): the GTK window under Tauri's.
gtk = "0.18"
gdk = "0.18"
glib = "0.18"
+# The web views' memory cache sized for an app, not a browser (main.rs, app_cache): the same
+# build wry already compiles, so nothing new is built.
+webkit2gtk = { version = "2.0.2", features = ["v2_40"] }
[dev-dependencies]
-image = { version = "0.25", default-features = false, features = ["jpeg"] }
tempfile = "3"
+# A stand-in for Apple's contacts service, for sending a merge twice (contacts_merge.rs).
+wiremock = "0.6"
diff --git a/src-tauri/icons/128x128.png b/src-tauri/icons/128x128.png
index 7c80ef8..b39d642 100644
Binary files a/src-tauri/icons/128x128.png and b/src-tauri/icons/128x128.png differ
diff --git a/src-tauri/icons/[email protected] b/src-tauri/icons/[email protected]
index 9280052..ee0ebab 100644
Binary files a/src-tauri/icons/[email protected] and b/src-tauri/icons/[email protected] differ
diff --git a/src-tauri/icons/16x16.png b/src-tauri/icons/16x16.png
new file mode 100644
index 0000000..aef686e
Binary files /dev/null and b/src-tauri/icons/16x16.png differ
diff --git a/src-tauri/icons/24x24.png b/src-tauri/icons/24x24.png
new file mode 100644
index 0000000..2f00aa8
Binary files /dev/null and b/src-tauri/icons/24x24.png differ
diff --git a/src-tauri/icons/32x32.png b/src-tauri/icons/32x32.png
index 77936dd..7c2f05c 100644
Binary files a/src-tauri/icons/32x32.png and b/src-tauri/icons/32x32.png differ
diff --git a/src-tauri/icons/48x48.png b/src-tauri/icons/48x48.png
new file mode 100644
index 0000000..77e5c8f
Binary files /dev/null and b/src-tauri/icons/48x48.png differ
diff --git a/src-tauri/icons/64x64.png b/src-tauri/icons/64x64.png
index 4b613fb..06ba69c 100644
Binary files a/src-tauri/icons/64x64.png and b/src-tauri/icons/64x64.png differ
diff --git a/src-tauri/icons/icon.ico b/src-tauri/icons/icon.ico
index d1566e5..d378487 100644
Binary files a/src-tauri/icons/icon.ico and b/src-tauri/icons/icon.ico differ
diff --git a/src-tauri/icons/icon.png b/src-tauri/icons/icon.png
index fbdecff..1fe0b18 100644
Binary files a/src-tauri/icons/icon.png and b/src-tauri/icons/icon.png differ
diff --git a/src-tauri/icons/tray-16.png b/src-tauri/icons/tray-16.png
new file mode 100644
index 0000000..d6da206
Binary files /dev/null and b/src-tauri/icons/tray-16.png differ
diff --git a/src-tauri/icons/tray-22.png b/src-tauri/icons/tray-22.png
new file mode 100644
index 0000000..2fd3272
Binary files /dev/null and b/src-tauri/icons/tray-22.png differ
diff --git a/src-tauri/icons/tray-24.png b/src-tauri/icons/tray-24.png
new file mode 100644
index 0000000..6a8cbeb
Binary files /dev/null and b/src-tauri/icons/tray-24.png differ
diff --git a/src-tauri/icons/tray-32.png b/src-tauri/icons/tray-32.png
new file mode 100644
index 0000000..2d427cb
Binary files /dev/null and b/src-tauri/icons/tray-32.png differ
diff --git a/src-tauri/icons/tray-48.png b/src-tauri/icons/tray-48.png
new file mode 100644
index 0000000..c17b31d
Binary files /dev/null and b/src-tauri/icons/tray-48.png differ
diff --git a/src-tauri/icons/tray-64.png b/src-tauri/icons/tray-64.png
new file mode 100644
index 0000000..96624b2
Binary files /dev/null and b/src-tauri/icons/tray-64.png differ
diff --git a/src-tauri/icons/tray.png b/src-tauri/icons/tray.png
index 1d72b5c..96624b2 100644
Binary files a/src-tauri/icons/tray.png and b/src-tauri/icons/tray.png differ
diff --git a/src-tauri/src/alerts.rs b/src-tauri/src/alerts.rs
index 99bb41e..beb91f8 100644
--- a/src-tauri/src/alerts.rs
+++ b/src-tauri/src/alerts.rs
@@ -80,8 +80,10 @@ fn answer(app: &AppHandle, due: &DueAlarm, due_then: Option<Option<i64>>, action
changed();
}
"default" => {
- crate::show_window(app);
- app.emit(OPEN_REMINDER, &due.reminder_guid).ok();
+ let guid = due.reminder_guid.clone();
+ crate::show_window_then(app, move |app| {
+ app.emit(OPEN_REMINDER, &guid).ok();
+ });
}
_ => {}
}
diff --git a/src-tauri/src/appearance.rs b/src-tauri/src/appearance.rs
new file mode 100644
index 0000000..7e03e07
--- /dev/null
+++ b/src-tauri/src/appearance.rs
@@ -0,0 +1,132 @@
+//! The desktop's Increase Contrast setting, for the window to follow.
+//!
+//! WebKitGTK does not map it to `prefers-contrast` (docs/accessibility.md), so on Linux it is
+//! read here from the Settings portal — `org.freedesktop.appearance` `contrast`, which GNOME's
+//! High Contrast and KDE's set — and handed to the window, which marks its root with
+//! `data-contrast="more"`; the same rules as `prefers-contrast: more` then apply (a11y.css).
+//! Followed as it changes: switched on in the desktop's settings, the window firms up at once.
+//! Elsewhere the engine's own media query already says it, and this reads as unset.
+
+#[cfg(target_os = "linux")]
+use tauri::Emitter;
+
+/// Told to every window when the setting changes: `true` for more contrast.
+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
+pub const CHANGED: &str = "quince://contrast";
+
+/// The portal's value: 1 is "higher contrast"; 0, absent or anything else is the default.
+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
+fn more(value: u32) -> bool {
+ value == 1
+}
+
+/// Whether the desktop asks for more contrast now.
+#[tauri::command]
+pub async fn system_contrast() -> bool {
+ #[cfg(target_os = "linux")]
+ {
+ if let Some(settings) = portal().await {
+ return read(&settings).await.is_some_and(more);
+ }
+ }
+ false
+}
+
+#[cfg(target_os = "linux")]
+async fn portal() -> Option<zbus::Proxy<'static>> {
+ let bus = zbus::Connection::session().await.ok()?;
+ zbus::proxy::Builder::<zbus::Proxy<'static>>::new(&bus)
+ .destination("org.freedesktop.portal.Desktop")
+ .ok()?
+ .path("/org/freedesktop/portal/desktop")
+ .ok()?
+ .interface("org.freedesktop.portal.Settings")
+ .ok()?
+ .cache_properties(zbus::proxy::CacheProperties::No)
+ .build()
+ .await
+ .ok()
+}
+
+/// `ReadOne`, or `Read` on a portal older than version 2, which wraps the value once more.
+#[cfg(target_os = "linux")]
+async fn read(settings: &zbus::Proxy<'static>) -> Option<u32> {
+ use zbus::zvariant::OwnedValue;
+ let key = ("org.freedesktop.appearance", "contrast");
+ if let Ok(v) = settings.call::<_, _, OwnedValue>("ReadOne", &key).await {
+ return u32::try_from(v).ok();
+ }
+ let v: OwnedValue = settings.call("Read", &key).await.ok()?;
+ let inner = zbus::zvariant::Value::from(v);
+ match inner {
+ zbus::zvariant::Value::Value(boxed) => u32::try_from(*boxed).ok(),
+ other => u32::try_from(other).ok(),
+ }
+}
+
+/// Follow the setting for as long as the app runs, telling every window when it moves.
+pub fn watch(app: tauri::AppHandle) {
+ #[cfg(target_os = "linux")]
+ tauri::async_runtime::spawn(async move {
+ use futures_util::StreamExt;
+ use zbus::zvariant::OwnedValue;
+ let Some(settings) = portal().await else {
+ return;
+ };
+ let Ok(mut changes) = settings.receive_signal("SettingChanged").await else {
+ return;
+ };
+ while let Some(signal) = changes.next().await {
+ let Ok((ns, key, value)) = signal.body().deserialize::<(String, String, OwnedValue)>()
+ else {
+ continue;
+ };
+ if ns == "org.freedesktop.appearance" && key == "contrast" {
+ let on = u32::try_from(value).is_ok_and(more);
+ let _ = app.emit(CHANGED, on);
+ }
+ }
+ });
+ #[cfg(not(target_os = "linux"))]
+ let _ = app;
+}
+
+/// The locale dates are written in here, as a BCP 47 tag (`en-GB`): `LC_ALL`, then `LC_TIME`,
+/// then `LANG`, as the C library reads them. WebKitGTK's `navigator.language` follows `LANG`
+/// alone, so a British `LC_TIME` under an American `LANG` would start the week on Sunday;
+/// Calendar asks here first. None for C, POSIX or nothing set.
+#[tauri::command]
+pub fn system_time_locale() -> Option<String> {
+ let var = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty());
+ tag(&var("LC_ALL")
+ .or_else(|| var("LC_TIME"))
+ .or_else(|| var("LANG"))?)
+}
+
+/// `en_GB.UTF-8@euro` as `en-GB`.
+fn tag(posix: &str) -> Option<String> {
+ let bare = posix.split(['.', '@']).next()?.trim();
+ if bare.is_empty() || bare == "C" || bare == "POSIX" {
+ return None;
+ }
+ Some(bare.replace('_', "-"))
+}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn a_posix_locale_reads_as_a_language_tag() {
+ assert_eq!(super::tag("en_GB.UTF-8").as_deref(), Some("en-GB"));
+ assert_eq!(super::tag("de_DE@euro").as_deref(), Some("de-DE"));
+ assert_eq!(super::tag("fr").as_deref(), Some("fr"));
+ assert_eq!(super::tag("C.UTF-8"), None);
+ assert_eq!(super::tag("POSIX"), None);
+ }
+
+ #[test]
+ fn only_the_portals_high_contrast_value_asks_for_more() {
+ assert!(super::more(1));
+ assert!(!super::more(0));
+ assert!(!super::more(2));
+ }
+}
diff --git a/src-tauri/src/apps.rs b/src-tauri/src/apps.rs
index 514b397..f8a4b8c 100644
--- a/src-tauri/src/apps.rs
+++ b/src-tauri/src/apps.rs
@@ -141,6 +141,7 @@ pub fn open(app: &AppHandle, key: &str) {
let Some((key, name)) = APPS.iter().find(|(k, _)| *k == key).copied() else {
return;
};
+ crate::timing::mark(format_args!("app {key} asked"));
if let Some(w) = app.get_webview_window(&label(key)) {
w.unminimize().ok();
show(&w);
@@ -157,6 +158,7 @@ pub fn open(app: &AppHandle, key: &str) {
// Shown by its own window_ready, once it has drawn: never a blank frame.
.visible(false)
.build();
+ crate::timing::mark(format_args!("app {key} window made"));
let window = match made {
Ok(w) => w,
Err(e) => {
@@ -178,7 +180,8 @@ pub fn open(app: &AppHandle, key: &str) {
});
}
-/// How long a closed app window is kept, put away, before its memory is given back.
+/// How long a closed window — an app's, or the whole-library one — is kept, put away, before
+/// its memory is given back.
const KEPT: std::time::Duration = std::time::Duration::from_secs(10 * 60);
/// When each put-away app window was closed: shown again, it is taken off the list, so a
@@ -186,8 +189,9 @@ const KEPT: std::time::Duration = std::time::Duration::from_secs(10 * 60);
static PUT_AWAY: std::sync::Mutex<Vec<(String, std::time::Instant)>> =
std::sync::Mutex::new(Vec::new());
-/// A closed app window, kept hidden for a while and then closed for good if it was not opened
-/// again meanwhile.
+/// A closed window, kept hidden for a while and then closed for good if it was not opened again
+/// meanwhile. The whole-library window too: `show_window` makes it again when it is next asked
+/// for, and the app goes on behind the tray with no window at all (main.rs, `ExitRequested`).
pub fn put_away(window: &tauri::Window) {
let label = window.label().to_string();
let at = std::time::Instant::now();
@@ -228,6 +232,7 @@ pub fn show(window: &tauri::WebviewWindow) {
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.retain(|(l, _)| l != window.label());
+ crate::timing::mark(format_args!("{} shown", window.label()));
window.show().ok();
window.set_focus().ok();
#[cfg(target_os = "linux")]
diff --git a/src-tauri/src/contacts_cmds.rs b/src-tauri/src/contacts_cmds.rs
index 27bf4e1..b9a8242 100644
--- a/src-tauri/src/contacts_cmds.rs
+++ b/src-tauri/src/contacts_cmds.rs
@@ -16,46 +16,31 @@ pub async fn contact_addresses(
}
/// Change a card's addresses: set a part, set a label, add one or take one out — any number
-/// at once, in order. `base` is the list the form opened (the stored list when absent); the
-/// edits are laid over Apple's addresses as they stand at the moment of writing, so a part
-/// changed on another device stays. Shown here at once; on a refusal Apple's card is read
-/// back, so what is on screen is never something Apple does not have. Answers the list.
+/// at once, in order. `base` is the list the form opened (the stored list when absent). Shown
+/// here at once and queued (outbox.rs), like every other contact write: it works offline, and
+/// on a card made here that Apple does not have yet it goes after the card itself. Sent, the
+/// edits are laid over Apple's addresses as they stand then, so a part changed on another
+/// device stays. Answers the list as it now shows.
#[tauri::command]
pub async fn contact_address_edit(
guid: String,
base: Option<Vec<PostalAddress>>,
edits: Vec<AddressEdit>,
- auth: State<'_, crate::Auth>,
data: State<'_, Data>,
) -> UiResult<Vec<PostalAddress>> {
- let _one = crate::CONTACTS_PASS.lock().await;
- let (http, root, params) = crate::contacts_context(&auth).await?;
- let base = match base {
- Some(base) => base,
- None => {
- let library = data.0.lock().await;
- library
+ let after = {
+ let mut library = data.0.lock().await;
+ let base = match base {
+ Some(base) => base,
+ None => library
.contact_addresses(&guid)
- .map_err(|e| e.to_string())?
- }
+ .map_err(|e| e.to_string())?,
+ };
+ // Checked before anything is queued: an edit naming nothing is said now.
+ address::apply_edits(&base, &edits).map_err(|e| e.to_string())?;
+ crate::outbox::record_contact_address(&mut library, &guid, base, edits)
+ .map_err(|e| e.to_string())?
};
- // Checked, and shown, before anything is sent.
- let (after, _) = address::apply_edits(&base, &edits).map_err(|e| e.to_string())?;
- {
- let mut library = data.0.lock().await;
- library
- .set_contact_addresses(&guid, &after)
- .map_err(|e| e.to_string())?;
- }
- match address::edit(&http, &root, params.clone(), &guid, &base, &edits).await {
- Ok(written) => {
- crate::settle(crate::resync_contacts(&http, &root, params, &data).await)?;
- Ok(written)
- }
- Err(e) => {
- // Put back what Apple has.
- let _ = crate::resync_contacts(&http, &root, params, &data).await;
- Err(e.to_string())
- }
- }
+ crate::outbox::kick();
+ Ok(after)
}
diff --git a/src-tauri/src/contacts_merge.rs b/src-tauri/src/contacts_merge.rs
new file mode 100644
index 0000000..8bdee42
--- /dev/null
+++ b/src-tauri/src/contacts_merge.rs
@@ -0,0 +1,699 @@
+//! Duplicate cards, found and merged.
+//!
+//! A merge is a change like any other made here (outbox.rs): shown at once — one card where
+//! there were several, in every list any of them was in — and sent behind, offline or not.
+//! It waits [`HOLD`] before it goes, and until it goes it can be undone: taken off the queue,
+//! and every card put back as it was. Sent, it is done on Apple's own cards
+//! (`quince_icloud::contacts::merge`), each step safe to take twice.
+
+use crate::outbox::{self, CONTACTS};
+use crate::{Data, UiResult};
+use quince_core::contacts::merge::{self as core_merge, Duplicates};
+use quince_core::contacts::{Card, Contact, ContactDetails, PostalAddress};
+use quince_core::outbox::Pending;
+use quince_core::Library;
+use quince_icloud::contacts::{self as c, merge as apple};
+use quince_icloud::Error;
+use serde::{Deserialize, Serialize};
+use std::time::Duration;
+use tauri::State;
+use tokio::sync::Mutex;
+
+/// How long a merge waits before it is sent: the time its Undo is on screen.
+const HOLD: i64 = 10;
+
+/// One card as it was before a merge, whole.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct Kept {
+ pub card: Card,
+ pub addresses: Vec<PostalAddress>,
+}
+
+/// A merge made here: the card it leaves, and everything needed to send it or undo it.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ContactMerge {
+ /// The kept card as merged — what is shown until Apple has it. Named `contact` as a save
+ /// names its card, so a notice about it can name the person.
+ pub contact: Contact,
+ pub details: ContactDetails,
+ pub addresses: Vec<PostalAddress>,
+ /// The kept card as it was.
+ pub before: Kept,
+ /// The cards merged into it, as they were.
+ pub absorbed: Vec<Kept>,
+ /// The lists as they stood, to put back on an undo.
+ pub lists_before: String,
+ /// Not sent before this moment (seconds since the epoch).
+ pub hold_until: i64,
+}
+
+fn now() -> i64 {
+ jiff::Timestamp::now().as_second()
+}
+
+fn json<T: Serialize>(v: &T) -> quince_core::Result<String> {
+ serde_json::to_string(v)
+ .map_err(|e| quince_core::Error::Io(std::io::Error::other(e.to_string())))
+}
+
+fn same(a: &str, b: &str) -> bool {
+ a.eq_ignore_ascii_case(b)
+}
+
+/// The lists with `kept` in every one any of `absorbed` was in, and none of `absorbed` left.
+fn lists_after(lists: &str, kept: &str, absorbed: &[String]) -> String {
+ let mut all: Vec<c::ContactList> = serde_json::from_str(lists).unwrap_or_default();
+ for l in &mut all {
+ let had = l
+ .members
+ .iter()
+ .any(|m| absorbed.iter().any(|a| same(a, m)));
+ l.members.retain(|m| !absorbed.iter().any(|a| same(a, m)));
+ if had && !l.members.iter().any(|m| same(m, kept)) {
+ l.members.push(kept.to_string());
+ }
+ }
+ serde_json::to_string(&all).unwrap_or_else(|_| lists.to_string())
+}
+
+/// Lay a merge over the library: one card where there were several, in all their lists.
+pub fn lay(l: &mut Library, m: &ContactMerge) -> quince_core::Result<()> {
+ let kept = m.contact.guid.clone();
+ let absorbed: Vec<String> = m
+ .absorbed
+ .iter()
+ .map(|a| a.card.contact.guid.clone())
+ .collect();
+ for guid in &absorbed {
+ l.forget_contact(guid)?;
+ }
+ l.put_card(&Card {
+ contact: m.contact.clone(),
+ details: m.details.clone(),
+ })?;
+ l.set_contact_addresses(&kept, &m.addresses)?;
+ let lists = l.state(c::LISTS_KEY)?.unwrap_or_else(|| "[]".into());
+ l.set_state(c::LISTS_KEY, &lists_after(&lists, &kept, &absorbed))?;
+ if let Some(me) = l.state(c::ME_KEY)? {
+ if absorbed.iter().any(|a| same(a, &me)) {
+ l.set_state(c::ME_KEY, &kept)?;
+ }
+ }
+ Ok(())
+}
+
+/// Merge these cards into one, here at once and at Apple behind. Answers the kept card's id.
+pub fn record(library: &mut Library, guids: &[String]) -> Result<String, String> {
+ let mut wanted: Vec<String> = Vec::new();
+ for g in guids {
+ if !wanted.iter().any(|w| same(w, g)) {
+ wanted.push(g.clone());
+ }
+ }
+ let book = library.cards(None).map_err(|e| e.to_string())?;
+ let cards: Vec<Card> = wanted
+ .iter()
+ .filter_map(|g| book.iter().find(|c| same(&c.contact.guid, g)).cloned())
+ .collect();
+ if cards.len() < 2 {
+ return Err("Choose two or more contacts to merge.".into());
+ }
+ let me = library
+ .state(c::ME_KEY)
+ .map_err(|e| e.to_string())?
+ .filter(|m| !m.is_empty());
+ let at = core_merge::survivor(&cards, me.as_deref());
+ let kept = cards[at].clone();
+ let others: Vec<Card> = cards
+ .iter()
+ .enumerate()
+ .filter(|(i, _)| *i != at)
+ .map(|(_, c)| c.clone())
+ .collect();
+ let whole = |card: &Card| -> Result<Kept, String> {
+ Ok(Kept {
+ addresses: library
+ .contact_addresses(&card.contact.guid)
+ .map_err(|e| e.to_string())?,
+ card: card.clone(),
+ })
+ };
+ let before = whole(&kept)?;
+ let absorbed = others.iter().map(whole).collect::<Result<Vec<_>, _>>()?;
+ let merged = core_merge::merged(&kept, &others);
+ let addresses = core_merge::merged_addresses(
+ &std::iter::once(&before)
+ .chain(&absorbed)
+ .map(|k| k.addresses.clone())
+ .collect::<Vec<_>>(),
+ );
+ let m = ContactMerge {
+ contact: merged.contact,
+ details: merged.details,
+ addresses,
+ before,
+ absorbed,
+ lists_before: library
+ .state(c::LISTS_KEY)
+ .map_err(|e| e.to_string())?
+ .unwrap_or_else(|| "[]".into()),
+ hold_until: now() + HOLD,
+ };
+ let guid = kept.contact.guid.clone();
+ library
+ .atomically(|l| {
+ l.outbox_append(CONTACTS, &guid, "merge", &json(&m)?)?;
+ lay(l, &m)
+ })
+ .map_err(|e| e.to_string())?;
+ Ok(guid)
+}
+
+/// Take back a merge not yet sent: off the queue, and every card as it was. False when it has
+/// already gone to Apple (or there is none).
+pub fn undo(library: &mut Library, kept: &str) -> Result<bool, String> {
+ let waiting = library
+ .outbox_waiting(CONTACTS, kept, "merge")
+ .map_err(|e| e.to_string())?;
+ let Some(p) = waiting.last() else {
+ return Ok(false);
+ };
+ let m: ContactMerge = serde_json::from_str(&p.payload).map_err(|e| e.to_string())?;
+ let id = p.id;
+ library
+ .atomically(|l| {
+ if !l.outbox_withdraw(id)? {
+ return Ok(false);
+ }
+ for k in std::iter::once(&m.before).chain(&m.absorbed) {
+ l.put_card(&k.card)?;
+ l.set_contact_addresses(&k.card.contact.guid, &k.addresses)?;
+ }
+ l.set_state(c::LISTS_KEY, &m.lists_before)?;
+ // Whatever else waits for these cards is laid over them again.
+ outbox::replay(l, CONTACTS)?;
+ Ok::<_, quince_core::Error>(true)
+ })
+ .map_err(|e| e.to_string())
+}
+
+/// How long until the merge at the head of the queue may go; `None` when nothing waits on one.
+pub async fn held(data: &State<'_, Data>) -> Option<Duration> {
+ let head = data
+ .0
+ .lock()
+ .await
+ .outbox_pending(CONTACTS)
+ .ok()?
+ .into_iter()
+ .next()?;
+ if head.kind != "merge" || head.tries > 0 {
+ return None;
+ }
+ let m: ContactMerge = serde_json::from_str(&head.payload).ok()?;
+ let left = m.hold_until - now();
+ (left > 0).then(|| Duration::from_secs(u64::try_from(left).unwrap_or(1)))
+}
+
+/// Whether an error means Apple was never reached.
+fn unreached(e: &Error) -> bool {
+ matches!(e, Error::Network(_) | Error::ReauthRequired)
+}
+
+/// Send a merge, on Apple's own cards. See the module's notes for why each step is safe to
+/// take twice.
+pub async fn send(
+ library: &Mutex<Library>,
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+ p: &Pending,
+) -> Result<(), Error> {
+ let m: ContactMerge = serde_json::from_str(&p.payload)
+ .map_err(|e| Error::Refused(format!("A queued merge could not be read: {e}")))?;
+ let book = match apple::read_book(http, root, params.clone()).await {
+ Ok(book) => book,
+ Err(e) => {
+ // Nothing of it reached Apple: it can still be undone.
+ if unreached(&e) {
+ let _ = library.lock().await.outbox_untry(p.id);
+ }
+ return Err(e);
+ }
+ };
+ let Some(kept) = book.card(&p.record).filter(apple::readable) else {
+ return Err(Error::Refused(format!(
+ "{} was deleted on another device, so the merge wasn't sent.",
+ m.before.card.contact.display_name()
+ )));
+ };
+ // A card already gone — deleted on another device, or by this merge sent before — still
+ // brings what it held, from the copy kept here.
+ let others: Vec<serde_json::Value> = m
+ .absorbed
+ .iter()
+ .map(|a| {
+ book.card(&a.card.contact.guid)
+ .unwrap_or_else(|| apple::snapshot(&a.card, &a.addresses))
+ })
+ .collect();
+ let (mut card, photo) = apple::union(&kept, &others);
+ if let Some(photo) = photo {
+ if let Some(entry) = carry_photo(http, &params, &photo).await {
+ if let Some(o) = card.as_object_mut() {
+ o.insert("photo".into(), entry);
+ }
+ }
+ }
+ if card != kept {
+ apple::put(http, root, params.clone(), &book.tokens, card).await?;
+ }
+
+ // Into every list the others were in.
+ let absorbed: Vec<&str> = m
+ .absorbed
+ .iter()
+ .map(|a| a.card.contact.guid.as_str())
+ .collect();
+ let book = apple::read_book(http, root, params.clone()).await?;
+ for mut list in book.lists() {
+ let had = list
+ .members
+ .iter()
+ .any(|x| absorbed.iter().any(|a| same(a, x)));
+ if had && !list.members.iter().any(|x| same(x, &p.record)) {
+ list.members.push(p.record.clone());
+ let tokens = apple::read_book(http, root, params.clone()).await?.tokens;
+ c::update_list(http, root, params.clone(), &tokens, &list).await?;
+ }
+ }
+
+ // And the others gone. My Card moves to the kept card first, if it was one of them.
+ let book = apple::read_book(http, root, params.clone()).await?;
+ let me = book.me();
+ if me
+ .as_deref()
+ .is_some_and(|me| absorbed.iter().any(|a| same(a, me)))
+ {
+ c::set_me_card(http, root, params.clone(), &book.tokens, &p.record).await?;
+ }
+ for guid in absorbed {
+ let book = apple::read_book(http, root, params.clone()).await?;
+ if let Some(card) = book.card(guid) {
+ apple::delete_card(http, root, params.clone(), &book.tokens, &card).await?;
+ }
+ }
+ Ok(())
+}
+
+/// The largest picture Apple's web editor sends, as a `data:` URL's length.
+const PHOTO_LIMIT: usize = 229_376;
+
+/// Another card's picture, as an image of the kept card's own: fetched, and sent as a JPEG
+/// under Apple's size, its chosen square scaled with it — what icloud.com sends for a picture
+/// chosen there. `None` when it cannot be had; the merge goes ahead without it rather than
+/// not at all.
+async fn carry_photo(
+ http: &reqwest::Client,
+ params: &[(String, String)],
+ photo: &serde_json::Value,
+) -> Option<serde_json::Value> {
+ let url = photo.get("url")?.as_str()?;
+ let bytes = if let Some(data) = url.strip_prefix("data:") {
+ use base64::Engine;
+ let (_, b64) = data.split_once(',')?;
+ base64::engine::general_purpose::STANDARD.decode(b64).ok()?
+ } else {
+ let response = http.get(url).query(params).send().await.ok()?;
+ if !response.status().is_success() {
+ return None;
+ }
+ response.bytes().await.ok()?.to_vec()
+ };
+ let crop = photo.get("crop").and_then(|c| {
+ let at = |k: &str| c.get(k).and_then(serde_json::Value::as_i64);
+ Some((at("x")?, at("y")?, at("width")?, at("height")?))
+ });
+ let (data_url, scale) = tokio::task::spawn_blocking(move || encode_photo(&bytes, PHOTO_LIMIT))
+ .await
+ .ok()??;
+ #[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)]
+ let scaled = crop.map(|(x, y, w, h)| {
+ let s = |v: i64| (v as f64 * scale).round() as i64;
+ (s(x), s(y), s(w).max(1), s(h).max(1))
+ });
+ Some(apple::photo_entry(&data_url, scaled))
+}
+
+/// An image as a JPEG `data:` URL no longer than `limit`: quality stepped down first, then
+/// size, as icloud.com does. Answers the URL and the scale the image was drawn at.
+pub fn encode_photo(bytes: &[u8], limit: usize) -> Option<(String, f64)> {
+ use base64::Engine;
+ let image = image::load_from_memory(bytes).ok()?.to_rgb8();
+ let (w, h) = image.dimensions();
+ let (mut scale, mut quality) = (1.0_f64, 90_u8);
+ for _ in 0..24 {
+ #[allow(
+ clippy::cast_possible_truncation,
+ clippy::cast_sign_loss,
+ clippy::cast_precision_loss
+ )]
+ let (sw, sh) = (
+ ((f64::from(w) * scale).round() as u32).max(1),
+ ((f64::from(h) * scale).round() as u32).max(1),
+ );
+ let drawn = if (sw, sh) == (w, h) {
+ image.clone()
+ } else {
+ image::imageops::resize(&image, sw, sh, image::imageops::FilterType::Triangle)
+ };
+ let mut out = Vec::new();
+ image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, quality)
+ .encode_image(&drawn)
+ .ok()?;
+ let url = format!(
+ "data:image/jpeg;base64,{}",
+ base64::engine::general_purpose::STANDARD.encode(&out)
+ );
+ if url.len() <= limit {
+ return Some((url, f64::from(sw) / f64::from(w)));
+ }
+ if quality > 40 {
+ quality -= 15;
+ } else {
+ scale *= 0.8;
+ }
+ }
+ None
+}
+
+// --- Commands.
+
+/// Cards that look like one person: the same name, or a number or email they share.
+#[tauri::command]
+pub async fn contacts_duplicates(data: State<'_, Data>) -> UiResult<Vec<Duplicates>> {
+ let library = data.0.lock().await;
+ let book = library.contacts(None).map_err(|e| e.to_string())?;
+ Ok(core_merge::find_duplicates(&book))
+}
+
+/// Merge these cards into one. Shown at once, sent behind; answers the kept card's id.
+#[tauri::command]
+pub async fn contacts_merge(guids: Vec<String>, data: State<'_, Data>) -> UiResult<String> {
+ let kept = {
+ let mut library = data.0.lock().await;
+ record(&mut library, &guids)?
+ };
+ outbox::kick();
+ Ok(kept)
+}
+
+/// Undo a merge Apple does not have yet. Answers whether it was undone.
+#[tauri::command]
+pub async fn contacts_merge_undo(kept: String, data: State<'_, Data>) -> UiResult<bool> {
+ let mut library = data.0.lock().await;
+ undo(&mut library, &kept)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use quince_core::contacts::ContactMethod;
+
+ fn person(guid: &str, first: &str, phone: &str) -> Card {
+ Card {
+ contact: Contact {
+ guid: guid.into(),
+ first_name: Some(first.into()),
+ middle_name: None,
+ last_name: None,
+ company: None,
+ is_company: false,
+ birthday: None,
+ notes: None,
+ photo_url: None,
+ photo_signature: None,
+ photo_crop: None,
+ etag: None,
+ methods: vec![ContactMethod {
+ kind: "phone".into(),
+ label: None,
+ value: phone.into(),
+ }],
+ },
+ details: ContactDetails::default(),
+ }
+ }
+
+ fn library() -> Library {
+ let mut l = Library::in_memory().unwrap();
+ let mut a = person("A", "Zoya", "+91 90000 00001");
+ a.details.job_title = Some("Architect".into());
+ let mut b = person("B", "Zoya", "090000 00001");
+ b.contact.notes = Some("Prefers WhatsApp".into());
+ b.contact.methods.push(ContactMethod {
+ kind: "email".into(),
+ label: Some("HOME".into()),
+ value: "[email protected]".into(),
+ });
+ for c in [&a, &b, &person("C", "Ravi", "+91 98765 43210")] {
+ l.put_card(c).unwrap();
+ }
+ l.put_addresses(
+ &[(
+ "B".into(),
+ vec![PostalAddress {
+ label: Some("HOME".into()),
+ city: Some("Pune".into()),
+ ..PostalAddress::default()
+ }],
+ )],
+ false,
+ )
+ .unwrap();
+ l.set_state(
+ c::LISTS_KEY,
+ r#"[{"guid":"L1","name":"Family","members":["B","C"],"etag":null}]"#,
+ )
+ .unwrap();
+ l.set_state(c::ME_KEY, "").unwrap();
+ l
+ }
+
+ #[test]
+ fn a_merge_shows_one_card_at_once_and_undo_puts_every_card_back() {
+ let mut l = library();
+ let dupes = core_merge::find_duplicates(&l.contacts(None).unwrap());
+ assert_eq!(dupes.len(), 1);
+ assert_eq!(dupes[0].guids, ["A", "B"]);
+
+ let kept = record(&mut l, &dupes[0].guids).unwrap();
+ let book = l.cards(None).unwrap();
+ assert_eq!(book.len(), 2, "one card where there were two");
+ let merged = book.iter().find(|c| c.contact.guid == kept).unwrap();
+ assert_eq!(merged.details.job_title.as_deref(), Some("Architect"));
+ assert_eq!(merged.contact.notes.as_deref(), Some("Prefers WhatsApp"));
+ assert!(merged.contact.methods.iter().any(|m| m.kind == "email"));
+ assert_eq!(
+ l.contact_addresses(&kept).unwrap()[0].city.as_deref(),
+ Some("Pune")
+ );
+ let lists = c::stored_lists(&l);
+ assert!(
+ lists[0].members.contains(&kept),
+ "in the list the other card was in"
+ );
+ assert_eq!(l.outbox_pending(CONTACTS).unwrap().len(), 1);
+
+ // Undone before it is sent: every card as it was, and nothing waits.
+ assert!(undo(&mut l, &kept).unwrap());
+ let book = l.cards(None).unwrap();
+ assert_eq!(book.len(), 3);
+ let b = book.iter().find(|c| c.contact.guid == "B").unwrap();
+ assert_eq!(b.contact.notes.as_deref(), Some("Prefers WhatsApp"));
+ assert_eq!(l.contact_addresses("B").unwrap().len(), 1);
+ assert_eq!(c::stored_lists(&l)[0].members, ["B", "C"]);
+ assert!(l.outbox_pending(CONTACTS).unwrap().is_empty());
+ assert!(!undo(&mut l, &kept).unwrap(), "nothing left to undo");
+ }
+
+ #[test]
+ fn a_merge_on_its_way_cannot_be_undone_and_a_pass_keeps_it_shown() {
+ let mut l = library();
+ let kept = record(&mut l, &["A".into(), "B".into()]).unwrap();
+ l.outbox_take(CONTACTS).unwrap();
+ assert!(!undo(&mut l, &kept).unwrap());
+ // A pass reads Apple's book from before the merge; what waits is laid over it.
+ let a = person("A", "Zoya", "+91 90000 00001");
+ let b = person("B", "Zoya", "090000 00001");
+ l.put_contacts(&[a.contact, b.contact]).unwrap();
+ outbox::replay(&mut l, CONTACTS).unwrap();
+ assert_eq!(l.contacts(None).unwrap().len(), 1);
+ // Reached nothing at Apple: counted as untried, it can be undone again.
+ let id = l.outbox_pending(CONTACTS).unwrap()[0].id;
+ l.outbox_untry(id).unwrap();
+ assert!(undo(&mut l, &kept).unwrap());
+ }
+
+ #[test]
+ fn my_card_stays_mine_when_it_is_merged() {
+ let mut l = library();
+ l.set_state(c::ME_KEY, "B").unwrap();
+ let kept = record(&mut l, &["A".into(), "B".into()]).unwrap();
+ assert_eq!(kept, "B", "My Card is the one kept");
+ assert_eq!(l.state(c::ME_KEY).unwrap().as_deref(), Some("B"));
+ }
+
+ #[test]
+ fn a_picture_is_made_small_enough_for_apple_to_take() {
+ let big = image::RgbImage::from_fn(1600, 1200, |x, y| {
+ image::Rgb([(x % 251) as u8, (y % 241) as u8, ((x * y) % 239) as u8])
+ });
+ let mut png = Vec::new();
+ image::DynamicImage::ImageRgb8(big)
+ .write_to(
+ &mut std::io::Cursor::new(&mut png),
+ image::ImageFormat::Jpeg,
+ )
+ .unwrap();
+ let (url, scale) = encode_photo(&png, PHOTO_LIMIT).unwrap();
+ assert!(url.starts_with("data:image/jpeg;base64,"));
+ assert!(url.len() <= PHOTO_LIMIT);
+ assert!(scale <= 1.0 && scale > 0.0);
+ }
+
+ /// Apple's contacts service, enough of it to merge against: it keeps the cards and lists
+ /// it is sent, and counts every write.
+ mod apple_stub {
+ use serde_json::{json, Value};
+ use std::sync::{Arc, Mutex as StdMutex};
+ use wiremock::{Request, Respond, ResponseTemplate};
+
+ #[derive(Default)]
+ pub struct Book {
+ pub cards: Vec<Value>,
+ pub groups: Vec<Value>,
+ pub writes: Vec<String>,
+ pub version: u64,
+ }
+
+ #[derive(Clone)]
+ pub struct Apple(pub Arc<StdMutex<Book>>);
+
+ impl Respond for Apple {
+ fn respond(&self, req: &Request) -> ResponseTemplate {
+ let mut b = self.0.lock().unwrap();
+ let path = req.url.path().to_string();
+ let method = req
+ .url
+ .query_pairs()
+ .find(|(k, _)| k == "method")
+ .map_or_else(|| req.method.to_string(), |(_, v)| v.to_string());
+ let body: Value = serde_json::from_slice(&req.body).unwrap_or(Value::Null);
+ if path.ends_with("/co/startup") {
+ let order: Vec<Value> =
+ b.cards.iter().map(|c| c["contactId"].clone()).collect();
+ return ResponseTemplate::new(200).set_body_json(json!({
+ "syncToken": format!("S{}", b.version), "prefToken": "P",
+ "contacts": b.cards, "groups": b.groups, "contactsOrder": order,
+ }));
+ }
+ b.version += 1;
+ let v = b.version;
+ if path.contains("/co/contacts/card") {
+ let card = body["contacts"][0].clone();
+ let id = card["contactId"].as_str().unwrap_or("").to_string();
+ b.writes.push(format!("{method} card {id}"));
+ b.cards.retain(|c| c["contactId"] != id.as_str());
+ if method != "DELETE" {
+ let mut card = card;
+ card["etag"] = json!(format!("E{v}"));
+ b.cards.push(card);
+ }
+ } else if path.contains("/co/groups/card") {
+ let g = body["groups"][0].clone();
+ b.writes.push(format!(
+ "{method} list {}",
+ g["groupId"].as_str().unwrap_or("")
+ ));
+ b.groups.retain(|x| x["groupId"] != g["groupId"]);
+ b.groups.push(g);
+ }
+ ResponseTemplate::new(200).set_body_json(json!({}))
+ }
+ }
+ }
+
+ /// Sent, the kept card at Apple holds everything both did, is in the other's list, and the
+ /// other is gone; sent again — a send cut off, retried — nothing more is written.
+ #[test]
+ fn a_merge_sent_twice_lands_once_and_loses_nothing() {
+ use serde_json::json;
+ tauri::async_runtime::block_on(async {
+ let server = wiremock::MockServer::start().await;
+ let apple = apple_stub::Apple(std::sync::Arc::new(std::sync::Mutex::new(
+ apple_stub::Book {
+ cards: vec![
+ json!({ "contactId": "A", "etag": "ea", "firstName": "Zoya",
+ "jobTitle": "Architect",
+ "phones": [{ "label": "MOBILE", "field": "+91 90000 00001" }] }),
+ json!({ "contactId": "B", "etag": "eb", "firstName": "Zoya",
+ "notes": "Prefers WhatsApp", "X-APPLE-ONLY": "kept",
+ "phones": [{ "field": "090000 00001" }],
+ "emailAddresses": [{ "label": "HOME", "field": "[email protected]" }],
+ "streetAddresses": [{ "label": "HOME", "field": { "city": "Pune" } }] }),
+ json!({ "contactId": "C", "etag": "ec", "firstName": "Ravi" }),
+ ],
+ groups: vec![
+ json!({ "groupId": "L1", "name": "Family", "contactIds": ["A", "C"], "etag": "g1" }),
+ ],
+ ..Default::default()
+ },
+ )));
+ wiremock::Mock::given(wiremock::matchers::any())
+ .respond_with(apple.clone())
+ .mount(&server)
+ .await;
+
+ let lib = Mutex::new(library());
+ let kept = record(&mut *lib.lock().await, &["A".into(), "B".into()]).unwrap();
+ assert_eq!(kept, "B", "the card holding the most");
+ let p = lib.lock().await.outbox_pending(CONTACTS).unwrap().remove(0);
+ let http = reqwest::Client::new();
+ send(&lib, &http, &server.uri(), vec![], &p).await.unwrap();
+
+ {
+ let b = apple.0.lock().unwrap();
+ assert_eq!(b.cards.len(), 2, "{:?}", b.writes);
+ let a = b
+ .cards
+ .iter()
+ .find(|c| c["contactId"] == kept.as_str())
+ .unwrap();
+ assert_eq!(a["jobTitle"], "Architect");
+ assert_eq!(a["notes"], "Prefers WhatsApp");
+ assert_eq!(
+ a["X-APPLE-ONLY"], "kept",
+ "even what this app does not show"
+ );
+ assert_eq!(
+ a["phones"].as_array().unwrap().len(),
+ 1,
+ "one number, not two"
+ );
+ assert_eq!(a["emailAddresses"][0]["field"], "[email protected]");
+ assert_eq!(a["streetAddresses"][0]["field"]["city"], "Pune");
+ assert!(b.groups[0]["contactIds"]
+ .as_array()
+ .unwrap()
+ .contains(&json!(kept)));
+ assert_eq!(b.writes.len(), 3, "{:?}", b.writes);
+ }
+ // Sent again: nothing more to write.
+ send(&lib, &http, &server.uri(), vec![], &p).await.unwrap();
+ assert_eq!(apple.0.lock().unwrap().writes.len(), 3);
+ });
+ }
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 5d40805..f7a67ff 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -13,8 +13,10 @@ macro_rules! quiet {
}
mod alerts;
+mod appearance;
mod apps;
mod contacts_cmds;
+mod contacts_merge;
mod cpu;
mod export;
mod grants;
@@ -25,9 +27,11 @@ mod mount;
mod mount_photos;
mod notes_cmds;
mod outbox;
+mod photo_cache;
mod photos;
#[cfg(target_os = "linux")]
mod poster;
+mod power;
#[cfg(not(target_os = "linux"))]
mod poster {
//! Elsewhere than Linux there is no GStreamer to read a frame with: Apple's own poster stands.
@@ -42,11 +46,11 @@ mod reminders_cmds;
#[cfg(target_os = "linux")]
mod search_provider;
mod settings;
+mod timing;
mod video;
use quince_auth::{Client, SignInOutcome, TwoFactorOptions};
use quince_core::calendar::{Calendar, Event};
-use quince_core::contacts::Contact;
use quince_core::drive::DriveItem;
use quince_core::notes::{Note, NoteFolder};
use quince_core::reminders::{Reminder, ReminderList, SmartList};
@@ -64,6 +68,29 @@ struct Auth {
/// A sign-in is in flight. The mutex would serialise a second click rather than reject
/// it, so it would run a whole second SRP exchange and trigger another code push.
signing_in: AtomicBool,
+ /// What `auth_status` last read of the session, for a window that opens while the session
+ /// is busy — being taken up, or checked by the timer — behind its lock: read from here it
+ /// opens at once, never waiting out a round trip to Apple first.
+ known: std::sync::Mutex<SessionFacts>,
+}
+
+/// What a window asks of the session as it opens.
+#[derive(Clone, Default)]
+struct SessionFacts {
+ has_stored_session: bool,
+ signed_in: bool,
+ /// The account it is (`account_tag`).
+ account: Option<String>,
+}
+
+impl SessionFacts {
+ fn of(client: &Client) -> Self {
+ SessionFacts {
+ has_stored_session: client.has_stored_session(),
+ signed_in: client.session().webservices.is_some(),
+ account: client.session().dsid.as_deref().map(account_tag),
+ }
+ }
}
/// Clears the in-flight flag however the guarded block exits.
@@ -82,6 +109,9 @@ struct Status {
has_stored_session: bool,
/// Apple's service map is loaded, i.e. we are actually signed in right now.
signed_in: bool,
+ /// The stored session's account is the one the library already belongs to: the library
+ /// can open on what it holds at once, while the session is taken up again behind it.
+ library_ready: bool,
}
struct Data(Mutex<Library>);
@@ -235,6 +265,52 @@ fn note_part(path: &str) -> Option<(String, quince_icloud::note_media::Part)> {
(!id.is_empty()).then(|| (id.to_string(), part))
}
+/// The reminder picture a `quince://` request asks for: `rimg/<UUID>`, the `Attachment/`
+/// record it stands for.
+fn reminder_image_part(path: &str) -> Option<String> {
+ let path = percent_decode(path.trim_start_matches('/'));
+ let id = path.strip_prefix("rimg/")?;
+ (!id.is_empty() && id.chars().all(|c| c.is_ascii_hexdigit() || c == '-'))
+ .then(|| format!("Attachment/{id}"))
+}
+
+/// A reminder's picture as the window can draw it: from disk when fetched before, from Apple
+/// when not, and a HEIC (what an iPhone takes) made a JPEG once — the engine draws no HEIC.
+async fn reminder_image_shown(app: &tauri::AppHandle, attachment: &str) -> Result<Vec<u8>, String> {
+ let dir = state_dir(app).join("reminder-media");
+ let safe = media_file_id(attachment);
+ let shown = dir.join(format!("{safe}-shown"));
+ if let Ok(bytes) = tokio::fs::read(&shown).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::reminders::more::attachment_file(&http, &root, params, attachment)
+ .await
+ .map_err(|e| e.to_string())?
+ .ok_or("no such picture")?;
+ let bytes = if quince_media::is_heif(&bytes) {
+ crate::cpu::run(move || quince_media::heic_to_jpeg(&bytes))
+ .await
+ .map_err(|e| e.to_string())??
+ } else {
+ bytes
+ };
+ tokio::fs::create_dir_all(&dir).await.ok();
+ let part = shown.with_extension("part");
+ if tokio::fs::write(&part, &bytes).await.is_ok() {
+ let _ = tokio::fs::rename(&part, &shown).await;
+ }
+ Ok(bytes)
+}
+
/// A note attachment's id as part of a file name in `note-media`: letters, digits and dashes,
/// so an id from a request is never a path.
fn media_file_id(id: &str) -> String {
@@ -283,7 +359,13 @@ async fn note_media_cached(
if let Some(dir) = path.parent() {
tokio::fs::create_dir_all(dir).await.ok();
}
- tokio::fs::write(&path, &bytes).await.ok();
+ // Whole or not at all: written beside it and renamed in, so a second request for the same
+ // picture (a drawing's light and dark ink, the viewer) never reads half a file — which
+ // the window took for a broken picture and showed as a file for the rest of the session.
+ let part = path.with_extension("part");
+ if tokio::fs::write(&part, &bytes).await.is_ok() {
+ let _ = tokio::fs::rename(&part, &path).await;
+ }
Ok(bytes)
}
@@ -437,61 +519,130 @@ async fn diagnostics_save(app: tauri::AppHandle, data: State<'_, Data>) -> UiRes
Ok(path.to_string_lossy().into_owned())
}
-/// What a note's attachment is, to draw it where it sits.
+/// What a note's attachment is, to draw it where it sits. Asked of Apple once and kept in the
+/// library — an attachment never changes under its id — so a note opens on its pictures and
+/// cards at once, offline too, instead of two lookups per attachment every time it is drawn.
+/// Read only: nothing is written to Apple.
#[tauri::command]
async fn note_attachment_info(
id: String,
auth: State<'_, Auth>,
-) -> UiResult<quince_icloud::note_media::AttachmentInfo> {
+ data: State<'_, Data>,
+) -> UiResult<serde_json::Value> {
+ let key = format!("notes.attachment.{id}");
+ if let Ok(Some(kept)) = data.0.lock().await.state(&key) {
+ if let Ok(info) = serde_json::from_str::<serde_json::Value>(&kept) {
+ return Ok(info);
+ }
+ }
let (http, root, params) = cloudkit_context(&auth).await?;
- quince_icloud::note_media::info(&http, &root, params, &id)
+ let info = quince_icloud::note_media::info(&http, &root, params, &id)
.await
- .map_err(|e| e.to_string())
+ .map_err(|e| e.to_string())?;
+ let info = serde_json::to_value(&info).map_err(|e| e.to_string())?;
+ if let Ok(json) = serde_json::to_string(&info) {
+ let _ = data.0.lock().await.set_state(&key, &json);
+ }
+ Ok(info)
}
/// 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.
+/// saved beside the others under its own name, and handed over. Opened before, it is handed
+/// over from where it was saved at once — an attachment never changes under its id — with
+/// nothing asked of Apple: asking its name again first, every time, kept each open waiting a
+/// round trip, and behind the session's lock whenever a check of the session held it.
#[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?;
+ timing::mark("attachment asked");
let folder: String = id.chars().filter(char::is_ascii_alphanumeric).collect();
if folder.is_empty() {
return Err("That attachment is not one Skykeep knows.".into());
}
+ let dir = state_dir(&app).join("note-files").join(&folder);
+ if let Some(path) = saved_attachment(&dir).await {
+ return hand_over_attachment(&app, &path).await;
+ }
+ // Its name and its bytes asked for together, not one after the other.
+ let (http, root, params) = cloudkit_context(&auth).await?;
+ let (info, bytes) = tokio::join!(
+ quince_icloud::note_media::info(&http, &root, params, &id),
+ note_media_cached(&app, &id, quince_icloud::note_media::Part::File),
+ );
+ let info = info.map_err(|e| e.to_string())?;
+ let bytes = bytes?;
+ timing::mark("attachment fetched");
// The name is whoever shared the note's to choose: made a plain file name here, never a
// path, and never one that pretends to be something else.
let name = attachment_name(info.filename.as_deref(), &folder);
- let dir = state_dir(&app).join("note-files").join(&folder);
tokio::fs::create_dir_all(&dir)
.await
.map_err(|e| e.to_string())?;
let path = dir.join(&name);
- tokio::fs::write(&path, &bytes)
+ // Written beside it and renamed into place: a file cut short by a crash is never the one a
+ // later open finds and hands over. Hidden (a leading dot) until whole, which no saved name
+ // has.
+ let partial = dir.join(".partial");
+ tokio::fs::write(&partial, &bytes)
.await
.map_err(|e| e.to_string())?;
// Readable by this user alone, and never runnable, whatever was there before.
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
- tokio::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))
+ tokio::fs::set_permissions(&partial, std::fs::Permissions::from_mode(0o600))
.await
.map_err(|e| e.to_string())?;
}
+ tokio::fs::rename(&partial, &path)
+ .await
+ .map_err(|e| e.to_string())?;
+ hand_over_attachment(&app, &path).await
+}
+
+/// The attachment saved in `dir` by an earlier open: the one whole file there.
+async fn saved_attachment(dir: &std::path::Path) -> Option<PathBuf> {
+ let mut entries = tokio::fs::read_dir(dir).await.ok()?;
+ let mut found = None;
+ while let Ok(Some(entry)) = entries.next_entry().await {
+ if entry.file_name().to_string_lossy().starts_with('.') {
+ continue;
+ }
+ if !entry.file_type().await.is_ok_and(|t| t.is_file()) || found.is_some() {
+ return None;
+ }
+ found = Some(entry.path());
+ }
+ found
+}
+
+/// A saved attachment handed to the app this computer uses for it — or, if it is a program,
+/// a script or a launcher, shown in its folder instead: opening it would run it, and a shared
+/// note can carry one from anyone.
+async fn hand_over_attachment(app: &tauri::AppHandle, path: &std::path::Path) -> UiResult<()> {
use tauri_plugin_opener::OpenerExt;
- // A program, a script or a launcher is shown in its folder, not opened: opening it would
- // run it, and a shared note can carry one from anyone.
- if runs_code(&name, &bytes) {
+ use tokio::io::AsyncReadExt;
+ let name = path
+ .file_name()
+ .map(|n| n.to_string_lossy().into_owned())
+ .unwrap_or_default();
+ // What `runs_code` reads of a file: its first bytes.
+ let mut head = Vec::with_capacity(64);
+ tokio::fs::File::open(path)
+ .await
+ .map_err(|e| e.to_string())?
+ .take(64)
+ .read_to_end(&mut head)
+ .await
+ .map_err(|e| e.to_string())?;
+ timing::mark("attachment handed over");
+ if runs_code(&name, &head) {
return app
.opener()
- .reveal_item_in_dir(&path)
+ .reveal_item_in_dir(path)
.map_err(|e| e.to_string());
}
app.opener()
@@ -707,30 +858,62 @@ fn state_dir(app: &tauri::AppHandle) -> PathBuf {
}
#[tauri::command]
-async fn auth_status(auth: State<'_, Auth>) -> UiResult<Status> {
- let client = auth.client.lock().await;
+async fn auth_status(auth: State<'_, Auth>, data: State<'_, Data>) -> UiResult<Status> {
+ timing::mark("auth_status asked");
+ let known = |facts: Option<SessionFacts>| {
+ let mut kept = auth
+ .known
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ match facts {
+ Some(facts) => {
+ *kept = facts.clone();
+ facts
+ }
+ None => kept.clone(),
+ }
+ };
+ // Busy (a resume, a sign-in, the timer's check): what was last known, rather than a wait.
+ let facts = match auth.client.try_lock() {
+ Ok(client) => known(Some(SessionFacts::of(&client))),
+ Err(_) => known(None),
+ };
+ let owner = data.0.lock().await.state(ACCOUNT_KEY).ok().flatten();
+ timing::mark("auth_status answered");
Ok(Status {
- has_stored_session: client.has_stored_session(),
- signed_in: client.session().webservices.is_some(),
+ has_stored_session: facts.has_stored_session,
+ signed_in: facts.signed_in,
+ library_ready: facts.has_stored_session
+ && facts.account.is_some()
+ && owner == facts.account,
})
}
/// Try the stored session. `false` just means a sign-in is needed — not an error.
#[tauri::command]
async fn auth_resume(app: tauri::AppHandle, auth: State<'_, Auth>) -> UiResult<&'static str> {
+ timing::mark("auth_resume asked");
if LIVE.load(Ordering::SeqCst) {
return Ok("library");
}
let outcome = {
let mut client = auth.client.lock().await;
+ // Another window took the session up while this one waited for it (each window asks
+ // as it opens): asking Apple again would only be a second wait.
+ if LIVE.load(Ordering::SeqCst) {
+ return Ok("library");
+ }
let outcome = resume_session(&mut client).await?;
+ timing::mark("auth_resume: session resumed");
if outcome == "library" {
signed_in(&app, &mut client).await?;
+ timing::mark("auth_resume: library claimed");
}
outcome
};
if outcome == "library" {
folders_up(&app).await;
+ timing::mark("auth_resume: folders up");
}
Ok(outcome)
}
@@ -741,7 +924,11 @@ async fn resume_session(client: &mut Client) -> UiResult<&'static str> {
// Offline with a session kept: the library opens on what it holds, as a local-first
// app should, and the next refresh — on the timer, or when the network is back —
// signs back in.
- Err(quince_auth::Error::Network(_)) if client.has_stored_session() => true,
+ Err(quince_auth::Error::Network(_) | quince_auth::Error::Unavailable(_))
+ if client.has_stored_session() =>
+ {
+ true
+ }
Err(e) => return Err(e.to_string()),
};
// Back in; or back in but for the code Apple wants before trusting this computer again;
@@ -1021,6 +1208,12 @@ async fn signed_in(app: &tauri::AppHandle, client: &mut Client) -> Result<(), St
return Err(e);
}
LIVE.store(true, Ordering::SeqCst);
+ if let Some(auth) = app.try_state::<Auth>() {
+ *auth
+ .known
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) = SessionFacts::of(client);
+ }
Ok(())
}
@@ -1513,6 +1706,27 @@ async fn event_alerts(
.map_err(|e| e.to_string())
}
+/// An event's guests and their answers, as Apple holds them, the organizer first. Read only.
+#[tauri::command]
+async fn event_guests(
+ guid: String,
+ auth: State<'_, Auth>,
+ data: State<'_, Data>,
+) -> UiResult<Vec<quince_icloud::calendar::Guest>> {
+ let event = {
+ let library = data.0.lock().await;
+ library.event(&guid).map_err(|e| e.to_string())?
+ };
+ let Some(event) = event else {
+ return Ok(Vec::new());
+ };
+ let (http, root, params) = calendar_context(&auth).await?;
+ quince_icloud::calendar::CalendarClient::new(&http, &root, params)
+ .guests(&event)
+ .await
+ .map_err(|e| e.to_string())
+}
+
/// How an event repeats, as Apple holds it.
#[tauri::command]
async fn event_repeat(
@@ -1759,6 +1973,32 @@ fn save_subscriptions(
std::fs::rename(&tmp, &path).map_err(|e| e.to_string())
}
+/// What Skykeep can reach, for Settings: Apple's domains as the network lock holds them
+/// (`quince_auth::APPLE_DOMAINS`, the list the resolver checks), and the host of each calendar
+/// subscribed to, which only its own client can reach.
+#[derive(serde::Serialize)]
+struct Reach {
+ apple: Vec<&'static str>,
+ subscribed: Vec<String>,
+}
+
+#[tauri::command]
+async fn network_reach(feeds: State<'_, Feeds>) -> UiResult<Reach> {
+ let mut subscribed: Vec<String> = feeds
+ .subs
+ .lock()
+ .await
+ .iter()
+ .filter_map(|(s, _)| feeds::host_of(&s.url))
+ .collect();
+ subscribed.sort();
+ subscribed.dedup();
+ Ok(Reach {
+ apple: quince_auth::APPLE_DOMAINS.to_vec(),
+ subscribed,
+ })
+}
+
/// Fetch one subscription's file with the client that reaches its host and nothing else.
async fn fetch_subscription(url: &str) -> UiResult<(String, feeds::Feed)> {
let host = feeds::host_of(url).ok_or("That address has no server in it.")?;
@@ -2292,11 +2532,22 @@ async fn set_done(
_list_guid: &str,
done: bool,
) -> UiResult<()> {
- let reminder = {
+ let (reminder, last) = {
let library = data.0.lock().await;
- reminder_to_write(&library, guid)?
+ let reminder = reminder_to_write(&library, guid)?;
+ // The last tick of a repeat that ends: completed, as the phone completes it, rather
+ // than moved past its End Repeat date.
+ let end = library
+ .reminder_repeat_end(guid)
+ .map_err(|e| e.to_string())?;
+ let days = library
+ .reminder_repeat_days(guid)
+ .map_err(|e| e.to_string())?;
+ let last =
+ done && reminder.tick_ends_series_on(end, &days, jiff::Timestamp::now().as_second());
+ (reminder, last)
};
- if !(done && reminder.repeats()) {
+ if last || !(done && reminder.repeats()) {
let now = jiff::Timestamp::now().as_second();
let payload =
serde_json::to_string(&outbox::Done { done, at: now }).map_err(|e| e.to_string())?;
@@ -2337,6 +2588,10 @@ async fn reminder_set_repeat(
// The list the window saw it in: a hint that can be stale, never checked (reminder_to_write).
#[allow(unused_variables)] list_guid: String,
repeat: Option<quince_icloud::reminders::Repeat>,
+ // End Repeat On Date, in seconds; absent repeats for ever.
+ end_at: Option<i64>,
+ // A weekly repeat's weekdays, 1 Sunday … 7 Saturday; absent falls on the due date's day.
+ days_of_week: Option<Vec<i64>>,
auth: State<'_, Auth>,
data: State<'_, Data>,
) -> UiResult<()> {
@@ -2347,12 +2602,14 @@ async fn reminder_set_repeat(
reminder_to_write(&library, &guid)?
};
- quince_icloud::reminders::set_recurrence_cloudkit(
+ quince_icloud::reminders::set_repeat_until_cloudkit(
&http,
&root,
params.clone(),
&reminder,
repeat,
+ end_at,
+ days_of_week.as_deref().unwrap_or(&[]),
)
.await
.map_err(|e| e.to_string())?;
@@ -2672,11 +2929,16 @@ 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.
-/// Whether Quince writes to Notes tables. OFF: a cell and a row and a column written here
-/// showed on his iPhone (2026-10-21), but Notes there then kept two conflict copies of the note,
-/// one with the written cells' text doubled and tripled — it could not merge these edits
-/// cleanly. No table is written until a write is shown to merge on the phone with no copy.
-const TABLE_CELL_WRITES: bool = false;
+/// Whether Quince writes to Notes tables.
+///
+/// Cells: ON. On 2026-10-21 cell, row and column writes showed on his iPhone but left two
+/// conflict copies with the text doubled — this app's writer had been appended to the table's
+/// writer list out of uuid order. With the list kept sorted, a cell written here (2026-10-22,
+/// supervised, on his account) showed once on his iPhone with no conflict copy.
+///
+/// Rows and columns: still OFF. Only a cell write was tried live after the fix; adding or
+/// removing a row or column has not been watched on a phone since.
+const TABLE_CELL_WRITES: bool = true;
const TABLE_LINE_WRITES: bool = false;
const TABLE_WRITES_OFF: &str =
"Tables are read-only in Skykeep for now: edits made here didn’t merge cleanly on iPhone yet.";
@@ -3154,12 +3416,15 @@ async fn contact_list_write(
/// related names, social profiles — is written back untouched rather than dropped.
#[tauri::command]
async fn contact_save(
- contact: Contact,
+ contact: quince_core::contacts::Card,
// The card as the form opened it: only what differs from it is written.
- base: Option<Contact>,
+ base: Option<quince_core::contacts::Card>,
data: State<'_, Data>,
) -> UiResult<String> {
- if contact.guid.is_empty() && quince_icloud::contacts::blank_card(&contact) {
+ if contact.contact.guid.is_empty()
+ && quince_icloud::contacts::blank_card(&contact.contact)
+ && contact.details.is_empty()
+ {
return Err("Add a name, a phone number or an email address first.".into());
}
// In the library at once — a new card under the id it will have at Apple — and queued
@@ -3167,7 +3432,7 @@ async fn contact_save(
// model — a photo, related names, social profiles — is written back untouched.
let guid = {
let mut library = data.0.lock().await;
- outbox::record_contact_save(&mut library, &contact, base).map_err(|e| e.to_string())?
+ outbox::record_card_save(&mut library, &contact, base).map_err(|e| e.to_string())?
};
outbox::kick();
Ok(guid)
@@ -3338,11 +3603,12 @@ async fn contact_set_me(
/// The address book, optionally filtered by name or by any stored number or address.
#[tauri::command]
-async fn contacts_list(search: Option<String>, data: State<'_, Data>) -> UiResult<Vec<Contact>> {
+async fn contacts_list(
+ search: Option<String>,
+ data: State<'_, Data>,
+) -> UiResult<Vec<quince_core::contacts::Card>> {
let library = data.0.lock().await;
- library
- .contacts(search.as_deref())
- .map_err(|e| e.to_string())
+ library.cards(search.as_deref()).map_err(|e| e.to_string())
}
#[tauri::command]
@@ -3837,7 +4103,11 @@ async fn drive_upload(
)
.ok();
- let results: Vec<Option<String>> = futures_util::stream::iter(jobs)
+ // Every file's stop is made and registered before any starts, so Cancel — the batch's, or
+ // one waiting file's ✕ — reaches the files still waiting. Made as each began (three at a
+ // time), only those three could be stopped and every other planned file went on up.
+ let prepared: Vec<_> = jobs
+ .into_iter()
.map(|job| {
let (app, http, docws, root, params) = (
app.clone(),
@@ -3925,6 +4195,8 @@ async fn drive_upload(
}
}
})
+ .collect();
+ let results: Vec<Option<String>> = futures_util::stream::iter(prepared)
.buffer_unordered(3)
.collect()
.await;
@@ -4434,16 +4706,25 @@ async fn contact_photo(
}
}
- let (http, params) = {
- let auth = app.state::<Auth>();
- let client = auth.client.lock().await;
- (client.http().clone(), client.service_params())
+ // A picture chosen here and not yet at Apple is the image itself, as icloud.com sends it.
+ let bytes = if let Some(data) = photo.url.strip_prefix("data:") {
+ use base64::Engine;
+ let (_, encoded) = data
+ .split_once(',')
+ .ok_or("that picture could not be read")?;
+ base64::engine::general_purpose::STANDARD.decode(encoded)?
+ } else {
+ let (http, params) = {
+ let auth = app.state::<Auth>();
+ let client = auth.client.lock().await;
+ (client.http().clone(), client.service_params())
+ };
+ let response = http.get(&photo.url).query(&params).send().await?;
+ if !response.status().is_success() {
+ return Err(format!("Apple returned {}", response.status()).into());
+ }
+ response.bytes().await?.to_vec()
};
- let response = http.get(&photo.url).query(&params).send().await?;
- if !response.status().is_success() {
- return Err(format!("Apple returned {}", response.status()).into());
- }
- let bytes = response.bytes().await?.to_vec();
// Cut to the square its owner chose and sized for a face, off the interface's thread.
// Apple stores these whole — one of them is 1696x2528 — and a list of them has to scroll.
@@ -4596,19 +4877,23 @@ pub(crate) fn tiling_compositor() -> bool {
/// never says so still leaves a window to use.
#[tauri::command]
fn window_ready(app: tauri::AppHandle, window: tauri::WebviewWindow, needs_you: Option<bool>) {
+ timing::mark(format_args!("window_ready {}", window.label()));
// An app's own window (Notes, Reminders…): shown once it has drawn.
if window.label() != "main" {
apps::show(&window);
return;
}
- // Opened as one app from its launcher entry: the whole-library window stays put away.
- if LAUNCHED_AS_APP.load(Ordering::SeqCst) {
+ // Opened as one app from its launcher entry: the whole-library window stays put away —
+ // unless it was asked for since, and made for that (show_window).
+ if LAUNCHED_AS_APP.load(Ordering::SeqCst) && !MAIN_ASKED.load(Ordering::SeqCst) {
return;
}
// Started at login, with nothing for the person to do: everything runs, the window waits
// in the tray.
// Never without the tray to come back from.
- if app.tray_by_id("quince").is_some() && login::stay_hidden(needs_you.unwrap_or(true)) {
+ if tray_reachable(&app) && login::stay_hidden(needs_you.unwrap_or(true)) {
+ // Its page has done what a launch needs of it (the session taken up again): it waits,
+ // drawn and hidden, so the tray opens it at once.
return;
}
show_window(&app);
@@ -4668,17 +4953,318 @@ fn show_when_ready(app: &tauri::AppHandle) {
});
}
-/// Bring the window back, wherever it went.
-fn show_window(app: &tauri::AppHandle) {
+/// The whole-library window was asked for after a launch as one app, which does not make it.
+static MAIN_ASKED: AtomicBool = AtomicBool::new(false);
+
+/// The whole-library window, made hidden (tauri.conf.json's "main"; shown by its window_ready
+/// once drawn). Not made at startup by Tauri: a launch as one app (`--app notes`) built it
+/// anyway, a second web view loading the whole library, resuming the session and starting a
+/// refresh behind the one window asked for — contending with it for every step of its launch.
+fn make_main(app: &tauri::AppHandle) -> Option<tauri::WebviewWindow> {
if let Some(window) = app.get_webview_window("main") {
+ return Some(window);
+ }
+ let config = app
+ .config()
+ .app
+ .windows
+ .iter()
+ .find(|w| w.label == "main")?
+ .clone();
+ let window = match tauri::WebviewWindowBuilder::from_config(app, &config)
+ .and_then(tauri::WebviewWindowBuilder::build)
+ {
+ Ok(window) => window,
+ Err(e) => {
+ quiet!("the window could not be made: {e}");
+ return None;
+ }
+ };
+ timing::mark("main made");
+ // A tiling compositor places, sizes and closes windows itself; a title bar with minimise
+ // and maximise there only takes room and does nothing it does not. On a desktop that
+ // floats windows — GNOME, KDE — it is how a window is moved, so it stays.
+ if tiling_compositor() {
+ window.set_decorations(false).ok();
+ }
+ Some(window)
+}
+
+/// Bring the window back, wherever it went; made first if this launch had not made it. Answers
+/// whether it had to be made — its page is then still loading, not yet listening.
+fn show_window(app: &tauri::AppHandle) -> bool {
+ if let Some(window) = app.get_webview_window("main") {
+ timing::mark("main shown");
window.show().ok();
window.unminimize().ok();
window.set_focus().ok();
+ return false;
+ }
+ MAIN_ASKED.store(true, Ordering::SeqCst);
+ let Some(window) = make_main(app) else {
+ return false;
+ };
+ // Shown by its window_ready once drawn; shown anyway if that never comes.
+ tauri::async_runtime::spawn(async move {
+ tokio::time::sleep(Duration::from_secs(3)).await;
+ if !window.is_visible().unwrap_or(true) {
+ window.show().ok();
+ window.set_focus().ok();
+ }
+ });
+ true
+}
+
+/// `then`, once the whole-library window can hear it: at once if it was open, or once a window
+/// just made has drawn (its page is up, and listening, by then) — never sent to a page still
+/// loading, which would drop it.
+pub(crate) fn show_window_then(
+ app: &tauri::AppHandle,
+ then: impl FnOnce(&tauri::AppHandle) + Send + 'static,
+) {
+ if !show_window(app) {
+ then(app);
+ return;
+ }
+ let app = app.clone();
+ tauri::async_runtime::spawn(async move {
+ let until = std::time::Instant::now() + Duration::from_secs(5);
+ while std::time::Instant::now() < until {
+ if app
+ .get_webview_window("main")
+ .is_some_and(|w| w.is_visible().unwrap_or(false))
+ {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ then(&app);
+ });
+}
+
+/// The web views' memory cache, sized for an app rather than a browser. WebKitGTK's default
+/// (the "web browser" model) keeps up to half a gigabyte of decoded pictures on a 16 GB
+/// machine, for pages a browser expects to be revisited. Here every picture is this app's own,
+/// served from disk in a few milliseconds by the `quince` scheme, so keeping them gained
+/// nothing: measured on 1,589 photos (the Hidden album), one scroll through left the web
+/// process 650 MB larger, and it stayed so after leaving Photos. The "document viewer" model
+/// keeps what is on screen and near it, gives the rest back, and keeps no disk cache of a
+/// page that is never fetched over the network. Set on the one web context every window
+/// shares, so once is enough; each new window sets it again harmlessly.
+#[cfg(target_os = "linux")]
+fn app_cache(webview: &tauri::Webview) {
+ let done = webview.with_webview(|platform| {
+ use webkit2gtk::{WebContextExt, WebViewExt};
+ if let Some(context) = platform.inner().context() {
+ context.set_cache_model(webkit2gtk::CacheModel::DocumentViewer);
+ }
+ });
+ if let Err(e) = done {
+ quiet!("the web view's cache could not be set: {e}");
}
}
+#[cfg(not(target_os = "linux"))]
+fn app_cache(_webview: &tauri::Webview) {}
+
+/// Whether the tray icon can be seen, so a closed window can be put away behind it. On Linux a
+/// tray icon is a StatusNotifierItem, shown only where a host is on the session bus (KDE's
+/// panel, waybar, Quickshell, Ubuntu's AppIndicator extension…). Stock GNOME (Fedora, Debian)
+/// has none: the icon is made and never shown, and a window put away there left Skykeep running
+/// with no way back but its launcher and no way to quit at all. Where no host is there, closing
+/// the window quits, as it does where no tray could be made.
+///
+/// Asked when it matters rather than once at start, because a panel started at login can
+/// register after Skykeep. A bus that cannot be asked is taken as a tray that is there.
+#[cfg(target_os = "linux")]
+fn tray_reachable(_app: &tauri::AppHandle) -> bool {
+ linux_tray::made() && status_notifier_host().unwrap_or(true)
+}
+
+#[cfg(not(target_os = "linux"))]
+fn tray_reachable(app: &tauri::AppHandle) -> bool {
+ app.tray_by_id("quince").is_some()
+}
+
+/// Whether a StatusNotifierItem host is registered: `None` when the session bus cannot be
+/// asked, `Some(false)` when no watcher, or no host behind it, is there.
+#[cfg(target_os = "linux")]
+fn status_notifier_host() -> Option<bool> {
+ let bus = zbus::blocking::connection::Builder::session()
+ .ok()?
+ .method_timeout(Duration::from_secs(1))
+ .build()
+ .ok()?;
+ let reply = bus.call_method(
+ Some("org.kde.StatusNotifierWatcher"),
+ "/StatusNotifierWatcher",
+ Some("org.freedesktop.DBus.Properties"),
+ "Get",
+ &(
+ "org.kde.StatusNotifierWatcher",
+ "IsStatusNotifierHostRegistered",
+ ),
+ );
+ let reply = match reply {
+ Ok(reply) => reply,
+ // No watcher on the bus at all: nothing shows tray icons here.
+ Err(zbus::Error::MethodError(name, _, _))
+ if name.as_str() == "org.freedesktop.DBus.Error.ServiceUnknown" =>
+ {
+ return Some(false)
+ }
+ Err(_) => return None,
+ };
+ let value: zbus::zvariant::OwnedValue = reply.body().deserialize().ok()?;
+ Some(bool::try_from(value).unwrap_or(false))
+}
+
+/// The tray on Linux: a StatusNotifierItem spoken over D-Bus by ksni, not Tauri's tray.
+/// Tauri's goes through libayatana-appindicator, which never passes a click on — a left click
+/// could only open the menu. Here a left click (the host's Activate) opens the window at once,
+/// and the right click's menu is the one Windows and macOS have.
+///
+/// Made even where no host is there yet (`assume_sni_available`): a panel that starts after
+/// Skykeep at login picks the icon up when it registers. Where none ever does (stock GNOME),
+/// `tray_reachable` says so, and closing the window quits.
+#[cfg(target_os = "linux")]
+mod linux_tray {
+ use super::{intake, show_window, shutdown};
+ use ksni::TrayMethods;
+ use std::sync::atomic::{AtomicBool, Ordering};
+
+ static MADE: AtomicBool = AtomicBool::new(false);
+
+ /// Whether the tray's D-Bus service is up.
+ pub fn made() -> bool {
+ MADE.load(Ordering::SeqCst)
+ }
+
+ struct SkykeepTray {
+ app: tauri::AppHandle,
+ icon: Vec<ksni::Icon>,
+ }
+
+ impl SkykeepTray {
+ /// `then` on the main thread, where the windows live; the tray's calls arrive on
+ /// ksni's own.
+ fn on_main(&self, then: fn(&tauri::AppHandle)) {
+ let app = self.app.clone();
+ self.app.run_on_main_thread(move || then(&app)).ok();
+ }
+ }
+
+ impl ksni::Tray for SkykeepTray {
+ fn id(&self) -> String {
+ "skykeep".into()
+ }
+ fn title(&self) -> String {
+ "Skykeep".into()
+ }
+ fn icon_pixmap(&self) -> Vec<ksni::Icon> {
+ self.icon.clone()
+ }
+ fn tool_tip(&self) -> ksni::ToolTip {
+ ksni::ToolTip {
+ title: "Skykeep".into(),
+ ..Default::default()
+ }
+ }
+ // The left click.
+ fn activate(&mut self, _x: i32, _y: i32) {
+ self.on_main(|app| {
+ show_window(app);
+ });
+ }
+ fn menu(&self) -> Vec<ksni::MenuItem<Self>> {
+ use ksni::menu::StandardItem;
+ use ksni::MenuItem;
+ let item = |label: &str, then: fn(&tauri::AppHandle)| -> MenuItem<Self> {
+ StandardItem {
+ label: label.into(),
+ activate: Box::new(move |tray: &mut Self| tray.on_main(then)),
+ ..Default::default()
+ }
+ .into()
+ };
+ // The same four lines as Tauri's tray on Windows and macOS (build_tray).
+ vec![
+ item("Open Skykeep", |app| {
+ show_window(app);
+ }),
+ MenuItem::Separator,
+ item("New Reminder", |app| intake::capture(app, "reminder")),
+ item("New Note", |app| intake::capture(app, "note")),
+ MenuItem::Separator,
+ item("Quit Skykeep", |app| shutdown(app, 0)),
+ ]
+ }
+ // A panel restarting, or not there yet: the icon comes back when it does.
+ fn watcher_offline(&self, _reason: ksni::OfflineReason) -> bool {
+ true
+ }
+ }
+
+ /// The tray's mark at every size a panel draws one, each made from the vector master with
+ /// a margin all round (as Vesktop's), as StatusNotifierItem wants it: ARGB32, in network
+ /// byte order. Given only 64px, a panel shrank it itself — soft, and the k clipped at an
+ /// edge it rounded off.
+ fn pixmap() -> Vec<ksni::Icon> {
+ let sizes: [&[u8]; 6] = [
+ include_bytes!("../icons/tray-16.png"),
+ include_bytes!("../icons/tray-22.png"),
+ include_bytes!("../icons/tray-24.png"),
+ include_bytes!("../icons/tray-32.png"),
+ include_bytes!("../icons/tray-48.png"),
+ include_bytes!("../icons/tray-64.png"),
+ ];
+ sizes
+ .iter()
+ .filter_map(|bytes| tauri::image::Image::from_bytes(bytes).ok())
+ .map(|image| ksni::Icon {
+ width: image.width() as i32,
+ height: image.height() as i32,
+ data: image
+ .rgba()
+ .chunks_exact(4)
+ .flat_map(|p| [p[3], p[0], p[1], p[2]])
+ .collect(),
+ })
+ .collect()
+ }
+
+ pub fn spawn(app: tauri::AppHandle) {
+ let tray = SkykeepTray {
+ app,
+ icon: pixmap(),
+ };
+ // Inside the Flatpak sandbox the per-process bus name the spec asks for cannot be
+ // owned; the watcher takes the item by its unique name instead.
+ let sandboxed = std::path::Path::new("/.flatpak-info").exists();
+ tauri::async_runtime::spawn(async move {
+ match tray
+ .disable_dbus_name(sandboxed)
+ .assume_sni_available(true)
+ .spawn()
+ .await
+ {
+ // The service runs on its own; the handle is only for changing it later.
+ Ok(_handle) => MADE.store(true, Ordering::SeqCst),
+ Err(e) => quiet!("no tray on this desktop, so closing the window quits: {e}"),
+ }
+ });
+ }
+}
+
+#[cfg(target_os = "linux")]
+fn build_tray(app: &tauri::App) -> tauri::Result<()> {
+ linux_tray::spawn(app.handle().clone());
+ Ok(())
+}
+
/// A place in the tray, so Quince stays running — and ringing reminders — with its window
/// closed, and can be opened again or quit from there.
+#[cfg(not(target_os = "linux"))]
fn build_tray(app: &tauri::App) -> tauri::Result<()> {
use tauri::menu::PredefinedMenuItem;
use tauri::menu::{Menu, MenuItem};
@@ -4703,7 +5289,9 @@ fn build_tray(app: &tauri::App) -> tauri::Result<()> {
// the menu is the right click's. A Mac menu-bar extra opens its menu on any click.
.show_menu_on_left_click(cfg!(target_os = "macos"))
.on_menu_event(|app, event| match event.id.as_ref() {
- "open" => show_window(app),
+ "open" => {
+ show_window(app);
+ }
"quit" => shutdown(app, 0),
"new:reminder" => intake::capture(app, "reminder"),
"new:note" => intake::capture(app, "note"),
@@ -4738,6 +5326,7 @@ fn build_tray(app: &tauri::App) -> tauri::Result<()> {
}
fn main() {
+ timing::start();
login::note_launch();
steady_drawing();
smooth_video();
@@ -4748,6 +5337,7 @@ fn main() {
let mut context = tauri::generate_context!();
let current = context.config().identifier.clone();
let identifier = migrate::at_launch(&current);
+ timing::mark("identifier settled");
if identifier != current {
context.config_mut().identifier = identifier;
}
@@ -4764,6 +5354,7 @@ fn main() {
// One Quince at a time: opening it again brings back the one already running, which
// may be sitting in the tray with its window closed.
.plugin(tauri_plugin_single_instance::init(|app, args, cwd| {
+ timing::mark("handed a launch");
// A file opened with Skykeep, or a quick capture (`--new reminder`): handled
// here, in the one already running.
if intake::arrived(app, &args, std::path::Path::new(&cwd)) {
@@ -4772,7 +5363,9 @@ fn main() {
// `--app notes` from a launcher entry: that app's window, in this same process.
match apps::asked(&args) {
Some(key) => apps::open(app, key),
- None => show_window(app),
+ None => {
+ show_window(app);
+ }
}
}))
// Each window — the library, and every app's own — reopens at the size and place it was
@@ -4814,11 +5407,12 @@ fn main() {
}
inside
})
+ .on_webview_ready(|webview| app_cache(&webview))
.build(),
)
// Closing the window hides it rather than quitting, so reminders still ring. Quit is
- // in the tray. Where no tray could be made there is nowhere to come back from, so
- // there closing quits as it always did.
+ // in the tray. Where no tray could be made, or none is shown (tray_reachable), there
+ // is nowhere to come back from, so there closing quits as it always did.
// Files dropped on a window are the person's to hand over: granted to the commands
// that read them (grants.rs) here, before the page hears of the drop.
.on_webview_event(|_, event| {
@@ -4830,16 +5424,23 @@ fn main() {
if let tauri::WindowEvent::DragDrop(drop) = event {
grants::dropped(drop);
}
+ // Coming back to a window is when a change made elsewhere is looked for at once.
+ if let tauri::WindowEvent::Focused(true) = event {
+ push::wake();
+ }
// The whole-library window is put away, as the engine keeps running behind the
// tray. An app's own window is put away too, so opening it again is instant rather
// than a new web view built from nothing — and given back for good once it has
// gone unused for a while, so six put-away windows do not sit on memory.
if let tauri::WindowEvent::CloseRequested { api, .. } = event {
- if window.app_handle().tray_by_id("quince").is_none() {
+ if !tray_reachable(window.app_handle()) {
return;
}
if window.label() == "main" {
api.prevent_close();
+ // Hidden, never given back: the tray's click shows it at once, already
+ // drawn. Remade on demand it took about half a second, which the founder
+ // asked to be gone; keeping its web view costs about 190 MB in the tray.
window.hide().ok();
} else if window.label().starts_with("app-") {
api.prevent_close();
@@ -4858,6 +5459,7 @@ fn main() {
let uri = request.uri();
let wanted = photo_guid(uri.host(), uri.path());
let attachment = note_part(uri.path());
+ let reminder_image = reminder_image_part(uri.path());
// A drawing's ink for a dark page, rather than a light one.
let ink_dark = uri.path().ends_with("drawing-dark");
let picture = photos::requested(uri.path());
@@ -4908,6 +5510,21 @@ fn main() {
responder.respond(response.unwrap_or_default());
return;
}
+ // A picture attached to a reminder.
+ if let Some(id) = reminder_image {
+ let response = match reminder_image_shown(&app, &id).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;
+ }
// 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_shown(&app, &id, part, ink_dark).await {
@@ -4961,23 +5578,29 @@ fn main() {
});
})
.setup(|app| {
+ timing::mark("setup");
video::serve(app.handle().clone());
let dir = state_dir(app.handle());
keep_private(&dir);
- let client = Arc::new(Mutex::new(Client::new(&dir)?));
+ let client = Client::new(&dir)?;
+ let known = std::sync::Mutex::new(SessionFacts::of(&client));
+ let client = Arc::new(Mutex::new(client));
app.manage(Auth {
client: Arc::clone(&client),
signing_in: AtomicBool::new(false),
+ known,
});
// The local library. Opened once at startup so every command shares one
// connection and the WAL behaves.
let mut library = Library::open(&dir)?;
+ timing::mark("library open");
adopt_writer(&mut library);
app.manage(Data(Mutex::new(library)));
// The sender of edits made offline, started once what it sends with — the session
// and the library — is in place: started first, its opening pass found neither and
// its task died, and nothing waiting was sent all session.
outbox::start(app.handle().clone());
+ appearance::watch(app.handle().clone());
// A photo cache past what this computer can spare now — the disk filled since —
// is brought back under its budget first thing.
let trim = app.handle().clone();
@@ -5047,14 +5670,6 @@ fn main() {
search_provider::serve(app.handle().clone());
alerts::spawn(app.handle().clone());
alerts::spawn_events(app.handle().clone());
- // A tiling compositor places, sizes and closes windows itself; a title bar with
- // minimise and maximise there only takes room and does nothing it does not. On a
- // desktop that floats windows — GNOME, KDE — it is how a window is moved, so it stays.
- if tiling_compositor() {
- if let Some(window) = app.get_webview_window("main") {
- window.set_decorations(false).ok();
- }
- }
if let Err(e) = build_tray(app) {
quiet!("no tray on this desktop, so closing the window quits: {e}");
}
@@ -5067,7 +5682,24 @@ fn main() {
LAUNCHED_AS_APP.store(true, Ordering::SeqCst);
apps::open(app.handle(), key);
}
+ // The whole-library window, unless this launch is one app's or one file's — then
+ // made a little later, hidden, once that app's window is up, so the tray still
+ // opens the whole library at once.
+ if !LAUNCHED_AS_APP.load(Ordering::SeqCst) {
+ make_main(app.handle());
+ } else {
+ let app = app.handle().clone();
+ tauri::async_runtime::spawn(async move {
+ tokio::time::sleep(Duration::from_secs(4)).await;
+ let warm = app.clone();
+ app.run_on_main_thread(move || {
+ make_main(&warm);
+ })
+ .ok();
+ });
+ }
show_when_ready(app.handle());
+ timing::mark("setup done");
// Photos uploads a quit left half done carry on.
photos::work(app.handle().clone());
Ok(())
@@ -5082,6 +5714,9 @@ fn main() {
outbox::outbox_resend,
outbox::outbox_discard,
outbox::outbox_wake,
+ appearance::system_contrast,
+ appearance::system_time_locale,
+ network_reach,
auth_status,
auth_resume,
auth_sign_in,
@@ -5115,6 +5750,7 @@ fn main() {
calendar_events,
event_save,
event_alerts,
+ event_guests,
event_repeat,
event_delete,
calendar_create,
@@ -5166,13 +5802,21 @@ fn main() {
mount::photos_folder_set,
mount::photos_folder_open,
photos::photo_video_turn,
+ photos::photo_video_zoom,
photos::photos_set_flag,
photos::photos_burst,
photos::photos_shared_albums,
photos::photos_shared_create,
photos::photos_shared_delete,
photos::photos_prepare,
+ photos::photos_index,
+ photos::photos_page,
+ photos::photos_get,
+ photo_cache::photos_cache_status,
+ photo_cache::photos_cache_set,
+ photo_cache::photos_cache_clear,
video::video_base,
+ video::video_support,
window_tint,
window_fullscreen,
photos::photos_upload,
@@ -5215,12 +5859,19 @@ fn main() {
contact_delete,
contacts_cmds::contact_addresses,
contacts_cmds::contact_address_edit,
+ contacts_merge::contacts_duplicates,
+ contacts_merge::contacts_merge,
+ contacts_merge::contacts_merge_undo,
notes_cmds::note_unlock,
notes_cmds::note_lock_hint,
notes_cmds::note_lock_forget,
notes_cmds::note_attach_file,
+ notes_cmds::note_attach_preview,
notes_cmds::note_attach_enabled,
reminders_cmds::reminder_detail,
+ reminders_cmds::reminder_more,
+ reminders_cmds::reminders_ending,
+ reminders_cmds::reminder_marks,
reminders_cmds::reminder_tags,
reminders_cmds::reminders_tagged,
reminders_cmds::reminder_smart_lists,
@@ -5256,6 +5907,19 @@ fn main() {
.build(context)
.expect("Skykeep failed to start")
.run(|_app, event| {
+ // The last window given back (put away, then closed for good — see apps::put_away)
+ // is not the app ending: it goes on behind the tray, ringing alerts and keeping
+ // the library current. Quit, a logout or a signal ends it through `shutdown`;
+ // with no tray to come back from, closing the window still quits.
+ if let tauri::RunEvent::ExitRequested {
+ code: None, api, ..
+ } = &event
+ {
+ if tray_reachable(_app) {
+ api.prevent_exit();
+ return;
+ }
+ }
// The iCloud Drive folder goes with the app: left mounted, it would answer
// nothing ("Transport endpoint is not connected").
if let tauri::RunEvent::Exit = event {
diff --git a/src-tauri/src/migrate.rs b/src-tauri/src/migrate.rs
index 3d0f4ca..c733178 100644
--- a/src-tauri/src/migrate.rs
+++ b/src-tauri/src/migrate.rs
@@ -167,11 +167,17 @@ impl Default for Mover<'_> {
/// identifier to run as — `current` (tauri.conf.json's), or an earlier one whose folders could
/// not be moved this time.
pub fn at_launch(current: &str) -> String {
- // One running under the current identifier: the single-instance plugin hands off to it.
- // Nothing is moved under a running app.
+ // One running under the current identifier: handed this launch's arguments, as the
+ // single-instance plugin would hand them, and this launch ends — here, before GTK, WebKit
+ // and Tauri are brought up only for the plugin to find the same instance and exit. Nothing
+ // is moved under a running app.
+ crate::timing::mark("asking for a running instance");
if instance::running(current) {
- return current.to_string();
+ instance::hand_off(current);
+ crate::timing::mark("handed off");
+ std::process::exit(0);
}
+ crate::timing::mark("none under the current identifier");
// One running under an earlier one (the build before this one, still open after an
// update, or this build after a failed move): it has the library open, so nothing moves
// under it. It is shown, as the single-instance plugin would show it, and this launch ends.
diff --git a/src-tauri/src/notes_cmds.rs b/src-tauri/src/notes_cmds.rs
index ecd4502..f08a03c 100644
--- a/src-tauri/src/notes_cmds.rs
+++ b/src-tauri/src/notes_cmds.rs
@@ -108,6 +108,36 @@ pub fn note_lock_forget() {
/// Add the file at `path` to a note at `at_offset` (UTF-16 units of `base`, the text the
/// editor shows, or of Apple's text when no base is given). Answers what was added, then
/// brings the library up to date.
+/// A small picture of a file about to be added to a note — shown at once while the file goes
+/// up to Apple, so adding never looks stuck. Only for a file the person just picked or dropped
+/// (the same grant the add itself checks), read on this computer, never sent anywhere. Empty
+/// for a file that is not a picture.
+#[tauri::command]
+pub async fn note_attach_preview(path: String) -> UiResult<tauri::ipc::Response> {
+ crate::grants::take_read(&path)?;
+ crate::cpu::run(move || {
+ let Ok(bytes) = std::fs::read(&path) else {
+ return Vec::new();
+ };
+ let bytes = if quince_media::is_heif(&bytes) {
+ match quince_media::heic_to_jpeg(&bytes) {
+ Ok(jpeg) => jpeg,
+ Err(_) => return Vec::new(),
+ }
+ } else {
+ bytes
+ };
+ match quince_media::fit(&bytes, 480) {
+ Ok(Some(small)) => small,
+ Ok(None) => bytes,
+ Err(_) => Vec::new(),
+ }
+ })
+ .await
+ .map(tauri::ipc::Response::new)
+ .map_err(|e| e.to_string())
+}
+
#[tauri::command]
pub async fn note_attach_file(
guid: String,
diff --git a/src-tauri/src/outbox.rs b/src-tauri/src/outbox.rs
index c6c030a..1763f6d 100644
--- a/src-tauri/src/outbox.rs
+++ b/src-tauri/src/outbox.rs
@@ -22,12 +22,13 @@
use crate::{cloudkit_context, Auth, Data};
use quince_core::calendar::Event;
-use quince_core::contacts::Contact;
+use quince_core::contacts::{Card, Contact, ContactDetails, PostalAddress};
use quince_core::outbox::Pending;
use quince_core::reminders::Reminder;
use quince_core::Library;
use quince_icloud::calendar::{EventRepeat, Scope};
use quince_icloud::ckdocument::Run;
+use quince_icloud::contacts::address::{self as postal, AddressEdit};
use quince_icloud::reminders::ReminderEdit;
use quince_icloud::Error;
use serde::{Deserialize, Serialize};
@@ -36,9 +37,13 @@ use tauri::{AppHandle, Emitter, Manager, State};
use tokio::sync::{Mutex, Notify};
static WAKE: Notify = Notify::const_new();
+/// Set by every [`kick`] until the sender's next pass: a pass after one is never taken as idle,
+/// so a change queued and sent between two looks is still announced as it lands.
+static KICKED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Something was queued: send it now.
pub fn kick() {
+ KICKED.store(true, std::sync::atomic::Ordering::SeqCst);
WAKE.notify_one();
}
@@ -219,6 +224,23 @@ pub struct ContactSave {
pub contact: Contact,
pub base: Option<Contact>,
pub create: bool,
+ /// The rest of the name and work, from a form that shows them; `None` (a change queued
+ /// before there was one) leaves Apple's.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub details: Option<ContactDetails>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub base_details: Option<ContactDetails>,
+}
+
+/// A card's addresses edited here: the edits, and the list the form opened them from. Sent,
+/// they are laid over Apple's addresses as they stand then (`contacts::address::edit`), so a
+/// send that already landed lands again as no change. `name` is who the card is, for a notice.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+pub struct ContactAddress {
+ pub base: Vec<PostalAddress>,
+ pub edits: Vec<AddressEdit>,
+ #[serde(default)]
+ pub name: String,
}
/// A repeating reminder ticked here: Apple moves it on to its next date. `from_due` is the
@@ -333,6 +355,10 @@ fn last_word(
/// A note's text, saved here. Several saves before one is sent become one, sent from the
/// text the first was typed over; one already on its way is followed by the next, typed over
/// what it sends.
+///
+/// A save that changes nothing — the text it was typed over, set the same way however the
+/// runs are cut — is no save: it is never queued, and one that undoes the change still waiting
+/// takes that change back. Opening or looking at a note must never write it.
pub fn record_note_save(
library: &mut Library,
guid: &str,
@@ -343,6 +369,9 @@ pub fn record_note_save(
) -> quince_core::Result<()> {
library.atomically(|l| {
let stored = l.note_body(guid)?;
+ let stored_runs: Option<Vec<Run>> = l
+ .note_runs(guid)?
+ .and_then(|r| serde_json::from_str(&r).ok());
let waiting: Option<(Pending, NoteSave)> = l
.outbox_waiting(NOTES, guid, "save")?
.into_iter()
@@ -356,12 +385,30 @@ pub fn record_note_save(
};
match waiting {
Some((p, before)) if p.tries == 0 => {
- let merged = save(before.base, before.base_runs);
- if !l.outbox_amend(p.id, &json(&merged)?)? {
- l.outbox_append(NOTES, guid, "save", &json(&merged)?)?;
+ if changes_nothing(
+ body,
+ runs.as_deref(),
+ before.base.as_deref(),
+ before.base_runs.as_deref(),
+ ) && l.outbox_withdraw(p.id)?
+ {
+ // Back to what Apple holds: the change waiting is taken back, not sent.
+ } else {
+ let merged = save(before.base, before.base_runs);
+ if !l.outbox_amend(p.id, &json(&merged)?)? {
+ l.outbox_append(NOTES, guid, "save", &json(&merged)?)?;
+ }
}
}
Some((_, before)) => {
+ if changes_nothing(
+ body,
+ runs.as_deref(),
+ Some(&before.body),
+ before.runs.as_deref(),
+ ) {
+ return Ok(());
+ }
l.outbox_append(
NOTES,
guid,
@@ -373,13 +420,44 @@ pub fn record_note_save(
// Nothing waiting: the library holds what Apple holds, the base when the
// editor did not say.
let base = base.or(stored);
+ let base_runs = base_runs.or(stored_runs);
+ if changes_nothing(body, runs.as_deref(), base.as_deref(), base_runs.as_deref()) {
+ return Ok(());
+ }
l.outbox_append(NOTES, guid, "save", &json(&save(base, base_runs))?)?;
}
}
- lay_note(l, guid, body, runs.as_deref())
+ lay_note(l, guid, body, runs.as_deref())?;
+ l.touch_note(guid, chrono_now())
})
}
+/// Now, in unix seconds.
+fn chrono_now() -> i64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map_or(0, |d| d.as_secs() as i64)
+}
+
+/// Whether a note save of `body` set by `runs`, typed over `base` set by `base_runs`, changes
+/// nothing: the same text, and — when it carries formatting — the same formatting once both
+/// are in one shape ([`quince_icloud::notes::same_formatting`]: Apple's runs come in pieces,
+/// an editor's merged, and that difference alone is not an edit).
+fn changes_nothing(
+ body: &str,
+ runs: Option<&[Run]>,
+ base: Option<&str>,
+ base_runs: Option<&[Run]>,
+) -> bool {
+ base == Some(body)
+ && match runs {
+ None => true,
+ Some(runs) => {
+ base_runs.is_some_and(|b| quince_icloud::notes::same_formatting(body, runs, b))
+ }
+ }
+}
+
fn lay_note(
l: &mut Library,
guid: &str,
@@ -495,11 +573,37 @@ fn lay_delete(l: &mut Library, d: &Delete) -> quince_core::Result<()> {
l.forget_reminders(&gone, &[])
}
-/// A card saved here — made (no id yet: one is given now) or edited. Answers its id.
+/// A card saved here — made (no id yet: one is given now) or edited. Answers its id. The
+/// shape a save had before the form showed the rest of the name and work: kept for the tests
+/// that queue one, as a window from before would have.
+#[cfg(test)]
pub fn record_contact_save(
library: &mut Library,
contact: &Contact,
base: Option<Contact>,
+) -> quince_core::Result<String> {
+ record_save(library, contact, None, base.map(|b| (b, None)))
+}
+
+/// [`record_contact_save`] for a whole card: the rest of its name and work go too.
+pub fn record_card_save(
+ library: &mut Library,
+ card: &Card,
+ base: Option<Card>,
+) -> quince_core::Result<String> {
+ record_save(
+ library,
+ &card.contact,
+ Some(&card.details),
+ base.map(|b| (b.contact, Some(b.details))),
+ )
+}
+
+fn record_save(
+ library: &mut Library,
+ contact: &Contact,
+ details: Option<&ContactDetails>,
+ base: Option<(Contact, Option<ContactDetails>)>,
) -> quince_core::Result<String> {
let create = contact.guid.is_empty();
let mut contact = contact.clone();
@@ -508,6 +612,7 @@ pub fn record_contact_save(
contact.etag = None;
}
let guid = contact.guid.clone();
+ let details = details.cloned();
library.atomically(|l| {
let waiting = last_word(l, CONTACTS, &guid, "save")?.and_then(|p| {
serde_json::from_str::<ContactSave>(&p.payload)
@@ -521,6 +626,8 @@ pub fn record_contact_save(
contact: contact.clone(),
base: before.base,
create: before.create,
+ details: details.clone().or(before.details),
+ base_details: before.base_details,
};
if !l.outbox_amend(p.id, &json(&save)?)? {
l.outbox_append(CONTACTS, &guid, "save", &json(&save)?)?;
@@ -532,23 +639,43 @@ pub fn record_contact_save(
contact: contact.clone(),
base: Some(before.contact),
create: false,
+ base_details: before.details.clone(),
+ details: details.clone().or(before.details),
};
l.outbox_append(CONTACTS, &guid, "save", &json(&save)?)?;
}
None => {
+ let (base, base_details) = match (&base, create) {
+ (Some((b, d)), false) => (Some(b.clone()), d.clone()),
+ _ => (None, None),
+ };
let save = ContactSave {
contact: contact.clone(),
- base: if create { None } else { base.clone() },
+ base,
create,
+ details: details.clone(),
+ base_details,
};
l.outbox_append(CONTACTS, &guid, "save", &json(&save)?)?;
}
}
- l.put_contact(&contact)?;
+ lay_contact_save(l, &contact, details.as_ref())?;
Ok(guid.clone())
})
}
+fn lay_contact_save(
+ l: &mut Library,
+ contact: &Contact,
+ details: Option<&ContactDetails>,
+) -> quince_core::Result<()> {
+ l.put_contact(contact)?;
+ if let Some(d) = details {
+ l.put_contact_details(&[(contact.guid.clone(), d.clone())], false)?;
+ }
+ Ok(())
+}
+
/// A repeating reminder ticked: moved on to its next date here at once, and queued for Apple,
/// which keeps the history and moves its own copy on. Each tick is its own change — two ticks
/// are two days — and each moves it on from the date it had when it was made, once.
@@ -575,7 +702,14 @@ fn lay_advance(l: &mut Library, guid: &str, a: &Advance) -> quince_core::Result<
if r.due_at != a.from_due {
return Ok(());
}
- if let Some(next) = r.next_occurrence_after(a.at) {
+ // Past its End Repeat date there is no next one: the series is done, as on the phone.
+ // Weekdays, Weekends or chosen days: on to the next of those, not a week on.
+ let days = l.reminder_repeat_days(guid)?;
+ if r.tick_ends_series_on(l.reminder_repeat_end(guid)?, &days, a.at) {
+ r.completed_at = Some(a.at);
+ return l.put_reminder_local(&r);
+ }
+ if let Some(next) = r.next_occurrence_on(&days, a.at) {
r.due_at = Some(next);
}
r.completed_at = None;
@@ -707,6 +841,44 @@ pub fn record_contact_delete(library: &mut Library, contact: &Contact) -> quince
})
}
+/// A card's addresses edited: shown at once, sent behind — after the card itself, when it was
+/// made here and waits too, since the queue keeps the order changes were made in. Answers
+/// the list as it now shows.
+pub fn record_contact_address(
+ library: &mut Library,
+ guid: &str,
+ base: Vec<PostalAddress>,
+ edits: Vec<AddressEdit>,
+) -> quince_core::Result<Vec<PostalAddress>> {
+ library.atomically(|l| {
+ let current = l.contact_addresses(guid)?;
+ let after = postal::laid_over(&current, &base, &edits)
+ .map_err(|e| quince_core::Error::Io(std::io::Error::other(e.to_string())))?;
+ let name = l
+ .contacts(None)?
+ .into_iter()
+ .find(|c| c.guid == guid)
+ .map(|c| c.display_name())
+ .unwrap_or_default();
+ let change = ContactAddress { base, edits, name };
+ l.outbox_append(CONTACTS, guid, "address", &json(&change)?)?;
+ l.set_contact_addresses(guid, &after)?;
+ Ok(after)
+ })
+}
+
+fn lay_contact_address(l: &mut Library, guid: &str, a: &ContactAddress) -> quince_core::Result<()> {
+ // A card deleted here, or gone at Apple, has nowhere to show them.
+ if !l.contacts(None)?.iter().any(|c| c.guid == guid) {
+ return Ok(());
+ }
+ let current = l.contact_addresses(guid)?;
+ if let Ok(after) = postal::laid_over(&current, &a.base, &a.edits) {
+ l.set_contact_addresses(guid, &after)?;
+ }
+ Ok(())
+}
+
/// An event made or saved here: shown at once, sent behind. Saves not yet sent and still the
/// last word on the event, for the same events of a series, are one save; one already on its
/// way is followed by the next, made from what it sends.
@@ -857,10 +1029,20 @@ fn lay(l: &mut Library, p: &Pending) -> quince_core::Result<()> {
}
(CONTACTS, "save") => {
if let Ok(s) = serde_json::from_str::<ContactSave>(&p.payload) {
- l.put_contact(&s.contact)?;
+ lay_contact_save(l, &s.contact, s.details.as_ref())?;
+ }
+ }
+ (CONTACTS, "merge") => {
+ if let Ok(m) = serde_json::from_str::<crate::contacts_merge::ContactMerge>(&p.payload) {
+ crate::contacts_merge::lay(l, &m)?;
}
}
(CONTACTS, "delete") => l.forget_contact(&p.record)?,
+ (CONTACTS, "address") => {
+ if let Ok(a) = serde_json::from_str::<ContactAddress>(&p.payload) {
+ lay_contact_address(l, &p.record, &a)?;
+ }
+ }
(CALENDAR, "save") => {
if let Ok(s) = serde_json::from_str::<EventSave>(&p.payload) {
lay_event_save(l, &s)?;
@@ -913,14 +1095,23 @@ pub fn start(app: AppHandle) {
() = WAKE.notified() => {}
() = tokio::time::sleep(wait) => {}
}
- let _ = app.emit(CHANGED, ());
+ // Nothing waiting is nothing to say. Told every thirty seconds regardless, each open
+ // Notes, Reminders and Contacts read its whole list (and the open note or card)
+ // again, twice, and drew it again — all day, with nothing changed.
+ let kicked = KICKED.swap(false, std::sync::atomic::Ordering::SeqCst);
+ let idle = !kicked && nothing_waiting(&app).await;
+ if !idle {
+ let _ = app.emit(CHANGED, ());
+ }
let outcomes = [
drain_reminders(&app).await,
drain_notes(&app).await,
drain_contacts(&app).await,
drain_calendar(&app).await,
];
- let _ = app.emit(CHANGED, ());
+ if !idle {
+ let _ = app.emit(CHANGED, ());
+ }
wait = if outcomes.iter().any(|o| matches!(o, Outcome::Later)) {
// Apple out of reach: wait longer each time, up to two minutes.
(wait * 2).clamp(Duration::from_secs(4), Duration::from_secs(120))
@@ -1038,6 +1229,14 @@ fn tell_refused(app: &AppHandle, service: &'static str, report: &Report) {
}
/// Whether anything waits for `service` — the answer when Apple can't be asked yet.
+/// No change waiting for any service (refused ones are not sent, so they do not count): a pass
+/// would send nothing and change nothing anyone is shown.
+async fn nothing_waiting(app: &AppHandle) -> bool {
+ let data = app.state::<Data>();
+ let library = data.0.lock().await;
+ library.outbox_all_pending().is_ok_and(|p| p.is_empty())
+}
+
async fn waiting(data: &Data, service: &str) -> Outcome {
if data
.0
@@ -1373,8 +1572,16 @@ async fn drain_contacts(app: &AppHandle) -> Outcome {
let Ok((http, root, params)) = session else {
return Outcome::Later;
};
+ // A merge waits a moment before it goes, so it can still be undone.
+ if let Some(wait) = crate::contacts_merge::held(&data).await {
+ tauri::async_runtime::spawn(async move {
+ tokio::time::sleep(wait).await;
+ kick();
+ });
+ return Outcome::Clear;
+ }
let report = drain(&data.0, CONTACTS, &crate::CONTACTS_PASS, |p| {
- send_contact(&http, &root, params.clone(), p)
+ send_contact(&data.0, &http, &root, params.clone(), p)
})
.await;
tell_refused(app, CONTACTS, &report);
@@ -1386,12 +1593,22 @@ async fn drain_contacts(app: &AppHandle) -> Outcome {
}
async fn send_contact(
+ library: &Mutex<Library>,
http: &reqwest::Client,
root: &str,
params: Vec<(String, String)>,
p: Pending,
) -> Result<(), Error> {
use quince_icloud::contacts as c;
+ if p.kind == "merge" {
+ return crate::contacts_merge::send(library, http, root, params, &p).await;
+ }
+ if p.kind == "address" {
+ let a: ContactAddress = serde_json::from_str(&p.payload).map_err(|e| unreadable(&e))?;
+ return c::address::edit(http, root, params, &p.record, &a.base, &a.edits)
+ .await
+ .map(|_| ());
+ }
if p.kind == "delete" {
let (people, tokens) = c::fetch_with_tokens(http, root, params.clone()).await?;
// Gone already — deleted elsewhere, or by an earlier send of this one.
@@ -1402,6 +1619,42 @@ async fn send_contact(
}
let s: ContactSave = serde_json::from_str(&p.payload).map_err(|e| unreadable(&e))?;
let (_, tokens) = c::fetch_with_tokens(http, root, params.clone()).await?;
+ if let Some(details) = &s.details {
+ let whole = |contact: &Contact, details: &ContactDetails| Card {
+ contact: contact.clone(),
+ details: details.clone(),
+ };
+ let mine = whole(&s.contact, details);
+ if s.create {
+ return c::create_card_named(http, root, params, &tokens, &p.record, &mine).await;
+ }
+ let card = c::card(http, root, params.clone(), &p.record).await?;
+ // A base from before the form showed these has none: compared with Apple's own, so
+ // only what this form changed is written.
+ let base_details = match &s.base_details {
+ Some(d) => Some(d.clone()),
+ None => card.as_ref().map(|v| {
+ c::parse_cards(&serde_json::json!({ "contacts": [v] }))
+ .pop()
+ .map(|c| c.details)
+ .unwrap_or_default()
+ }),
+ };
+ let base = s
+ .base
+ .as_ref()
+ .map(|b| whole(b, &base_details.clone().unwrap_or_default()));
+ return c::update_card(
+ http,
+ root,
+ params,
+ &tokens,
+ &mine,
+ card.as_ref(),
+ base.as_ref(),
+ )
+ .await;
+ }
if s.create {
return c::create_named(http, root, params, &tokens, &p.record, &s.contact).await;
}
@@ -1597,6 +1850,7 @@ fn watch_network() {
if let Ok(state) = signal.body().deserialize::<u32>() {
if came_online(&mut was, nm_online(state)) {
kick();
+ crate::push::wake();
}
}
}
@@ -1622,6 +1876,7 @@ fn watch_network() {
if let Ok(state) = String::try_from(value) {
if came_online(&mut was, connman_online(&state)) {
kick();
+ crate::push::wake();
}
}
}
@@ -1634,6 +1889,8 @@ fn watch_network() {
#[tauri::command]
pub fn outbox_wake() {
kick();
+ // And look for what changed elsewhere while offline (push.rs).
+ crate::push::wake();
}
// --- What the window asks.
@@ -1678,6 +1935,7 @@ fn content_of(p: &Pending) -> String {
(REMINDERS, "edit") => s("/title").or_else(|| s("/notes")),
(REMINDERS, "delete") => s("/reminder/title"),
(CALENDAR, _) => s("/event/title"),
+ (CONTACTS, "address") => s("/name"),
(CONTACTS, _) => {
let name: Vec<String> = [
"/contact/firstName",
@@ -2034,6 +2292,122 @@ mod tests {
);
}
+ /// Opening a note is not an edit. His "Attachments" note (text made generic) queued a save
+ /// on being opened: the same text, Apple's runs in pieces against the editor's merged.
+ /// That save — and one typed then undone — is never queued; a real edit is.
+ #[test]
+ fn a_save_that_changes_nothing_is_never_queued() {
+ let plain = |length| Run {
+ length,
+ ..Run::default()
+ };
+ let at = |id: &str| Run {
+ attachment: Some(id.into()),
+ ..plain(1)
+ };
+ let text = "Attachments\n\u{FFFC}\n\u{FFFC}\nA few words to try it out \n\u{FFFC}";
+ let apple = vec![
+ plain(10),
+ plain(1),
+ plain(1),
+ at("A1"),
+ plain(1),
+ at("A2"),
+ plain(1),
+ plain(2),
+ plain(10),
+ plain(8),
+ plain(5),
+ plain(1),
+ plain(1),
+ at("A3"),
+ ];
+ let editor = vec![plain(12), at("A1"), plain(1), at("A2"), plain(28), at("A3")];
+ let mut lib = Library::in_memory().unwrap();
+ note(&mut lib, "N", text);
+ lib.set_note_runs("N", &serde_json::to_string(&apple).unwrap())
+ .unwrap();
+
+ // As the window sent it, with the base it read — and with none, from the library.
+ record_note_save(
+ &mut lib,
+ "N",
+ text,
+ Some(text.into()),
+ Some(editor.clone()),
+ Some(apple.clone()),
+ )
+ .unwrap();
+ record_note_save(&mut lib, "N", text, None, Some(editor.clone()), None).unwrap();
+ record_note_save(&mut lib, "N", text, None, None, None).unwrap();
+ assert!(
+ lib.outbox_pending(NOTES).unwrap().is_empty(),
+ "opening a note queued a save"
+ );
+ let kept: Vec<Run> = serde_json::from_str(&lib.note_runs("N").unwrap().unwrap()).unwrap();
+ assert_eq!(kept, apple, "the library's runs were rewritten");
+
+ // Typed, then undone before it went: the change is taken back, not sent.
+ let typed = text.replace("out ", "out! ");
+ let mut mine = editor.clone();
+ mine[4].length += 1;
+ record_note_save(
+ &mut lib,
+ "N",
+ &typed,
+ Some(text.into()),
+ Some(mine.clone()),
+ Some(apple.clone()),
+ )
+ .unwrap();
+ assert_eq!(
+ lib.outbox_pending(NOTES).unwrap().len(),
+ 1,
+ "a real edit is queued"
+ );
+ record_note_save(
+ &mut lib,
+ "N",
+ text,
+ Some(text.into()),
+ Some(editor.clone()),
+ Some(apple.clone()),
+ )
+ .unwrap();
+ assert!(
+ lib.outbox_pending(NOTES).unwrap().is_empty(),
+ "an undone edit was still sent"
+ );
+
+ // A restyle with the same text is an edit.
+ let mut bold = editor.clone();
+ bold.splice(
+ 4..5,
+ [
+ plain(1),
+ Run {
+ bold: true,
+ ..plain(1)
+ },
+ plain(26),
+ ],
+ );
+ record_note_save(
+ &mut lib,
+ "N",
+ text,
+ Some(text.into()),
+ Some(bold),
+ Some(apple),
+ )
+ .unwrap();
+ assert_eq!(
+ lib.outbox_pending(NOTES).unwrap().len(),
+ 1,
+ "a restyle is queued"
+ );
+ }
+
/// Note saves: shown at once; several unsent are one, from the first base; one on its way
/// is followed by the next typed over what it sends; a pass is laid over.
#[test]
@@ -2121,6 +2495,91 @@ mod tests {
assert!(names.contains(&("X".into(), Some("New".into()))));
}
+ fn address(city: &str) -> PostalAddress {
+ PostalAddress {
+ label: Some("HOME".into()),
+ street: Some("1 Example Road".into()),
+ city: Some(city.into()),
+ country: Some("India".into()),
+ ..PostalAddress::default()
+ }
+ }
+
+ /// Contacts: an address added to a card made here, before Apple has the card, shows at
+ /// once and waits behind the card's own create, in order; a pass that has neither yet
+ /// keeps both on screen. Nothing is sent to Apple until the card is.
+ #[test]
+ fn an_address_on_a_new_card_waits_behind_its_create() {
+ let mut lib = Library::in_memory().unwrap();
+ let guid = record_contact_save(&mut lib, &person("", "Asha"), None).unwrap();
+ let add = vec![AddressEdit::Add {
+ address: address("Pune"),
+ }];
+ let shown = record_contact_address(&mut lib, &guid, vec![], add.clone()).unwrap();
+ assert_eq!(shown.len(), 1);
+ assert_eq!(lib.contact_addresses(&guid).unwrap(), shown);
+
+ let p = lib.outbox_pending(CONTACTS).unwrap();
+ let kinds: Vec<&str> = p.iter().map(|p| p.kind.as_str()).collect();
+ assert_eq!(kinds, ["save", "address"], "the card goes first");
+ let a: ContactAddress = serde_json::from_str(&p[1].payload).unwrap();
+ assert_eq!((a.base.len(), a.edits.clone()), (0, add));
+ assert_eq!(a.name, "Asha");
+
+ // A pass from before either: the book without the card. Both are laid back.
+ lib.put_contacts(&[]).unwrap();
+ replay(&mut lib, CONTACTS).unwrap();
+ assert_eq!(lib.contact_addresses(&guid).unwrap(), shown);
+
+ // The notice for a refusal names the person.
+ assert_eq!(content_of(&p[1]), "Asha");
+ }
+
+ /// An address edit on a card Apple has is laid over each pass: a part the phone changed
+ /// meanwhile stays, the part edited here wins, and laying it again changes nothing.
+ #[test]
+ fn an_address_edit_lays_over_each_pass_once() {
+ let mut lib = Library::in_memory().unwrap();
+ lib.put_contacts(&[person("X", "Ravi")]).unwrap();
+ lib.set_contact_addresses("X", &[address("Pune")]).unwrap();
+ let edit = vec![AddressEdit::SetField {
+ index: 0,
+ field: "city".into(),
+ value: Some("Mumbai".into()),
+ }];
+ record_contact_address(&mut lib, "X", vec![address("Pune")], edit).unwrap();
+ // The phone added a postcode meanwhile; a pass brings Apple's older city with it.
+ let mut phone = address("Pune");
+ phone.postal_code = Some("411001".into());
+ lib.set_contact_addresses("X", &[phone]).unwrap();
+ replay(&mut lib, CONTACTS).unwrap();
+ replay(&mut lib, CONTACTS).unwrap();
+ let now = lib.contact_addresses("X").unwrap();
+ assert_eq!(now.len(), 1);
+ assert_eq!(now[0].city.as_deref(), Some("Mumbai"));
+ assert_eq!(now[0].postal_code.as_deref(), Some("411001"));
+ }
+
+ /// An address edit for a card deleted here before it went: nothing to show it on, and
+ /// the replay leaves no orphaned address behind.
+ #[test]
+ fn an_address_for_a_deleted_card_is_not_laid() {
+ let mut lib = Library::in_memory().unwrap();
+ lib.put_contacts(&[person("X", "Ravi")]).unwrap();
+ record_contact_address(
+ &mut lib,
+ "X",
+ vec![],
+ vec![AddressEdit::Add {
+ address: address("Pune"),
+ }],
+ )
+ .unwrap();
+ record_contact_delete(&mut lib, &person("X", "Ravi")).unwrap();
+ replay(&mut lib, CONTACTS).unwrap();
+ assert!(lib.contact_addresses("X").unwrap().is_empty());
+ }
+
/// Sent twice — the app died after Apple took it, before the queue heard — a change does
/// what it did once: the create finds its own name and makes nothing more.
#[test]
@@ -2248,6 +2707,83 @@ mod tests {
.await
}
+ /// The last tick before End Repeat: completed here at once, never moved past its end; and
+ /// one with time left still moves on.
+ #[test]
+ fn the_last_tick_before_end_repeat_completes_it() {
+ let mut lib = library();
+ let due = 4_102_444_800; // 2100-01-01 00:00 UTC
+ let mut daily = lib.reminder("a").unwrap().unwrap();
+ daily.due_at = Some(due);
+ daily.recur_frequency = Some(0);
+ daily.recur_interval = Some(1);
+ daily.timezone = Some("UTC".into());
+ daily.raw = Some(
+ r#"{"fields":{"RecurrenceRuleIDs":{"type":"STRING_LIST","value":["R1"]}}}"#.into(),
+ );
+ lib.put_reminders(std::slice::from_ref(&daily)).unwrap();
+ let rule = |end: i64| quince_core::reminders::ReminderPart {
+ name: "RecurrenceRule/R1".into(),
+ reminder_guid: Some("a".into()),
+ kind: "RecurrenceRule".into(),
+ raw: format!(r#"{{"fields":{{"EndDate":{{"type":"TIMESTAMP","value":{end}}}}}}}"#),
+ };
+ // Ends that evening: tomorrow is past it.
+ lib.put_reminder_parts(&[rule((due + 12 * 3600) * 1000)], &[], true)
+ .unwrap();
+ record_reminder_advance(&mut lib, &daily, 1_000).unwrap();
+ let after = lib.reminder("a").unwrap().unwrap();
+ assert_eq!(after.due_at, Some(due), "not moved past its end");
+ assert_eq!(
+ after.completed_at,
+ Some(1_000),
+ "completed, as on the phone"
+ );
+
+ // Ends two days on: moved on, open.
+ let mut lib = library();
+ lib.put_reminders(std::slice::from_ref(&daily)).unwrap();
+ lib.put_reminder_parts(&[rule((due + 2 * 86_400) * 1000)], &[], true)
+ .unwrap();
+ record_reminder_advance(&mut lib, &daily, 1_000).unwrap();
+ let after = lib.reminder("a").unwrap().unwrap();
+ assert_eq!(
+ (after.due_at, after.completed_at),
+ (Some(due + 86_400), None)
+ );
+ }
+
+ /// Weekdays, as the phone wrote "Repeating 1": ticked on a Friday, it moves on to Monday.
+ #[test]
+ fn a_weekdays_tick_on_friday_moves_on_to_monday() {
+ let mut lib = library();
+ let friday = 1_792_771_200; // Fri 23 Oct 2026, 00:00 UTC
+ let mut r = lib.reminder("a").unwrap().unwrap();
+ r.due_at = Some(friday);
+ r.recur_frequency = Some(1);
+ r.recur_interval = Some(1);
+ r.timezone = Some("UTC".into());
+ r.raw = Some(r#"{"fields":{"RecurrenceRuleIDs":{"type":"STRING_LIST","value":["EC08DD7D-132C-412C-AFDD-064AAECBA6A9"]}}}"#.into());
+ lib.put_reminders(std::slice::from_ref(&r)).unwrap();
+ lib.put_reminder_parts(
+ &[quince_core::reminders::ReminderPart {
+ name: "RecurrenceRule/EC08DD7D-132C-412C-AFDD-064AAECBA6A9".into(),
+ reminder_guid: Some("a".into()),
+ kind: "RecurrenceRule".into(),
+ raw: r#"{"fields":{"DaysOfTheWeek":{"type":"BYTES","value":"W3siZGF5T2ZUaGVXZWVrIjoyLCJ3ZWVrTnVtYmVyIjowfSx7ImRheU9mVGhlV2VlayI6Mywid2Vla051bWJlciI6MH0seyJkYXlPZlRoZVdlZWsiOjQsIndlZWtOdW1iZXIiOjB9LHsiZGF5T2ZUaGVXZWVrIjo1LCJ3ZWVrTnVtYmVyIjowfSx7ImRheU9mVGhlV2VlayI6Niwid2Vla051bWJlciI6MH1d"},"Frequency":{"type":"NUMBER_INT64","value":1}}}"#.into(),
+ }],
+ &[],
+ true,
+ )
+ .unwrap();
+ record_reminder_advance(&mut lib, &r, friday - 60).unwrap();
+ assert_eq!(
+ lib.reminder("a").unwrap().unwrap().due_at,
+ Some(friday + 3 * 86_400),
+ "Monday, not next Friday"
+ );
+ }
+
/// A repeating reminder ticked moves on to its next date at once, open; a pass from before
/// the tick is laid over once, never twice; two ticks are two days, sent in order.
#[test]
diff --git a/src-tauri/src/photo_cache.rs b/src-tauri/src/photo_cache.rs
new file mode 100644
index 0000000..abefbc2
--- /dev/null
+++ b/src-tauri/src/photo_cache.rs
@@ -0,0 +1,891 @@
+//! The photo cache held to the size chosen in Settings (2 GB unless changed), as Photos on a Mac
+//! with "Optimize Storage" keeps what was looked at last and lets the rest go.
+//!
+//! What it holds, by folder under `photos/`:
+//!
+//! - `thumb/`, and `fit/<step>/` up to [`THUMB_STEP`]: the grid's pictures. Small, drawn by every
+//! view, and never let go of — the library always scrolls from disk.
+//! - `original/`, `full/`, `medium/`, `video/`, `live/`, the larger `fit/` steps, and `open/`
+//! (a video's name for the system's player, a hard link to its original): originals and
+//! previews. These are what the cap holds, the longest unseen let go first.
+//!
+//! The disk is the only record of what is cached: a picture is cached exactly when its file is
+//! in place (`cached`, the Photos folder and the export all ask the disk), and no table anywhere
+//! says otherwise. Every file arrives whole — written to a `.part` beside it and renamed — and
+//! leaves in one unlink, so a crash at any moment leaves each picture either whole and cached or
+//! gone and fetched again when next wanted. Never half of one. A crash mid-download leaves only
+//! a `.part`, which is never taken for the picture and is swept once it is clearly abandoned.
+//!
+//! Never let go of: anything handed to a reader in the last few minutes (see [`hold_if_cached`]
+//! — the photo on screen, a film playing, a file the Photos folder is reading), anything waiting
+//! to be uploaded (its source may sit here), and any download still landing. Photos has no "Keep
+//! on This Computer" of its own — that is the iCloud Drive folder's, which keeps its files in its
+//! own cache (`drive-cache`), never walked here.
+//!
+//! Eviction runs on a blocking thread, one pass at a time, never on the window's.
+
+use std::collections::HashMap;
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::Mutex;
+use std::time::{Duration, Instant, SystemTime};
+
+pub const MB: u64 = 1 << 20;
+pub const GB: u64 = 1 << 30;
+/// The sizes Settings offers.
+pub const STEPS: [u64; 7] = [512 * MB, GB, 2 * GB, 5 * GB, 10 * GB, 20 * GB, 50 * GB];
+/// The cap until one is chosen.
+pub const DEFAULT_CAP: u64 = 2 * GB;
+/// Where the chosen cap is kept in the library's state.
+const CAP_KEY: &str = "photos.cacheCap";
+/// The largest `fit/` step that is a grid picture (made from the 512-pixel thumbnail): kept with
+/// the thumbnails. Larger steps are the viewer's, and previews.
+pub const THUMB_STEP: u32 = 512;
+/// Seen (or handed to a reader) this recently: on screen, or being read — never let go of by a
+/// trim. A trim that could not reach the cap for them is tried again once this has passed.
+pub const RECENT: Duration = Duration::from_secs(5 * 60);
+/// A download's `.part` untouched for this long belongs to a download that died with the app.
+/// One still landing is written to every moment.
+pub const STALE_PART: Duration = Duration::from_secs(60 * 60);
+/// The folders of originals and previews.
+const PREVIEWS: [&str; 6] = ["original", "full", "medium", "video", "live", "open"];
+
+// ---------------------------------------------------------------------------------------------
+// Readers' holds.
+
+/// Files handed to a reader, and when. Eviction checks this under the same lock as it unlinks,
+/// and a reader is handed a file only under it after seeing the file in place: a file is either
+/// let go of before it is handed out (and the reader fetches it again) or after its hold ends.
+static HELD: Mutex<Option<HashMap<PathBuf, Instant>>> = Mutex::new(None);
+
+fn held() -> std::sync::MutexGuard<'static, Option<HashMap<PathBuf, Instant>>> {
+ HELD.lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+}
+
+/// Whether `path` is in the cache; when it is, it is held for [`RECENT`] so no trim lets it go
+/// while it is being read.
+pub fn hold_if_cached(path: &Path) -> bool {
+ let mut map = held();
+ let there = std::fs::metadata(path).is_ok_and(|m| m.is_file());
+ if there {
+ note(&mut map, path);
+ }
+ there
+}
+
+/// A file just put in place for a reader, held as [`hold_if_cached`] holds one.
+pub fn hold(path: &Path) {
+ note(&mut held(), path);
+}
+
+fn note(map: &mut Option<HashMap<PathBuf, Instant>>, path: &Path) {
+ let map = map.get_or_insert_with(HashMap::new);
+ if map.len() > 4096 {
+ map.retain(|_, at| at.elapsed() < RECENT);
+ }
+ map.insert(path.to_path_buf(), Instant::now());
+}
+
+fn is_held(map: &Option<HashMap<PathBuf, Instant>>, path: &Path) -> bool {
+ map.as_ref()
+ .and_then(|m| m.get(path))
+ .is_some_and(|at| at.elapsed() < RECENT)
+}
+
+// ---------------------------------------------------------------------------------------------
+// What is on disk.
+
+/// Room a file takes on disk: its blocks, so a sparse or tail-packed file counts what it uses.
+fn on_disk(meta: &std::fs::Metadata) -> u64 {
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::MetadataExt;
+ meta.blocks().saturating_mul(512)
+ }
+ #[cfg(not(unix))]
+ {
+ meta.len()
+ }
+}
+
+/// A file's identity: one file under two names (a video's `open/` link and its original) is
+/// one picture, counted once and let go of whole.
+fn identity(meta: &std::fs::Metadata, path: &Path) -> (u64, u64, Option<PathBuf>) {
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::MetadataExt;
+ let _ = path;
+ (meta.dev(), meta.ino(), None)
+ }
+ #[cfg(not(unix))]
+ {
+ let _ = meta;
+ (0, 0, Some(path.to_path_buf()))
+ }
+}
+
+/// One picture that can be let go of: every name it has here, the room it takes, and when it
+/// was last seen (its modified time, set again each time it is read: `photos::cached`).
+#[derive(Debug, Clone)]
+struct Picture {
+ paths: Vec<PathBuf>,
+ bytes: u64,
+ seen: SystemTime,
+ id: (u64, u64, Option<PathBuf>),
+}
+
+/// The originals and previews on disk, and the `.part` files beside them.
+#[derive(Debug, Default)]
+struct Scan {
+ pictures: Vec<Picture>,
+ parts: Vec<(PathBuf, SystemTime)>,
+ used: u64,
+}
+
+/// Whether a `fit/` folder holds the grid's pictures (kept) or the viewer's (previews).
+fn fit_is_preview(name: &std::ffi::OsStr) -> bool {
+ name.to_str()
+ .and_then(|s| s.parse::<u32>().ok())
+ .is_some_and(|step| step > THUMB_STEP)
+}
+
+/// Every folder of originals and previews under `root`.
+fn preview_dirs(root: &Path) -> Vec<PathBuf> {
+ let mut dirs: Vec<PathBuf> = PREVIEWS.iter().map(|d| root.join(d)).collect();
+ for e in std::fs::read_dir(root.join("fit"))
+ .into_iter()
+ .flatten()
+ .flatten()
+ {
+ if fit_is_preview(&e.file_name()) {
+ dirs.push(e.path());
+ }
+ }
+ dirs
+}
+
+/// Files under `dir`, two levels at most (`open/<id>/<name>`), never following a link out.
+fn walk(dir: &Path, depth: u8, out: &mut Vec<(PathBuf, std::fs::Metadata)>) {
+ for e in std::fs::read_dir(dir).into_iter().flatten().flatten() {
+ let Ok(meta) = std::fs::symlink_metadata(e.path()) else {
+ continue;
+ };
+ if meta.is_file() {
+ out.push((e.path(), meta));
+ } else if meta.is_dir() && depth > 0 {
+ walk(&e.path(), depth - 1, out);
+ }
+ }
+}
+
+fn is_part(path: &Path) -> bool {
+ path.extension().is_some_and(|e| e == "part")
+}
+
+fn scan(root: &Path) -> Scan {
+ let mut files = Vec::new();
+ for dir in preview_dirs(root) {
+ walk(&dir, 1, &mut files);
+ }
+ let mut scan = Scan::default();
+ let mut by_id: HashMap<(u64, u64, Option<PathBuf>), usize> = HashMap::new();
+ for (path, meta) in files {
+ let seen = meta.modified().unwrap_or(std::time::UNIX_EPOCH);
+ if is_part(&path) {
+ scan.parts.push((path, seen));
+ continue;
+ }
+ let id = identity(&meta, &path);
+ match by_id.get(&id) {
+ Some(&i) => scan.pictures[i].paths.push(path),
+ None => {
+ let bytes = on_disk(&meta);
+ scan.used += bytes;
+ by_id.insert(id.clone(), scan.pictures.len());
+ scan.pictures.push(Picture {
+ paths: vec![path],
+ bytes,
+ seen,
+ id,
+ });
+ }
+ }
+ }
+ scan
+}
+
+/// Room the grid's pictures take (thumbnails, and `fit/` steps up to [`THUMB_STEP`]).
+fn thumbnails(root: &Path) -> u64 {
+ let mut files = Vec::new();
+ walk(&root.join("thumb"), 0, &mut files);
+ for e in std::fs::read_dir(root.join("fit"))
+ .into_iter()
+ .flatten()
+ .flatten()
+ {
+ if !fit_is_preview(&e.file_name()) {
+ walk(&e.path(), 0, &mut files);
+ }
+ }
+ files
+ .iter()
+ .filter(|(p, _)| !is_part(p))
+ .map(|(_, m)| on_disk(m))
+ .sum()
+}
+
+// ---------------------------------------------------------------------------------------------
+// Letting go.
+
+/// What a trim may not let go of, besides what readers hold.
+pub struct Guard<'a> {
+ /// Files never let go of, by identity: whatever is waiting to be uploaded.
+ pub protected: &'a [(u64, u64, Option<PathBuf>)],
+ /// Kept when seen within this long — on screen; `None` for an explicit Clear Cache.
+ pub recent: Option<Duration>,
+ pub now: SystemTime,
+}
+
+/// What a trim did.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct Outcome {
+ /// Originals and previews on disk before, and after, in bytes.
+ pub before: u64,
+ pub after: u64,
+ pub removed: usize,
+ /// It stopped short of the cap for pictures seen just now: worth trying again later.
+ pub held_back: bool,
+}
+
+/// The identity of each file at `paths` that exists — what is waiting to be uploaded.
+pub fn identities(paths: &[PathBuf]) -> Vec<(u64, u64, Option<PathBuf>)> {
+ paths
+ .iter()
+ .filter_map(|p| std::fs::metadata(p).ok().map(|m| identity(&m, p)))
+ .collect()
+}
+
+/// One file let go of unless a reader holds it or it is waiting to be uploaded — checked and
+/// removed under the readers' lock, as a trim does. Answers whether it is gone.
+pub fn remove_unless_in_use(path: &Path, protected: &[(u64, u64, Option<PathBuf>)]) -> bool {
+ let map = held();
+ if is_held(&map, path)
+ || std::fs::metadata(path).is_ok_and(|m| protected.contains(&identity(&m, path)))
+ {
+ return false;
+ }
+ std::fs::remove_file(path).is_ok()
+}
+
+/// One picture let go of, every name of it, unless a reader holds one. Its other names (the
+/// player's link) go first and the cached name last: stopped between the two, the picture is
+/// still whole and cached. Answers whether it is gone.
+fn let_go(p: &Picture) -> bool {
+ let map = held();
+ if p.paths.iter().any(|path| is_held(&map, path)) {
+ return false;
+ }
+ let mut order: Vec<&PathBuf> = p.paths.iter().collect();
+ order.sort_by_key(|path| !path.components().any(|c| c.as_os_str() == "open"));
+ for path in order {
+ match std::fs::remove_file(path) {
+ Ok(()) => {
+ // A video's own folder for the player, empty now, goes with it.
+ if let Some(dir) = path.parent().filter(|d| {
+ d.parent()
+ .and_then(Path::file_name)
+ .is_some_and(|n| n == "open")
+ }) {
+ let _ = std::fs::remove_dir(dir);
+ }
+ }
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
+ // Open elsewhere where that forbids it (Windows): it stays, whole.
+ Err(_) => return false,
+ }
+ }
+ true
+}
+
+/// `.part` files of downloads that died with the app, swept. One still landing is skipped.
+fn sweep_parts(parts: &[(PathBuf, SystemTime)], now: SystemTime) {
+ for (path, seen) in parts {
+ if now.duration_since(*seen).is_ok_and(|age| age >= STALE_PART) {
+ let _ = std::fs::remove_file(path);
+ }
+ }
+}
+
+/// The originals and previews under `root` held to `cap`: when over it, the longest unseen go
+/// first until they are back under nine tenths of it, so the next download does not trim again
+/// at once. `stop_after` ends the pass after that many pictures, as a crash would (tests).
+fn trim_with(root: &Path, cap: u64, guard: &Guard<'_>, stop_after: Option<usize>) -> Outcome {
+ let scan = scan(root);
+ sweep_parts(&scan.parts, guard.now);
+ let mut out = Outcome {
+ before: scan.used,
+ after: scan.used,
+ ..Outcome::default()
+ };
+ if scan.used <= cap {
+ return out;
+ }
+ let low = cap / 10 * 9;
+ let mut pictures = scan.pictures;
+ pictures.sort_by_key(|p| p.seen);
+ for p in &pictures {
+ if out.after <= low || stop_after.is_some_and(|n| out.removed >= n) {
+ break;
+ }
+ if guard.protected.contains(&p.id) {
+ continue;
+ }
+ if let Some(window) = guard.recent {
+ if guard
+ .now
+ .duration_since(p.seen)
+ .map_or(true, |age| age < window)
+ {
+ out.held_back = true;
+ continue;
+ }
+ }
+ if let_go(p) {
+ out.after = out.after.saturating_sub(p.bytes);
+ out.removed += 1;
+ } else {
+ out.held_back = true;
+ }
+ }
+ out
+}
+
+/// The cache under `root` held to `cap`. See [`trim_with`].
+pub fn trim(root: &Path, cap: u64, guard: &Guard<'_>) -> Outcome {
+ trim_with(root, cap, guard, None)
+}
+
+/// Every original and preview under `root` let go of, but what is held, protected or still
+/// landing. The grid's pictures stay.
+pub fn clear(root: &Path, guard: &Guard<'_>) -> Outcome {
+ trim_with(
+ root,
+ 0,
+ &Guard {
+ recent: None,
+ ..*guard
+ },
+ None,
+ )
+}
+
+/// The most the cache may take on a disk: the cap chosen, or a fifth of the room it could have
+/// (free space and its own) when that is less — a full disk is never the price of a cache.
+pub fn limit(cap: u64, free: u64, used: u64) -> u64 {
+ cap.min(free.saturating_add(used) / 5)
+}
+
+/// Free space on the disk holding `dir`, in bytes; `None` where it cannot be read.
+fn free_space(dir: &Path) -> Option<u64> {
+ #[cfg(unix)]
+ {
+ use std::os::unix::ffi::OsStrExt;
+ let path = std::ffi::CString::new(dir.as_os_str().as_bytes()).ok()?;
+ // SAFETY: statvfs fills the struct it is given and reads only the path.
+ let mut s: libc::statvfs = unsafe { std::mem::zeroed() };
+ if unsafe { libc::statvfs(path.as_ptr(), &mut s) } == 0 {
+ // 64-bit here already, narrower on some systems: the conversion is for those.
+ #[allow(clippy::useless_conversion)]
+ return Some(u64::from(s.f_bavail).saturating_mul(u64::from(s.f_frsize)));
+ }
+ None
+ }
+ #[cfg(not(unix))]
+ {
+ let _ = dir;
+ None
+ }
+}
+
+/// The nearest size Settings offers to `bytes`.
+pub fn snap(bytes: u64) -> u64 {
+ STEPS
+ .iter()
+ .copied()
+ .min_by_key(|s| s.abs_diff(bytes))
+ .unwrap_or(DEFAULT_CAP)
+}
+
+// ---------------------------------------------------------------------------------------------
+// In the app.
+
+use crate::Data;
+use tauri::{AppHandle, Emitter, Manager};
+
+/// The cap chosen, once read from the library (0: not read yet).
+static CAP: AtomicU64 = AtomicU64::new(0);
+/// One pass at a time: a trim and a Clear Cache never run over each other.
+static PASS: Mutex<()> = Mutex::new(());
+
+/// What Settings shows of the cache.
+#[derive(Debug, Clone, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Status {
+ /// Originals and previews on disk, in bytes.
+ pub used: u64,
+ /// The cap chosen.
+ pub cap: u64,
+ /// What it is held to now: the cap, or less while the disk is short of space.
+ pub limit: u64,
+ /// The grid's pictures, which always stay.
+ pub thumbnails: u64,
+ pub steps: Vec<u64>,
+}
+
+fn root(app: &AppHandle) -> PathBuf {
+ crate::state_dir(app).join("photos")
+}
+
+fn parse_cap(saved: Option<String>) -> u64 {
+ saved
+ .and_then(|s| s.parse::<u64>().ok())
+ .filter(|b| STEPS.contains(b))
+ .unwrap_or(DEFAULT_CAP)
+}
+
+/// The cap chosen. Off the async threads only: it may wait for the library.
+fn cap_blocking(app: &AppHandle) -> u64 {
+ match CAP.load(Ordering::SeqCst) {
+ 0 => {
+ let saved = app
+ .state::<Data>()
+ .0
+ .blocking_lock()
+ .state(CAP_KEY)
+ .ok()
+ .flatten();
+ let cap = parse_cap(saved);
+ CAP.store(cap, Ordering::SeqCst);
+ cap
+ }
+ cap => cap,
+ }
+}
+
+/// What is waiting to be uploaded, by identity. Off the async threads only.
+fn waiting_uploads(app: &AppHandle) -> Vec<(u64, u64, Option<PathBuf>)> {
+ let paths: Vec<PathBuf> = app
+ .state::<Data>()
+ .0
+ .blocking_lock()
+ .unfinished_uploads()
+ .unwrap_or_default()
+ .into_iter()
+ .map(|u| PathBuf::from(u.path))
+ .collect();
+ identities(&paths)
+}
+
+fn status_of(root: &Path, cap: u64, used: u64) -> Status {
+ let free = free_space(root).unwrap_or(u64::MAX / 2);
+ Status {
+ used,
+ cap,
+ limit: limit(cap, free, used),
+ thumbnails: thumbnails(root),
+ steps: STEPS.to_vec(),
+ }
+}
+
+/// The cache held to its limit now, on this (blocking) thread. Answers the outcome and the
+/// limit it was held to; tells the window what is there now.
+pub fn trim_now(app: &AppHandle) -> (Outcome, u64) {
+ let _pass = PASS
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let root = root(app);
+ if std::fs::create_dir_all(&root).is_err() {
+ return (Outcome::default(), 0);
+ }
+ let cap = cap_blocking(app);
+ let protected = waiting_uploads(app);
+ let used = scan(&root).used;
+ let held_to = limit(cap, free_space(&root).unwrap_or(u64::MAX / 2), used);
+ let out = trim(
+ &root,
+ held_to,
+ &Guard {
+ protected: &protected,
+ recent: Some(RECENT),
+ now: SystemTime::now(),
+ },
+ );
+ if out.removed > 0 {
+ let _ = app.emit(EVENT, status_of(&root, cap, out.after));
+ }
+ // Short of the limit only for what was on screen: tried again once that has had its time.
+ if out.held_back && out.after > held_to {
+ later(app, RECENT + Duration::from_secs(5));
+ }
+ (out, held_to)
+}
+
+/// The window's word that the cache changed: its [`Status`] now.
+pub const EVENT: &str = "quince://photo-cache";
+
+static RUNNING: AtomicBool = AtomicBool::new(false);
+static AGAIN: AtomicBool = AtomicBool::new(false);
+static LATER: AtomicBool = AtomicBool::new(false);
+
+/// A picture landed: the cap is checked soon, once, however many land together.
+pub fn grew(app: &AppHandle) {
+ request(app, Duration::from_secs(2));
+}
+
+/// A trim in the background after `after`; requests that come while one waits or runs are one.
+fn request(app: &AppHandle, after: Duration) {
+ if RUNNING.swap(true, Ordering::SeqCst) {
+ AGAIN.store(true, Ordering::SeqCst);
+ return;
+ }
+ let app = app.clone();
+ tauri::async_runtime::spawn(async move {
+ loop {
+ tokio::time::sleep(after).await;
+ AGAIN.store(false, Ordering::SeqCst);
+ let a = app.clone();
+ let _ = tauri::async_runtime::spawn_blocking(move || trim_now(&a)).await;
+ if !AGAIN.load(Ordering::SeqCst) {
+ break;
+ }
+ }
+ RUNNING.store(false, Ordering::SeqCst);
+ // One that came in the moment it stopped.
+ if AGAIN.swap(false, Ordering::SeqCst) {
+ request(&app, after);
+ }
+ });
+}
+
+/// One trim, `after` from now — however many ask meanwhile.
+fn later(app: &AppHandle, after: Duration) {
+ if LATER.swap(true, Ordering::SeqCst) {
+ return;
+ }
+ let app = app.clone();
+ tauri::async_runtime::spawn(async move {
+ tokio::time::sleep(after).await;
+ LATER.store(false, Ordering::SeqCst);
+ request(&app, Duration::ZERO);
+ });
+}
+
+/// What the cache holds now, and what it is held to.
+#[tauri::command]
+pub async fn photos_cache_status(app: AppHandle) -> Result<Status, String> {
+ tauri::async_runtime::spawn_blocking(move || {
+ let root = root(&app);
+ let cap = cap_blocking(&app);
+ status_of(&root, cap, scan(&root).used)
+ })
+ .await
+ .map_err(|e| e.to_string())
+}
+
+/// The cap set to one of the sizes offered (the nearest), kept, and held to in the background:
+/// a lower one lets the longest unseen go at once. Answers at once with what is there now; the
+/// trim's result follows as [`EVENT`].
+#[tauri::command]
+pub async fn photos_cache_set(bytes: u64, app: AppHandle) -> Result<Status, String> {
+ let cap = snap(bytes);
+ app.state::<Data>()
+ .0
+ .lock()
+ .await
+ .set_state(CAP_KEY, &cap.to_string())
+ .map_err(|e| e.to_string())?;
+ let lower = cap < CAP.swap(cap, Ordering::SeqCst);
+ let status = {
+ let app = app.clone();
+ tauri::async_runtime::spawn_blocking(move || {
+ let root = root(&app);
+ status_of(&root, cap, scan(&root).used)
+ })
+ .await
+ .map_err(|e| e.to_string())?
+ };
+ if lower || status.used > status.limit {
+ request(&app, Duration::ZERO);
+ }
+ Ok(status)
+}
+
+/// Every original and preview let go of (Apple keeps them all), off the window's thread; the
+/// grid's pictures stay. Answers what is there after.
+#[tauri::command]
+pub async fn photos_cache_clear(app: AppHandle) -> Result<Status, String> {
+ tauri::async_runtime::spawn_blocking(move || {
+ let _pass = PASS
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let root = root(&app);
+ let cap = cap_blocking(&app);
+ let protected = waiting_uploads(&app);
+ let out = clear(
+ &root,
+ &Guard {
+ protected: &protected,
+ recent: None,
+ now: SystemTime::now(),
+ },
+ );
+ let status = status_of(&root, cap, out.after);
+ let _ = app.emit(EVENT, status.clone());
+ status
+ })
+ .await
+ .map_err(|e| e.to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A cached picture at `rel` of `kb` kilobytes, last seen `ago` ago.
+ fn put(root: &Path, rel: &str, kb: usize, ago: Duration) -> PathBuf {
+ let p = root.join(rel);
+ std::fs::create_dir_all(p.parent().unwrap()).unwrap();
+ std::fs::write(&p, vec![7u8; kb * 1024]).unwrap();
+ let f = std::fs::File::options().write(true).open(&p).unwrap();
+ f.set_modified(SystemTime::now() - ago).unwrap();
+ p
+ }
+
+ fn mins(n: u64) -> Duration {
+ Duration::from_secs(n * 60)
+ }
+
+ fn guard(protected: &[(u64, u64, Option<PathBuf>)]) -> Guard<'_> {
+ Guard {
+ protected,
+ recent: Some(RECENT),
+ now: SystemTime::now(),
+ }
+ }
+
+ /// Every file under `root` is whole (all its bytes the ones written) or not there at all.
+ fn all_whole(root: &Path) {
+ let mut files = Vec::new();
+ for dir in [
+ "thumb", "original", "full", "medium", "video", "fit/128", "fit/1536", "open",
+ ] {
+ walk(&root.join(dir), 1, &mut files);
+ }
+ for (p, m) in files {
+ if is_part(&p) {
+ continue;
+ }
+ let bytes = std::fs::read(&p).unwrap();
+ assert!(
+ bytes.len() as u64 == m.len() && bytes.iter().all(|&b| b == 7),
+ "{p:?} is whole"
+ );
+ }
+ }
+
+ /// Over the cap, the longest unseen go first, down to nine tenths of it; the grid's
+ /// pictures always stay, and so does anything seen in the last few minutes.
+ #[test]
+ fn the_longest_unseen_go_first_and_thumbnails_stay() {
+ let t = tempfile::tempdir().unwrap();
+ let r = t.path();
+ let thumb = put(r, "thumb/A", 400, mins(900));
+ let grid = put(r, "fit/256/A", 400, mins(900));
+ let oldest = put(r, "original/A", 400, mins(600));
+ let old = put(r, "full/B", 400, mins(500));
+ let newer = put(r, "medium/C", 400, mins(100));
+ let viewer = put(r, "fit/1536/D", 400, mins(50));
+ let on_screen = put(r, "original/E", 400, mins(1));
+ let before = scan(r).used;
+ assert!(
+ before >= 5 * 400 * 1024,
+ "the five previews count, not the grid's: {before}"
+ );
+ // Room for three of the five under nine tenths of the cap: two go, the two seen
+ // longest ago.
+ let cap = 1_400_000;
+ let out = trim(r, cap, &guard(&[]));
+ assert_eq!(out.removed, 2, "{out:?}");
+ assert!(!oldest.exists() && !old.exists());
+ for kept in [&thumb, &grid, &newer, &viewer, &on_screen] {
+ assert!(kept.exists(), "{kept:?} stays");
+ }
+ assert!(out.after <= cap / 10 * 9 && out.after == scan(r).used);
+ // Under the cap: nothing more goes.
+ assert_eq!(trim(r, cap, &guard(&[])).removed, 0);
+ all_whole(r);
+ }
+
+ /// The cap lowered: the cache goes down to it at once, oldest first — but never the picture
+ /// on screen, which is tried again once it has had its time.
+ #[test]
+ fn a_lower_cap_is_held_to_at_once() {
+ let t = tempfile::tempdir().unwrap();
+ let r = t.path();
+ for i in 0..10 {
+ put(r, &format!("original/P{i}"), 100, mins(100 - i));
+ }
+ let shown = put(r, "full/SHOWN", 100, Duration::from_secs(10));
+ let out = trim(r, 5 * 104 * 1024, &guard(&[]));
+ assert!(out.after <= 5 * 104 * 1024, "{out:?}");
+ assert!(!r.join("original/P0").exists() && r.join("original/P9").exists());
+ assert!(shown.exists());
+ // Down to nothing: all but the one on screen go, and it says it held one back.
+ let out = trim(r, 0, &guard(&[]));
+ assert!(out.held_back && shown.exists());
+ assert_eq!(scan(r).pictures.len(), 1);
+ }
+
+ /// What waits to be uploaded, a picture a reader was just handed, and a download still
+ /// landing are never let go of — not by a trim, not by Clear Cache.
+ #[test]
+ fn pending_held_and_landing_files_stay() {
+ let t = tempfile::tempdir().unwrap();
+ let r = t.path();
+ let pending = put(r, "open/X/IMG_1.MOV", 300, mins(900));
+ let read_now = put(r, "original/R", 300, mins(900));
+ let landing = put(r, "original/L.1a2b.part", 300, Duration::from_secs(2));
+ let plain = put(r, "original/Q", 300, mins(900));
+ let protected = identities(std::slice::from_ref(&pending));
+ assert!(hold_if_cached(&read_now));
+ assert!(!hold_if_cached(&r.join("original/NOT-THERE")));
+ let out = clear(r, &guard(&protected));
+ assert!(pending.exists() && read_now.exists() && landing.exists());
+ assert!(!plain.exists());
+ assert!(out.held_back && out.removed == 1);
+ // The `.part` is never taken for a picture: not counted, never a cache hit.
+ assert_eq!(scan(r).pictures.len(), 2);
+ }
+
+ /// A pending upload that is a hard link to a cached original keeps the original too: the
+ /// two are one file, and letting one name go would free nothing.
+ #[cfg(unix)]
+ #[test]
+ fn a_link_and_its_original_are_one_picture() {
+ let t = tempfile::tempdir().unwrap();
+ let r = t.path();
+ let original = put(r, "original/V", 500, mins(900));
+ let link = r.join("open/V/clip.MOV");
+ std::fs::create_dir_all(link.parent().unwrap()).unwrap();
+ std::fs::hard_link(&original, &link).unwrap();
+ let s = scan(r);
+ assert_eq!(s.pictures.len(), 1, "one file under two names");
+ assert!(s.used < 600 * 1024, "counted once: {}", s.used);
+ // Protected by either name.
+ let protected = identities(std::slice::from_ref(&link));
+ assert_eq!(clear(r, &guard(&protected)).removed, 0);
+ assert!(original.exists() && link.exists());
+ // Unprotected, both names go, the player's folder with them.
+ assert_eq!(clear(r, &guard(&[])).removed, 1);
+ assert!(!original.exists() && !link.exists() && !r.join("open/V").exists());
+ }
+
+ /// A crash at any point of a trim leaves every picture whole or gone — never half — and the
+ /// next start finishes the job; what the disk holds is all there is to agree with.
+ #[test]
+ fn a_crash_mid_trim_leaves_everything_whole_and_the_next_start_finishes() {
+ let t = tempfile::tempdir().unwrap();
+ let r = t.path();
+ for i in 0..20 {
+ put(r, &format!("original/P{i:02}"), 50, mins(200 - i));
+ put(r, &format!("full/P{i:02}"), 50, mins(200 - i));
+ }
+ let cap = 10 * 52 * 1024;
+ for stop in [0, 1, 7, 19] {
+ let out = trim_with(r, cap, &guard(&[]), Some(stop));
+ assert!(out.removed <= stop);
+ all_whole(r);
+ // What is counted is exactly what is on disk.
+ assert_eq!(scan(r).used, out.after);
+ }
+ let out = trim(r, cap, &guard(&[]));
+ assert!(out.after <= cap && out.after == scan(r).used);
+ all_whole(r);
+ }
+
+ /// A download that died with the app leaves a `.part`: swept once clearly abandoned, never
+ /// while one may still be landing, and never counted as the picture.
+ #[test]
+ fn abandoned_parts_are_swept() {
+ let t = tempfile::tempdir().unwrap();
+ let r = t.path();
+ let dead = put(r, "original/A.9f.part", 200, Duration::from_secs(2 * 3600));
+ let live = put(r, "video/B.3c.part", 200, Duration::from_secs(30));
+ let out = trim(r, 10 * GB, &guard(&[]));
+ assert_eq!(out.before, 0, "parts are not pictures");
+ assert!(!dead.exists() && live.exists());
+ }
+
+ /// Settings offers fixed sizes; anything else is taken as the nearest, and a saved value
+ /// that is not one of them (or not a number) is the default.
+ #[test]
+ fn caps_are_the_sizes_offered() {
+ assert_eq!(snap(3 * GB), 2 * GB);
+ assert_eq!(snap(0), 512 * MB);
+ assert_eq!(snap(u64::MAX), 50 * GB);
+ assert_eq!(parse_cap(None), DEFAULT_CAP);
+ assert_eq!(parse_cap(Some("banana".into())), DEFAULT_CAP);
+ assert_eq!(parse_cap(Some("12345".into())), DEFAULT_CAP);
+ assert_eq!(parse_cap(Some((5 * GB).to_string())), 5 * GB);
+ // A fifth of the room it could have, when the disk is short of it.
+ assert_eq!(limit(10 * GB, 100 * GB, 0), 10 * GB);
+ assert_eq!(limit(10 * GB, 4 * GB, GB), GB);
+ }
+
+ /// A trim on a copy of a real cache (never the real one): `QUINCE_CACHE_COPY=<copy of
+ /// photos/> QUINCE_CACHE_CAP=<bytes> cargo test -p quince-app on_a_copy -- --ignored`.
+ #[test]
+ #[ignore = "needs a copy of a real cache"]
+ fn on_a_copy() {
+ let root = PathBuf::from(std::env::var("QUINCE_CACHE_COPY").unwrap());
+ let cap: u64 = std::env::var("QUINCE_CACHE_CAP").unwrap().parse().unwrap();
+ let thumbs = thumbnails(&root);
+ let t = Instant::now();
+ let out = trim(&root, cap, &guard(&[]));
+ println!(
+ "{} pictures let go, {} → {} bytes against {cap}, in {:?}; thumbnails {} → {}",
+ out.removed,
+ out.before,
+ out.after,
+ t.elapsed(),
+ thumbs,
+ thumbnails(&root)
+ );
+ assert_eq!(thumbnails(&root), thumbs);
+ assert!(out.after <= cap || out.held_back);
+ assert_eq!(scan(&root).used, out.after);
+ }
+
+ /// Drive's Keep on This Computer lives in its own cache beside Photos': never walked here.
+ #[test]
+ fn other_caches_are_never_touched() {
+ let t = tempfile::tempdir().unwrap();
+ let data = t.path();
+ let kept = put(data, "drive-cache/FILE__x", 300, mins(900));
+ let kept_list = put(data, "drive-cache/.kept.json", 1, mins(900));
+ let waiting = put(
+ data,
+ "photos-folder-writes/outgoing/h/IMG.HEIC",
+ 300,
+ mins(900),
+ );
+ let loose = put(data, "photos/LEGACY", 300, mins(900));
+ put(data, "photos/original/A", 300, mins(900));
+ clear(&data.join("photos"), &guard(&[]));
+ for f in [kept, kept_list, waiting, loose] {
+ assert!(f.exists(), "{f:?}");
+ }
+ assert!(!data.join("photos/original/A").exists());
+ }
+}
diff --git a/src-tauri/src/photos.rs b/src-tauri/src/photos.rs
index 622d265..af026f7 100644
--- a/src-tauri/src/photos.rs
+++ b/src-tauri/src/photos.rs
@@ -34,6 +34,9 @@ pub fn remember(links: HashMap<String, Links>) {
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let map = kept.get_or_insert_with(HashMap::new);
+ // Links past their life are of no use (each is asked of Apple again), so they go: kept,
+ // every photo's six signed links stayed in memory for as long as the app ran.
+ map.retain(|_, (_, at)| at.elapsed() < LINK_LIFE);
for (master, l) in links {
map.insert(master, (l, now));
}
@@ -194,7 +197,16 @@ pub async fn fitted(app: &AppHandle, id: &str, long: u32) -> Result<Vec<u8>, Str
.join("fit")
.join(long.to_string())
.join(id);
+ let preview = long > crate::photo_cache::THUMB_STEP;
if let Ok(bytes) = tokio::fs::read(&path).await {
+ // The viewer's sizes are previews, let go of longest unseen first: seen now.
+ if preview {
+ tokio::task::spawn_blocking(move || {
+ if let Ok(f) = std::fs::File::open(&path) {
+ let _ = f.set_modified(std::time::SystemTime::now());
+ }
+ });
+ }
return Ok(bytes);
}
MAKING_READY.call_once(|| {
@@ -233,8 +245,11 @@ pub async fn fitted(app: &AppHandle, id: &str, long: u32) -> Result<Vec<u8>, Str
let _ = tokio::fs::create_dir_all(dir).await;
}
let part = path.with_extension("part");
- if tokio::fs::write(&part, &bytes).await.is_ok() {
- let _ = tokio::fs::rename(&part, &path).await;
+ if tokio::fs::write(&part, &bytes).await.is_ok()
+ && tokio::fs::rename(&part, &path).await.is_ok()
+ && preview
+ {
+ crate::photo_cache::grew(app);
}
return Ok(bytes);
}
@@ -261,8 +276,16 @@ pub async fn picture(app: &AppHandle, id: &str, size: Size) -> Result<Vec<u8>, S
/// held whole in memory, and a half-written file is never served.
pub async fn cached(app: &AppHandle, id: &str, size: Size) -> Result<PathBuf, String> {
let path = cache_path(app, id, size);
- if tokio::fs::metadata(&path).await.is_ok() {
- // Seen now: the last to go when the cache is trimmed (see `trim_cache`).
+ // Held for its reader as it is found, so no trim lets it go before it is read (see
+ // photo_cache): found and held in one step, never found and then lost.
+ let found = {
+ let p = path.clone();
+ tokio::task::spawn_blocking(move || crate::photo_cache::hold_if_cached(&p))
+ .await
+ .unwrap_or(false)
+ };
+ if found {
+ // Seen now: the last to go when the cache is trimmed (see `photo_cache`).
if size != Size::Thumb {
let touched = path.clone();
tokio::task::spawn_blocking(move || {
@@ -323,6 +346,8 @@ async fn heic_full(app: &AppHandle, id: &str, path: &std::path::Path) -> Result<
tokio::fs::rename(&part, path)
.await
.map_err(|e| e.to_string())?;
+ crate::photo_cache::hold(path);
+ crate::photo_cache::grew(app);
Ok(path.to_path_buf())
}
@@ -362,136 +387,124 @@ async fn from_apple(
if !done && !fetch(new_link(&http, &root, params, &photo, size).await?).await? {
return Err("Apple did not send that picture.".into());
}
- // A video's poster that is black (Apple makes it from the first frame) is made again from
- // the first frame that shows something, before anyone sees it.
- if photo.kind == quince_core::photos::Kind::Video && matches!(size, Size::Thumb | Size::Medium)
+ // Held for whoever asked, and the cache checked against its cap soon after (thumbnails are
+ // never let go of, so a thumbnail landing asks nothing).
+ crate::photo_cache::hold(&path);
+ if size != Size::Thumb {
+ crate::photo_cache::grew(app);
+ }
+ // A video's picture that is black (Apple makes them from the first frame) is made again
+ // from the first frame that shows something, before anyone sees it — every size of it.
+ if photo.kind == quince_core::photos::Kind::Video
+ && matches!(size, Size::Thumb | Size::Medium | Size::Full)
{
repair_poster(app, id).await;
}
Ok(path)
}
-/// When a video's thumbnail is black, its first frame that is not (see `crate::poster`) made
-/// its thumbnail and screen-sized picture instead, at the sizes Apple's were, and every size
-/// made from the black one let go. Answers whether it was remade.
-pub async fn repair_poster(app: &AppHandle, id: &str) -> bool {
- let thumb = cache_path(app, id, Size::Thumb);
- let Ok(bytes) = tokio::fs::read(&thumb).await else {
- return false;
+/// A video's own picture: its first frame that shows something (see `crate::poster`), upright,
+/// read once from the film and kept (`photos/poster/<id>`). An empty file there says the film
+/// is dark all through, so it is not read again. `None` when there is none to be had.
+async fn seen_frame(app: &AppHandle, id: &str) -> Option<Vec<u8>> {
+ let kept = crate::state_dir(app).join("photos").join("poster").join(id);
+ if let Ok(bytes) = tokio::fs::read(&kept).await {
+ return (!bytes.is_empty()).then_some(bytes);
+ }
+ // The film on disk already, whichever it is; otherwise Apple's streaming copy, a few
+ // megabytes, which the player wants anyway.
+ let film = [Size::Original, Size::Video]
+ .into_iter()
+ .map(|s| cache_path(app, id, s))
+ .find(|p| p.exists());
+ let film = match film {
+ Some(path) => path,
+ None => Box::pin(cached(app, id, Size::Video)).await.ok()?,
};
- if !crate::cpu::run(move || quince_media::is_blank(&bytes))
+ let frame = crate::cpu::run(move || crate::poster::first_seen_frame(&film))
.await
- .unwrap_or(false)
+ .ok()?
+ .ok()?;
+ if let Some(dir) = kept.parent() {
+ let _ = tokio::fs::create_dir_all(dir).await;
+ }
+ let part = kept.with_extension("part");
+ if tokio::fs::write(&part, frame.as_deref().unwrap_or_default())
+ .await
+ .is_ok()
{
- return false;
+ let _ = tokio::fs::rename(&part, &kept).await;
}
- // The original when it is on disk already; otherwise the small rendition, a few megabytes.
- let original = cache_path(app, id, Size::Original);
- let film = if original.exists() {
- original
- } else {
- match Box::pin(cached(app, id, Size::Video)).await {
- Ok(path) => path,
- Err(_) => return false,
- }
- };
- let Ok(Ok(Some(frame))) = crate::cpu::run(move || crate::poster::first_seen_frame(&film)).await
- else {
- return false;
- };
- for size in [Size::Thumb, Size::Medium] {
+ frame
+}
+
+/// Every picture Apple made of a video that came out black — it makes them from the first
+/// frame, and a screen recording's or a fade-in's is black — made again from the video's own
+/// picture (`seen_frame`), at the size Apple's was, and every size made from a black one let
+/// go. Each picture is looked at on its own: the thumbnail repaired once did not stop a black
+/// screen-sized picture fetched later from being shown as the video's poster and slideshow
+/// still. Answers whether any was remade.
+pub async fn repair_poster(app: &AppHandle, id: &str) -> bool {
+ let mut frame: Option<Vec<u8>> = None;
+ let mut remade = false;
+ for size in [Size::Thumb, Size::Medium, Size::Full] {
let path = cache_path(app, id, size);
- let old = tokio::fs::read(&path).await.unwrap_or_default();
- let src = frame.clone();
- // Apple's own sizes: the thumbnail's long side, and the screen-sized one's.
- let long =
- quince_media::long_side(&old).unwrap_or(if size == Size::Thumb { 512 } else { 2048 });
+ let Ok(old) = tokio::fs::read(&path).await else {
+ continue;
+ };
+ let looked = old.clone();
+ if !crate::cpu::run(move || quince_media::is_blank(&looked))
+ .await
+ .unwrap_or(false)
+ {
+ continue;
+ }
+ if frame.is_none() {
+ frame = seen_frame(app, id).await;
+ }
+ let Some(src) = frame.clone() else {
+ break;
+ };
+ // Apple's own sizes: the long side the black one had.
+ let fallback = match size {
+ Size::Thumb => 512,
+ Size::Medium => 2048,
+ _ => 4096,
+ };
+ let long = quince_media::long_side(&old).unwrap_or(fallback);
let Ok(Ok(made)) =
crate::cpu::run(move || quince_media::fit(&src, long).map(|m| m.unwrap_or(src))).await
else {
continue;
};
- if let Some(dir) = path.parent() {
- let _ = tokio::fs::create_dir_all(dir).await;
- }
let part = path.with_extension("part");
- if tokio::fs::write(&part, &made).await.is_ok() {
- let _ = tokio::fs::rename(&part, &path).await;
+ if tokio::fs::write(&part, &made).await.is_ok()
+ && tokio::fs::rename(&part, &path).await.is_ok()
+ {
+ remade = true;
}
}
- for step in FITS {
- let _ = tokio::fs::remove_file(
- crate::state_dir(app)
- .join("photos")
- .join("fit")
- .join(step.to_string())
- .join(id),
- )
- .await;
- }
- true
-}
-
-/// Every picture the cache holds that can go — all but the grid's thumbnails, which every view
-/// draws from and which are small — with its size and when it was last seen.
-fn trimmable(root: &std::path::Path) -> Vec<(PathBuf, u64, std::time::SystemTime)> {
- let mut out = Vec::new();
- let Ok(sizes) = std::fs::read_dir(root) else {
- return out;
- };
- for dir in sizes.flatten() {
- if dir.file_name() == Size::Thumb.name() || !dir.path().is_dir() {
- continue;
- }
- for f in std::fs::read_dir(dir.path())
- .into_iter()
- .flatten()
- .flatten()
- {
- if let Ok(m) = f.metadata() {
- // A download still being written is never cut from under it.
- if m.is_file() && f.path().extension().is_none_or(|e| e != "part") {
- let seen = m.modified().unwrap_or(std::time::UNIX_EPOCH);
- out.push((f.path(), m.len(), seen));
- }
- }
+ if remade {
+ for step in FITS {
+ let _ = tokio::fs::remove_file(
+ crate::state_dir(app)
+ .join("photos")
+ .join("fit")
+ .join(step.to_string())
+ .join(id),
+ )
+ .await;
}
}
- out
+ remade
}
-/// The photo cache held to its budget (`mount::budget`: 10 GB, or a fifth of the free space when
-/// less), as Photos on a Mac with "Optimize Storage" keeps what was looked at last and lets the
-/// rest go: the longest unseen go first, down to four fifths of it, so a trim is not needed again
-/// at once. A picture seen in the last five minutes stays — it is on screen. Thumbnails always
-/// stay. Answers the room left under the budget.
+/// The photo cache held to its cap (Settings; see `photo_cache`), the longest unseen originals
+/// and previews let go of first; thumbnails always stay. Off the async threads: it walks the
+/// disk. Answers the room left under the cap.
pub fn trim_cache(app: &AppHandle) -> u64 {
- let root = crate::state_dir(app).join("photos");
- if std::fs::create_dir_all(&root).is_err() {
- return 0;
- }
- trim(&root, crate::mount::budget(&root))
-}
-
-fn trim(root: &std::path::Path, budget: u64) -> u64 {
- let mut files = trimmable(root);
- let mut used: u64 = files.iter().map(|(_, len, _)| len).sum();
- if used > budget {
- files.sort_by_key(|(_, _, seen)| *seen);
- let recent = std::time::SystemTime::now() - Duration::from_secs(5 * 60);
- for (path, len, seen) in files {
- if used <= budget / 5 * 4 {
- break;
- }
- if seen > recent {
- continue;
- }
- if std::fs::remove_file(&path).is_ok() {
- used -= len;
- }
- }
- }
- budget.saturating_sub(used)
+ let (out, limit) = crate::photo_cache::trim_now(app);
+ limit.saturating_sub(out.after)
}
/// Keeps the newest photos' whole pictures, and videos, on disk ahead of being opened — as
@@ -507,10 +520,15 @@ pub fn keep_ahead(app: AppHandle) {
}
tauri::async_runtime::spawn(async move {
use futures_util::StreamExt;
- let newest = {
+ let (newest, every_video) = {
let data = app.state::<Data>();
let library = data.0.lock().await;
- library.photos(View::Library).unwrap_or_default()
+ let videos: Vec<String> = grid_photos(&library, None)
+ .into_iter()
+ .filter(|p| p.kind == quince_core::photos::Kind::Video)
+ .map(|p| p.id)
+ .collect();
+ (library.photos(View::Library).unwrap_or_default(), videos)
};
// Videos whose black poster was kept before posters were remade: remade now, once —
// once per video for the life of the process. Every pass decoded every video's poster
@@ -520,11 +538,10 @@ pub fn keep_ahead(app: AppHandle) {
let looked = LOOKED
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
- newest
- .iter()
- .filter(|p| p.kind == quince_core::photos::Kind::Video)
- .filter(|p| looked.as_ref().is_none_or(|l| !l.contains(&p.id)))
- .map(|p| p.id.clone())
+ // Hidden's videos too: their posters show in its grid and its slideshow.
+ every_video
+ .into_iter()
+ .filter(|id| looked.as_ref().is_none_or(|l| !l.contains(id)))
.collect()
};
for id in unlooked {
@@ -545,13 +562,15 @@ pub fn keep_ahead(app: AppHandle) {
newest
.into_iter()
.take(600)
- .map(|p| {
- let size = if p.kind == quince_core::photos::Kind::Video {
- Size::Original
+ // A video's streaming copy as well as its original: the copy is what the
+ // window plays (H.264, its index first, a few megabytes), so a video opens
+ // playing from the disk, never waiting on Apple for its first frame.
+ .flat_map(|p| {
+ if p.kind == quince_core::photos::Kind::Video {
+ vec![(p.id.clone(), Size::Video), (p.id, Size::Original)]
} else {
- Size::Full
- };
- (p.id, size)
+ vec![(p.id, Size::Full)]
+ }
})
.filter(|(id, size)| !cache_path(&ask, id, *size).exists())
.collect()
@@ -606,6 +625,28 @@ pub struct Shown {
pub stage_w: f64,
pub stage_h: f64,
pub dpr: f64,
+ /// The view the grid is on: its pictures are made first.
+ #[serde(default)]
+ pub view: Option<View>,
+}
+
+/// Every photo a grid can show, the view being looked at first: the library, Hidden and
+/// Recently Deleted, each once. Made for the library alone, Hidden's pictures were made only as
+/// it was scrolled — every tile waited on one, and showed the soft thumbnail meanwhile.
+fn grid_photos(library: &quince_core::Library, first: Option<View>) -> Vec<Photo> {
+ let mut seen = std::collections::HashSet::new();
+ let mut out = Vec::new();
+ let views = first
+ .into_iter()
+ .chain([View::Library, View::Hidden, View::RecentlyDeleted]);
+ for view in views {
+ for p in library.photos(view).unwrap_or_default() {
+ if seen.insert(p.id.clone()) {
+ out.push(p);
+ }
+ }
+ }
+ out
}
/// The step a picture is made at for a longer side of `long` device pixels — the window's own
@@ -668,19 +709,27 @@ pub fn prepare(app: AppHandle) {
let photos = {
let data = app.state::<Data>();
let library = data.0.lock().await;
- library.photos(View::Library).unwrap_or_default()
+ grid_photos(&library, shown.view)
};
let fit_dir = crate::state_dir(&app).join("photos").join("fit");
// A stat per picture, off the runtime's workers (see keep_ahead).
let wanted: Vec<(String, u32)> = tauri::async_runtime::spawn_blocking(move || {
- photos
- .iter()
- .filter(|p| p.kind != quince_core::photos::Kind::Video)
+ // The grid's pictures for the whole library while they are thumbnail-sized (kept
+ // always); larger ones — a close zoom on a wide screen — are previews the cache's cap
+ // lets go of, so only the newest are made ahead: made for every photo, they were let
+ // go and made again after every sync.
+ let stills = || {
+ photos
+ .iter()
+ .filter(|p| p.kind != quince_core::photos::Kind::Video)
+ };
+ stills()
.map(|p| (p.id.clone(), steps_of(p, shown).0))
+ .enumerate()
+ .filter(|(i, (_, step))| *step <= crate::photo_cache::THUMB_STEP || *i < 600)
+ .map(|(_, w)| w)
.chain(
- photos
- .iter()
- .filter(|p| p.kind != quince_core::photos::Kind::Video)
+ stills()
.take(600)
.map(|p| (p.id.clone(), steps_of(p, shown).1)),
)
@@ -827,7 +876,13 @@ pub enum Film {
/// served from the bytes as they land.
pub async fn film(app: &AppHandle, id: &str, size: Size) -> Result<Film, String> {
let path = cache_path(app, id, size);
- if tokio::fs::metadata(&path).await.is_ok() {
+ let found = {
+ let p = path.clone();
+ tokio::task::spawn_blocking(move || crate::photo_cache::hold_if_cached(&p))
+ .await
+ .unwrap_or(false)
+ };
+ if found {
return Ok(Film::Whole(path));
}
if let Some(g) = GROWING
@@ -890,6 +945,7 @@ pub async fn film(app: &AppHandle, id: &str, size: Size) -> Result<Film, String>
map.insert(path.clone(), growth.clone());
}
let g = growth.clone();
+ let app = app.clone();
tauri::async_runtime::spawn(async move {
use futures_util::StreamExt;
use std::sync::atomic::Ordering;
@@ -913,7 +969,11 @@ pub async fn film(app: &AppHandle, id: &str, size: Size) -> Result<Film, String>
drop(out);
ok = ok && g.have.load(Ordering::SeqCst) == g.total;
let whole = ok && tokio::fs::rename(&g.part, &path).await.is_ok();
- if !whole {
+ if whole {
+ // Still being played from: held, and the cap checked once it is whole.
+ crate::photo_cache::hold(&path);
+ crate::photo_cache::grew(&app);
+ } else {
let _ = tokio::fs::remove_file(&g.part).await;
}
g.ended(whole);
@@ -939,6 +999,27 @@ pub async fn film_turn(app: &AppHandle, id: &str, size: Size) -> Result<[i32; 4]
Ok(found.map_or([1, 0, 0, 1], |(_, m)| m))
}
+/// How much a film is drawn larger than its box so only its clean aperture shows (see
+/// `quince_media::video_zoom`): a Live Photo's moving part then lies exactly over its still.
+pub async fn film_zoom(app: &AppHandle, id: &str, size: Size) -> Result<f64, String> {
+ let path = match film(app, id, size).await? {
+ Film::Whole(path) => path,
+ Film::Growing(g) => {
+ // Its header landed (a streaming copy keeps it at the front).
+ g.matrix().await?;
+ if g.kept.exists() {
+ g.kept.clone()
+ } else {
+ g.part.clone()
+ }
+ }
+ };
+ tokio::task::spawn_blocking(move || quince_media::video_zoom(&path))
+ .await
+ .map_err(|e| e.to_string())?
+ .map_err(|e| e.to_string())
+}
+
/// What a picture's bytes are, for the window to draw them.
/// The bytes a `Range: bytes=…` header asks of a file `len` long, as `(first, last)` inclusive,
/// at most `most` of them. No header is the whole file; one this file cannot satisfy is `None`.
@@ -994,6 +1075,48 @@ pub async fn photos_list(view: View, data: State<'_, Data>) -> UiResult<Vec<Phot
data.0.lock().await.photos(view).map_err(|e| e.to_string())
}
+/// What the grid lays out before any photo comes: every photo's id, the date it is grouped
+/// by and its marks, a few bytes each (see `PhotoIndex`). The photos follow a page at a time,
+/// as the grid comes near them — a library of fifty thousand is never sent whole.
+#[tauri::command]
+pub async fn photos_index(
+ source: quince_core::photos::Source,
+ order: Option<quince_core::photos::Order>,
+ data: State<'_, Data>,
+) -> UiResult<quince_core::photos::PhotoIndex> {
+ data.0
+ .lock()
+ .await
+ .photo_index(&source, order)
+ .map_err(|e| e.to_string())
+}
+
+/// `limit` photos from `offset` of a source, in its index's order.
+#[tauri::command]
+pub async fn photos_page(
+ source: quince_core::photos::Source,
+ order: Option<quince_core::photos::Order>,
+ offset: usize,
+ limit: usize,
+ data: State<'_, Data>,
+) -> UiResult<Vec<Photo>> {
+ data.0
+ .lock()
+ .await
+ .photo_page(&source, order, offset, limit)
+ .map_err(|e| e.to_string())
+}
+
+/// Photos by id — a selection reaching past the pages the window holds.
+#[tauri::command]
+pub async fn photos_get(ids: Vec<String>, data: State<'_, Data>) -> UiResult<Vec<Photo>> {
+ data.0
+ .lock()
+ .await
+ .photos_by_ids(&ids)
+ .map_err(|e| e.to_string())
+}
+
/// The Shared Albums service for the signed-in account: its client, address and params.
async fn shared_streams(
auth: &State<'_, Auth>,
@@ -1646,6 +1769,17 @@ pub async fn photo_video_turn(id: String, which: String, app: AppHandle) -> UiRe
film_turn(&app, &id, size).await
}
+/// How much larger than its box a film is drawn (see `film_zoom`).
+#[tauri::command]
+pub async fn photo_video_zoom(id: String, which: String, app: AppHandle) -> UiResult<f64> {
+ let size = if which == "video" {
+ Size::Video
+ } else {
+ Size::Original
+ };
+ film_zoom(&app, &id, size).await
+}
+
/// A video opened in this computer's own player. WebKitGTK plays nothing without GStreamer's
/// codec plugins, which many systems (his among them) do not have, so a video is fetched once,
/// kept beside the other pictures under its own name, and handed to the system's player.
@@ -2591,38 +2725,6 @@ async fn refresh_photos(app: &AppHandle) {
#[cfg(test)]
mod tests {
-
- /// Over its budget, the cache lets the longest-unseen pictures go first, down to four
- /// fifths; thumbnails and what was seen in the last minutes stay.
- #[test]
- fn the_cache_keeps_to_its_budget_longest_unseen_first() {
- let dir = tempfile::tempdir().unwrap();
- let root = dir.path();
- let put = |size: &str, name: &str, ago: u64| {
- std::fs::create_dir_all(root.join(size)).unwrap();
- let p = root.join(size).join(name);
- std::fs::write(&p, vec![0u8; 100]).unwrap();
- let f = std::fs::File::options().write(true).open(&p).unwrap();
- f.set_modified(std::time::SystemTime::now() - Duration::from_secs(ago))
- .unwrap();
- };
- put("thumb", "t", 99_999);
- put("original", "oldest", 9_000);
- put("full", "older", 8_000);
- put("full", "old", 7_000);
- put("original", "now", 10);
- // 400 bytes held against 300: down to 240 — the two longest unseen go.
- let room = trim(root, 300);
- assert!(!root.join("original/oldest").exists() && !root.join("full/older").exists());
- assert!(root.join("full/old").exists(), "no more than needed");
- assert!(
- root.join("original/now").exists(),
- "what is on screen stays"
- );
- assert!(root.join("thumb/t").exists(), "thumbnails always stay");
- assert_eq!(room, 100);
- }
-
use super::*;
#[test]
@@ -2656,6 +2758,34 @@ mod tests {
assert_eq!(byte_range(None, 0, all), None);
}
+ /// Pictures are made ahead for every photo a grid can show — Hidden and Recently Deleted
+ /// too, not the library alone — each once, the view being looked at first.
+ #[test]
+ fn hidden_and_deleted_are_made_ahead_too_the_view_shown_first() {
+ let photo = |id: &str, t: i64, hidden: bool, deleted: bool| -> Photo {
+ serde_json::from_value(serde_json::json!({
+ "id": id, "master": format!("m{id}"), "takenAt": t, "kind": "image", "width": 4032,
+ "height": 3024, "favorite": false, "hidden": hidden, "deleted": deleted, "subtype": 0
+ }))
+ .unwrap()
+ };
+ let mut lib = quince_core::Library::in_memory().unwrap();
+ lib.put_photos(&[
+ photo("L1", 30, false, false),
+ photo("H1", 20, true, false),
+ photo("H2", 10, true, false),
+ photo("D1", 5, false, true),
+ ])
+ .unwrap();
+ let ids =
+ |first| -> Vec<String> { grid_photos(&lib, first).into_iter().map(|p| p.id).collect() };
+ assert_eq!(ids(None), ["L1", "H1", "H2", "D1"]);
+ assert_eq!(ids(Some(View::Hidden)), ["H1", "H2", "L1", "D1"]);
+ assert_eq!(ids(Some(View::Library)), ["L1", "H1", "H2", "D1"]);
+ // A view inside the library (Favorites) adds nothing the library does not have.
+ assert_eq!(ids(Some(View::Favorites)), ["L1", "H1", "H2", "D1"]);
+ }
+
/// The steps made ahead are the ones the window asks for (fitSrc, tileSrc, viewSrc).
#[test]
fn steps_are_the_window_s() {
@@ -2670,6 +2800,7 @@ mod tests {
stage_w: 1300.0,
stage_h: 800.0,
dpr: 1.0,
+ view: None,
};
// A square crop of a 4:3 photo reaches 240 along its long side; the stage draws it
// 1066 wide (800 high × 4/3).
diff --git a/src-tauri/src/power.rs b/src-tauri/src/power.rs
new file mode 100644
index 0000000..2d9be84
--- /dev/null
+++ b/src-tauri/src/power.rs
@@ -0,0 +1,82 @@
+//! Whether this computer runs on its battery, so the checks for changes made elsewhere can
+//! come less often while it does.
+//!
+//! Linux: UPower's `OnBattery` on the system bus, read once and then followed as it changes.
+//! Elsewhere, or with no UPower, it reads as plugged in and nothing changes. Only the polls
+//! that stand in for a push slow down, and never while a window has the focus: the person
+//! looking at it sees changes as fast as ever, and Apple's own pushes are never held back.
+
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::time::Duration;
+
+static ON_BATTERY: AtomicBool = AtomicBool::new(false);
+
+pub fn on_battery() -> bool {
+ ON_BATTERY.load(Ordering::Relaxed)
+}
+
+/// `every` as it is on mains power, or twice as long on the battery — unless a window has the
+/// focus, when it stays as it is.
+pub fn pace(every: Duration, focused: bool) -> Duration {
+ stretch(every, focused, on_battery())
+}
+
+fn stretch(every: Duration, focused: bool, battery: bool) -> Duration {
+ if battery && !focused {
+ every * 2
+ } else {
+ every
+ }
+}
+
+/// Follow UPower for as long as the app runs. Once per run.
+pub fn watch() {
+ static ONCE: std::sync::Once = std::sync::Once::new();
+ ONCE.call_once(follow);
+}
+
+fn follow() {
+ #[cfg(target_os = "linux")]
+ tauri::async_runtime::spawn(async {
+ use futures_util::StreamExt;
+ let Ok(bus) = zbus::Connection::system().await else {
+ return;
+ };
+ let Ok(builder) = zbus::proxy::Builder::<zbus::Proxy<'static>>::new(&bus)
+ .destination("org.freedesktop.UPower")
+ .and_then(|b| b.path("/org/freedesktop/UPower"))
+ .and_then(|b| b.interface("org.freedesktop.UPower"))
+ else {
+ return;
+ };
+ let Ok(upower) = builder.build().await else {
+ return;
+ };
+ if let Ok(now) = upower.get_property::<bool>("OnBattery").await {
+ ON_BATTERY.store(now, Ordering::Relaxed);
+ }
+ let mut changes = upower.receive_property_changed::<bool>("OnBattery").await;
+ while let Some(change) = changes.next().await {
+ if let Ok(now) = change.get().await {
+ ON_BATTERY.store(now, Ordering::Relaxed);
+ }
+ }
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_battery_slows_only_what_nobody_is_looking_at() {
+ let every = Duration::from_secs(15);
+ assert_eq!(stretch(every, false, false), every);
+ assert_eq!(stretch(every, false, true), Duration::from_secs(30));
+ assert_eq!(
+ stretch(every, true, true),
+ every,
+ "a focused window keeps its pace"
+ );
+ }
+}
diff --git a/src-tauri/src/push.rs b/src-tauri/src/push.rs
index e799864..5e46aaf 100644
--- a/src-tauri/src/push.rs
+++ b/src-tauri/src/push.rs
@@ -1,17 +1,29 @@
//! Apple's pushes, turned into refreshes of exactly what changed.
//!
-//! A change made on a phone used to wait for the next five-minute pass. Now a parked
-//! connection hears of it from Apple within about a second (see
-//! `quince_icloud::push`), and only the service it was in is refreshed. The timed pass stays
-//! as the floor beneath this, for the services Apple does not push here and for any push
-//! that went missing.
+//! A change made on a phone reaches this computer two ways:
+//!
+//! - **Live:** the web push socket icloud.com itself uses (`quince_icloud::courier`). Apple
+//! says within about a second that Notes, Reminders or Photos changed, and only that
+//! service is refreshed. A dropped socket is reconnected with backoff; a refusal (an
+//! endpoint Apple retired, a bad request) is tried again only after half an hour and
+//! more, never in a loop.
+//! - **Polling, while there is no live channel:** each container's `changes/database` token —
+//! one small read-only request — is asked every few seconds while a window has focus, less
+//! often while one is merely open, and rarely from the tray; at once when the window gains
+//! focus or the network comes back ([`wake`]). Only a container whose token moved is
+//! refreshed.
+//!
+//! The log hears one line when the channel goes down and one when it is back. The timed
+//! pass stays as the floor beneath both, for anything that went missing.
use crate::{alerts, refresh, Data, SYNCED};
use quince_auth::Client;
-use std::sync::Arc;
+use quince_icloud::courier::{self, Courier, Failure, Identity};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, LazyLock};
use std::time::{Duration, Instant};
use tauri::{Emitter, Manager};
-use tokio::sync::{mpsc, Mutex};
+use tokio::sync::{mpsc, watch, Mutex};
/// The containers one connection listens to, and the service each one is. Photos measured
/// live (2026-10-19): a change made elsewhere arrives 0.7 to 1.5 seconds after it is written.
@@ -21,11 +33,12 @@ const CONTAINERS: [(&str, &str); 3] = [
("com.apple.photos.cloud", "photos"),
];
-/// How long one wait is left parked before it is parked afresh. Apple answers sooner when
-/// something changes; this only bounds a connection that went quiet without closing.
-const LONGEST_WAIT: Duration = Duration::from_secs(10 * 60);
+/// A registration with the push registry lasts 12 hours (`43200`); it is renewed a little
+/// before, on the same socket.
+const RENEW_REGISTRATION: Duration = Duration::from_secs(11 * 60 * 60);
-/// A token is made for a day (`ttl=86400`); a new one is made a little before.
+/// A token is asked for a day (`86400`); the socket is opened afresh, with a new token, a
+/// little before.
const TOKEN_LIFE: Duration = Duration::from_secs(23 * 60 * 60);
/// A phone sends a burst of pushes for one edit, one per record it saves. They are taken
@@ -40,11 +53,37 @@ fn service_of(container: &str) -> Option<&'static str> {
.map(|(_, s)| *s)
}
+/// Whether the live channel is up right now. While it is, nothing polls.
+static LIVE: AtomicBool = AtomicBool::new(false);
+
+/// Set when the channel comes back: one poll then catches up what changed while it was down.
+static CATCH_UP: AtomicBool = AtomicBool::new(false);
+
+/// Bumped by [`wake`]; the channel and the poller each watch it.
+static WAKE: LazyLock<watch::Sender<u64>> = LazyLock::new(|| watch::channel(0).0);
+
+/// Something happened that makes now a good moment to look: a window gained focus, or the
+/// network came back. A channel that failed for a passing reason is tried again at once, and
+/// a poll runs at once.
+pub fn wake() {
+ WAKE.send_modify(|n| *n = n.wrapping_add(1));
+}
+
+/// Sleep for `wait`, or until [`wake`] — whichever is first. True when woken.
+async fn sleep_or_wake(wait: Duration, woken: &mut watch::Receiver<u64>) -> bool {
+ tokio::select! {
+ () = tokio::time::sleep(wait) => false,
+ r = woken.changed() => r.is_ok(),
+ }
+}
+
pub fn spawn(app: tauri::AppHandle, client: Arc<Mutex<Client>>) {
+ crate::power::watch();
let (tx, rx) = mpsc::unbounded_channel::<&'static str>();
tauri::async_runtime::spawn(refresher(app.clone(), Arc::clone(&client), rx));
tauri::async_runtime::spawn(watch_calendar(app.clone(), Arc::clone(&client), tx.clone()));
- tauri::async_runtime::spawn(watch_contacts(app, Arc::clone(&client), tx.clone()));
+ tauri::async_runtime::spawn(watch_contacts(app.clone(), Arc::clone(&client), tx.clone()));
+ tauri::async_runtime::spawn(poll_cloudkit(app, Arc::clone(&client), tx.clone()));
tauri::async_runtime::spawn(listen(client, tx));
}
@@ -58,9 +97,9 @@ async fn watch_contacts(
) {
let mut tokens: Option<quince_icloud::contacts::Tokens> = None;
let mut backoff = Duration::from_secs(5);
+ let mut woken = WAKE.subscribe();
loop {
- let visible = shown(&app);
- tokio::time::sleep(if visible { LOOK } else { LOOK_HIDDEN }).await;
+ sleep_or_wake(look_every(presence(&app)), &mut woken).await;
let session = {
let guard = client.lock().await;
let s = guard.session();
@@ -102,17 +141,49 @@ async fn watch_contacts(
}
}
-/// Whether the window is in front of anyone: shown and not minimized. A minimized window is
-/// still "visible" to Windows (and to Tauri there), and was asked at the open window's pace.
-fn shown(app: &tauri::AppHandle) -> bool {
- app.get_webview_window("main")
- .is_some_and(|w| w.is_visible().unwrap_or(false) && !w.is_minimized().unwrap_or(false))
+/// How present the app is: a window with focus, one merely on screen, or none (the tray).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Presence {
+ Focused,
+ Open,
+ Hidden,
}
-/// How often Calendar and Contacts are asked whether anything changed: often while the window is open,
-/// rarely from the tray, where only an alert depends on it.
-const LOOK: Duration = Duration::from_secs(4);
-const LOOK_HIDDEN: Duration = Duration::from_secs(30);
+/// Every window counts — the whole-library one and each app's own. A minimized window is
+/// still "visible" to Windows (and to Tauri there), so it is counted as hidden.
+fn presence(app: &tauri::AppHandle) -> Presence {
+ let mut open = false;
+ for w in app.webview_windows().values() {
+ if !w.is_visible().unwrap_or(false) || w.is_minimized().unwrap_or(false) {
+ continue;
+ }
+ if w.is_focused().unwrap_or(false) {
+ return Presence::Focused;
+ }
+ open = true;
+ }
+ if open {
+ Presence::Open
+ } else {
+ Presence::Hidden
+ }
+}
+
+/// How often Calendar and Contacts — which have no push — are asked whether anything changed:
+/// every few seconds while a window has the focus, so a change made on the phone shows as it
+/// would with a push; less often while one is merely open (behind another, on another
+/// workspace), and rarely from the tray, where only an alert depends on it. Focus coming back
+/// asks at once ([`wake`]), so the slower pace is never felt. Asked every four seconds whatever
+/// the window was doing, the two of them made thirty requests a minute all day.
+/// On the battery, what no one is looking at is asked half as often (power.rs).
+fn look_every(presence: Presence) -> Duration {
+ let every = match presence {
+ Presence::Focused => Duration::from_secs(4),
+ Presence::Open => Duration::from_secs(15),
+ Presence::Hidden => Duration::from_secs(60),
+ };
+ crate::power::pace(every, presence == Presence::Focused)
+}
/// Calendar has no push for the web. Its own "has anything changed" call, `/ca/idle`, answers
/// in a few hundred milliseconds with only the calendars whose tag moved, so it is asked every
@@ -131,9 +202,9 @@ async fn watch_calendar(
let mut known: Vec<(String, String)> = Vec::new();
let mut seeded = false;
let mut backoff = Duration::from_secs(5);
+ let mut woken = WAKE.subscribe();
loop {
- let visible = shown(&app);
- tokio::time::sleep(if visible { LOOK } else { LOOK_HIDDEN }).await;
+ sleep_or_wake(look_every(presence(&app)), &mut woken).await;
let session = {
let guard = client.lock().await;
let s = guard.session();
@@ -206,68 +277,338 @@ async fn refresher(
}
}
-/// Keep a connection parked on Apple's push channel for as long as the app runs.
+// --- The live channel ------------------------------------------------------------------------
+
+/// What kind of failure was last met, which decides how soon to try again.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Kind {
+ /// The network, a dropped socket: soon, and sooner still on a wake.
+ Transient,
+ /// Apple asked to be left alone for this long.
+ Limited(Duration),
+ /// Refused outright — a retired endpoint, a bad request. Only after a long while.
+ Refused,
+ /// The session needs signing in again, which happens elsewhere.
+ Reauth,
+}
+
+impl From<&Failure> for Kind {
+ fn from(f: &Failure) -> Self {
+ match f {
+ Failure::Transient(_) => Self::Transient,
+ Failure::RateLimited(d) => Self::Limited(*d),
+ Failure::Refused(_) => Self::Refused,
+ Failure::Reauth => Self::Reauth,
+ }
+ }
+}
+
+/// A channel that stayed up this long was healthy: its loss starts the backoff over.
+const STABLE: Duration = Duration::from_secs(60);
+
+/// When to try the channel again, and when to say anything about it.
+///
+/// Pure bookkeeping, so it is tested on its own: the backoff for each kind of failure, that a
+/// channel which connects and drops at once still backs off, that a refusal is never retried
+/// in a tight loop (not even on a wake), and that the log hears one line per change of state.
+#[derive(Debug, Default)]
+struct Pace {
+ /// Failures in a row, since the channel was last healthy.
+ failures: u32,
+ last: Option<Kind>,
+ /// Down, and said so. Cleared — with one line — when it is back.
+ down_since: Option<Instant>,
+ /// Up at least once in this run.
+ ever_up: bool,
+}
+
+/// Grows `base` by doubling per failure after the first, up to `cap`.
+fn doubling(base: Duration, failures: u32, cap: Duration) -> Duration {
+ let shift = failures.saturating_sub(1).min(16);
+ base.saturating_mul(1u32 << shift).min(cap)
+}
+
+impl Pace {
+ /// How long to wait after this failure.
+ fn delay(&self) -> Duration {
+ let n = self.failures.max(1);
+ match self.last.unwrap_or(Kind::Transient) {
+ Kind::Transient => doubling(Duration::from_secs(1), n, Duration::from_secs(5 * 60)),
+ Kind::Limited(asked) => asked.max(doubling(
+ Duration::from_secs(1),
+ n,
+ Duration::from_secs(5 * 60),
+ )),
+ Kind::Refused => doubling(
+ Duration::from_secs(30 * 60),
+ n,
+ Duration::from_secs(6 * 60 * 60),
+ ),
+ Kind::Reauth => doubling(Duration::from_secs(2 * 60), n, Duration::from_secs(30 * 60)),
+ }
+ }
+
+ /// The channel could not be opened, or was lost after `lasted` (`None`: never opened).
+ /// Returns the wait before the next try, and whether this is the moment to say the channel
+ /// is down — the first failure only.
+ fn failed(&mut self, kind: Kind, lasted: Option<Duration>, now: Instant) -> (Duration, bool) {
+ if lasted.is_some_and(|l| l >= STABLE) {
+ self.failures = 0;
+ }
+ self.failures = self.failures.saturating_add(1);
+ self.last = Some(kind);
+ let announce = self.down_since.is_none();
+ if announce {
+ self.down_since = Some(now);
+ }
+ (self.delay(), announce)
+ }
+
+ /// The channel is up. `Some(how long it was down)` when that was announced, for the one
+ /// line saying it is back. The failure count stays until the channel proves stable.
+ fn up(&mut self, now: Instant) -> Option<Duration> {
+ self.ever_up = true;
+ self.down_since.take().map(|t| now.duration_since(t))
+ }
+
+ /// Whether a wake (focus, network back) may cut the wait short. Only a passing failure:
+ /// a refusal or a rate limit is waited out whatever happens.
+ fn wake_may_retry(&self) -> bool {
+ matches!(self.last, None | Some(Kind::Transient))
+ }
+}
+
+/// Keep the live channel open for as long as the app runs.
async fn listen(client: Arc<Mutex<Client>>, tx: mpsc::UnboundedSender<&'static str>) {
- let client_id = uuid::Uuid::new_v4().to_string().to_uppercase();
let containers: Vec<&str> = CONTAINERS.iter().map(|(c, _)| *c).collect();
- let mut backoff = Duration::from_secs(1);
- let mut first = true;
+ let mut identity = Identity::new();
+ let mut pace = Pace::default();
+ let mut woken = WAKE.subscribe();
loop {
let session = {
let guard = client.lock().await;
let s = guard.session();
s.webservices
.is_some()
- .then(|| s.service_url("ckdeviceservice"))
+ .then(|| s.dsid.clone())
.flatten()
- .map(|root| (guard.http().clone(), guard.service_params(), root))
+ .map(|dsid| (guard.http().clone(), dsid))
};
- let Some((http, params, root)) = session else {
- // Not signed in, or no CloudKit for this account: look again shortly.
- tokio::time::sleep(Duration::from_secs(30)).await;
+ let Some((http, dsid)) = session else {
+ // Not signed in yet: look again shortly.
+ sleep_or_wake(Duration::from_secs(30), &mut woken).await;
continue;
};
- let channel =
- match quince_icloud::push::open(&http, &root, &params, &client_id, &containers).await {
- Ok(channel) => channel,
- Err(e) => {
- quiet!("push: could not open the channel: {e}");
- tokio::time::sleep(backoff).await;
- backoff = (backoff * 2).min(Duration::from_secs(5 * 60));
+ let opened = Instant::now();
+ let failure = match open(&http, &mut identity, &containers, &dsid).await {
+ Err(f) => (f, None),
+ Ok(mut channel) => {
+ let was_up = pace.ever_up;
+ match pace.up(Instant::now()) {
+ Some(down) => quiet!("push: live channel back after {}s", down.as_secs()),
+ None if !was_up => quiet!("push: live channel up"),
+ None => {}
+ }
+ LIVE.store(true, Ordering::SeqCst);
+ // What changed while no channel was up was never pushed: one poll catches it.
+ CATCH_UP.store(true, Ordering::SeqCst);
+ wake();
+ let lost = run(&mut channel, &http, &identity, &dsid, &tx, opened).await;
+ LIVE.store(false, Ordering::SeqCst);
+ wake();
+ // Those wakes were for the poller; this loop is not to take them as its own.
+ woken.borrow_and_update();
+ channel.close().await;
+ let Some(lost) = lost else {
+ // The token's day is nearly up: straight back with a new one, unannounced.
+ identity.forget_token();
continue;
+ };
+ (lost, Some(opened.elapsed()))
+ }
+ };
+ let (failure, lasted) = failure;
+ if let Failure::Refused(_) = failure {
+ // A fresh identity next time: whatever was refused is not offered again.
+ identity = Identity::new();
+ }
+ let (wait, announce) = pace.failed(Kind::from(&failure), lasted, Instant::now());
+ if announce {
+ quiet!(
+ "push: live channel down ({failure}); polling for changes, next try in {}s",
+ wait.as_secs()
+ );
+ }
+ let until = Instant::now() + wait;
+ while Instant::now() < until {
+ let woke = sleep_or_wake(until - Instant::now(), &mut woken).await;
+ if woke && pace.wake_may_retry() {
+ break;
+ }
+ }
+ }
+}
+
+/// Connect, get a token and register it.
+async fn open(
+ http: &reqwest::Client,
+ identity: &mut Identity,
+ containers: &[&str],
+ dsid: &str,
+) -> Result<Courier, Failure> {
+ let mut channel = Courier::connect(courier::SERVER, identity, containers).await?;
+ if let Err(f) = channel
+ .register(http, courier::REGISTRY, identity, dsid)
+ .await
+ {
+ channel.close().await;
+ return Err(f);
+ }
+ Ok(channel)
+}
+
+/// Pass pushes on until the channel is lost (`Some`) or its token is due to be renewed
+/// (`None`); renew the registration on the way.
+async fn run(
+ channel: &mut Courier,
+ http: &reqwest::Client,
+ identity: &Identity,
+ dsid: &str,
+ tx: &mpsc::UnboundedSender<&'static str>,
+ opened: Instant,
+) -> Option<Failure> {
+ let mut registered = Instant::now();
+ loop {
+ if opened.elapsed() >= TOKEN_LIFE {
+ return None;
+ }
+ if registered.elapsed() >= RENEW_REGISTRATION {
+ if let Err(f) = channel
+ .register(http, courier::REGISTRY, identity, dsid)
+ .await
+ {
+ return Some(f);
+ }
+ registered = Instant::now();
+ }
+ let until_renewal = RENEW_REGISTRATION.saturating_sub(registered.elapsed());
+ match channel
+ .next(until_renewal.min(Duration::from_secs(10 * 60)))
+ .await
+ {
+ Ok(Some(courier::Event::Changed(container))) => {
+ if let Some(service) = service_of(&container) {
+ quiet!("push: {service} changed (live)");
+ tx.send(service).ok();
}
- };
- backoff = Duration::from_secs(1);
- // Whatever changed while no connection was parked was never pushed: one pass catches
- // it up. Not at launch, which runs a full pass of its own.
- if !first {
- for (_, service) in CONTAINERS {
- tx.send(service).ok();
}
+ Ok(Some(courier::Event::Other) | None) => {}
+ Err(f) => return Some(f),
}
- first = false;
- let opened = Instant::now();
- let mut failures = 0;
- while opened.elapsed() < TOKEN_LIFE {
- match quince_icloud::push::wait(&http, &channel, LONGEST_WAIT).await {
- Ok(Some(container)) => {
- failures = 0;
- if let Some(service) = service_of(&container) {
+ }
+}
+
+// --- Polling, while there is no live channel ---------------------------------------------------
+
+/// How often the containers are asked whether anything changed while no live channel is up:
+/// often with a window in focus, less with one merely open, rarely from the tray.
+/// On the battery, what no one is looking at is asked half as often (power.rs).
+fn poll_every(presence: Presence) -> Duration {
+ let every = match presence {
+ Presence::Focused => Duration::from_secs(5),
+ Presence::Open => Duration::from_secs(15),
+ Presence::Hidden => Duration::from_secs(60),
+ };
+ crate::power::pace(every, presence == Presence::Focused)
+}
+
+/// How often a window on screen checks anyway while the live channel is up.
+const SAFETY_CHECK: Duration = Duration::from_secs(2 * 60);
+
+/// While the live channel is down, ask each container's database whether it moved, and
+/// refresh only the ones that did. The tokens are seeded once at the start, so a channel lost
+/// hours later is still compared with a known point.
+async fn poll_cloudkit(
+ app: tauri::AppHandle,
+ client: Arc<Mutex<Client>>,
+ tx: mpsc::UnboundedSender<&'static str>,
+) {
+ let mut tokens: Vec<Option<String>> = vec![None; CONTAINERS.len()];
+ let mut seeded = false;
+ let mut woken = WAKE.subscribe();
+ let mut backoff: Option<Duration> = None;
+ loop {
+ let live = LIVE.load(Ordering::SeqCst);
+ let catch_up = CATCH_UP.swap(false, Ordering::SeqCst);
+ if seeded && live && !catch_up {
+ // The channel carries it; woken when that changes. A window on screen still gets
+ // a check every couple of minutes, in case a push went astray.
+ let woke = sleep_or_wake(SAFETY_CHECK, &mut woken).await;
+ if woke || !LIVE.load(Ordering::SeqCst) || presence(&app) == Presence::Hidden {
+ continue;
+ }
+ }
+ let session = {
+ let guard = client.lock().await;
+ let s = guard.session();
+ s.webservices
+ .is_some()
+ .then(|| s.service_url("ckdatabasews"))
+ .flatten()
+ .map(|root| (guard.http().clone(), guard.service_params(), root))
+ };
+ let Some((http, params, root)) = session else {
+ sleep_or_wake(Duration::from_secs(30), &mut woken).await;
+ continue;
+ };
+ let mut failed = None;
+ for (i, (container, service)) in CONTAINERS.iter().enumerate() {
+ match quince_icloud::push::database_changed(
+ &http,
+ &root,
+ &params,
+ container,
+ tokens[i].as_deref(),
+ )
+ .await
+ {
+ Ok((moved, next)) => {
+ tokens[i] = next;
+ if moved {
+ if live && !catch_up {
+ quiet!("push: {service} changed (poll; the live channel missed it)");
+ } else {
+ quiet!("push: {service} changed (poll)");
+ }
tx.send(service).ok();
}
}
- Ok(None) => failures = 0,
- Err(e) => {
- failures += 1;
- quiet!("push: the wait failed ({failures}): {e}");
- if failures >= 3 {
- // Three in a row is a channel gone bad, not a blip: make a new one.
- break;
- }
- tokio::time::sleep(backoff * failures).await;
+ Err(quince_icloud::Error::StaleCursor) => {
+ // Start over, and refresh in case something moved meanwhile.
+ tokens[i] = None;
+ tx.send(service).ok();
}
+ Err(e) => failed = Some(e),
}
}
+ seeded = true;
+ backoff = match failed {
+ None => None,
+ Some(e) => {
+ let next = backoff.map_or(Duration::from_secs(5), |b| {
+ (b * 2).min(Duration::from_secs(5 * 60))
+ });
+ if backoff.is_none() {
+ quiet!(
+ "push: change check failed ({e}); trying again in {}s",
+ next.as_secs()
+ );
+ }
+ Some(next)
+ }
+ };
+ let wait = backoff.unwrap_or_else(|| poll_every(presence(&app)));
+ sleep_or_wake(wait, &mut woken).await;
}
}
@@ -282,4 +623,99 @@ mod tests {
assert_eq!(service_of("com.apple.photos.cloud"), Some("photos"));
assert_eq!(service_of("com.apple.clouddocs"), None);
}
+
+ #[test]
+ fn a_passing_failure_backs_off_doubling_to_five_minutes() {
+ let mut pace = Pace::default();
+ let t = Instant::now();
+ let waits: Vec<u64> = (0..12)
+ .map(|_| pace.failed(Kind::Transient, None, t).0.as_secs())
+ .collect();
+ assert_eq!(&waits[..5], &[1, 2, 4, 8, 16]);
+ assert_eq!(*waits.last().unwrap(), 300, "capped at five minutes");
+ assert!(pace.wake_may_retry(), "network back retries at once");
+ }
+
+ #[test]
+ fn a_refusal_is_never_retried_in_a_tight_loop() {
+ // What Apple now answers the old endpoint: 403, "This endpoint is deprecated."
+ let mut pace = Pace::default();
+ let t = Instant::now();
+ let (first, _) = pace.failed(Kind::Refused, None, t);
+ assert!(first >= Duration::from_secs(30 * 60), "{first:?}");
+ let (second, _) = pace.failed(Kind::Refused, None, t);
+ assert!(second > first);
+ for _ in 0..20 {
+ pace.failed(Kind::Refused, None, t);
+ }
+ assert_eq!(pace.delay(), Duration::from_secs(6 * 60 * 60));
+ assert!(
+ !pace.wake_may_retry(),
+ "not even focus or the network cuts it short"
+ );
+ // A rate limit is honoured whatever the count.
+ let mut pace = Pace::default();
+ let (wait, _) = pace.failed(Kind::Limited(Duration::from_secs(900)), None, t);
+ assert_eq!(wait, Duration::from_secs(900));
+ assert!(!pace.wake_may_retry());
+ }
+
+ #[test]
+ fn a_channel_that_drops_at_once_still_backs_off() {
+ let mut pace = Pace::default();
+ let t = Instant::now();
+ let mut last = Duration::ZERO;
+ for _ in 0..6 {
+ pace.up(t);
+ let (wait, _) = pace.failed(Kind::Transient, Some(Duration::from_secs(2)), t);
+ assert!(wait >= last, "never shorter while it keeps dropping");
+ last = wait;
+ }
+ assert!(last >= Duration::from_secs(32));
+ // One that stayed up a while starts over.
+ pace.up(t);
+ let (wait, _) = pace.failed(Kind::Transient, Some(STABLE), t);
+ assert_eq!(wait, Duration::from_secs(1));
+ }
+
+ #[test]
+ fn the_log_hears_one_line_down_and_one_line_back() {
+ let mut pace = Pace::default();
+ let t0 = Instant::now();
+ let said: Vec<bool> = (0..5)
+ .map(|_| pace.failed(Kind::Transient, None, t0).1)
+ .collect();
+ assert_eq!(said, [true, false, false, false, false]);
+ let back = pace.up(t0 + Duration::from_secs(40));
+ assert_eq!(back, Some(Duration::from_secs(40)));
+ assert_eq!(pace.up(t0 + Duration::from_secs(50)), None, "said once");
+ let (_, said) = pace.failed(Kind::Transient, Some(Duration::from_secs(600)), t0);
+ assert!(said, "a new outage is a new line");
+ }
+
+ #[test]
+ fn polling_is_quickest_with_focus_and_slowest_from_the_tray() {
+ let (f, o, h) = (
+ poll_every(Presence::Focused),
+ poll_every(Presence::Open),
+ poll_every(Presence::Hidden),
+ );
+ assert!(f <= Duration::from_secs(5), "changes show within seconds");
+ assert!(f < o && o < h);
+ assert!(h <= Duration::from_secs(60));
+ }
+
+ #[test]
+ fn calendar_and_contacts_are_asked_often_only_while_looked_at() {
+ let (f, o, h) = (
+ look_every(Presence::Focused),
+ look_every(Presence::Open),
+ look_every(Presence::Hidden),
+ );
+ assert!(f <= Duration::from_secs(5), "changes show within seconds");
+ // A window merely open — behind another, on another workspace — is not asked at the
+ // focused pace: at most four requests a minute for the two of them, not thirty.
+ assert!(o >= Duration::from_secs(15), "{o:?}");
+ assert!(o < h && h <= Duration::from_secs(120));
+ }
}
diff --git a/src-tauri/src/reminders_cmds.rs b/src-tauri/src/reminders_cmds.rs
index 3aa7944..2807328 100644
--- a/src-tauri/src/reminders_cmds.rs
+++ b/src-tauri/src/reminders_cmds.rs
@@ -1,12 +1,13 @@
//! Reminders commands for what sits beside a reminder: tags, its link, an early alert, custom
//! smart lists, and sections. Reads come from the library; writes go to Apple (each refused
-//! there while `REMINDER_DETAIL_WRITES` is off) and the library is read again after.
+//! there whenever `REMINDER_DETAIL_WRITES` is off) and the library is read again after.
use crate::{Auth, Data, UiResult};
use quince_core::reminders::{
- Reminder, ReminderDetail, ReminderSection, ReminderSmartList, SmartListContents, TagCount,
+ Reminder, ReminderDetail, ReminderMarks, ReminderMore, ReminderSection, ReminderSmartList,
+ SmartListContents, TagCount,
};
-use quince_icloud::reminders::details;
+use quince_icloud::reminders::{details, more};
use tauri::State;
fn now() -> i64 {
@@ -22,6 +23,147 @@ pub async fn reminder_detail(guid: String, data: State<'_, Data>) -> UiResult<Re
library.reminder_detail(&guid).map_err(|e| e.to_string())
}
+/// The rest of one reminder's Details: its repeat whole, time zone, a place, the person it
+/// comes up for when messaging — from the library — and Urgent, which lives in a small file
+/// read from Apple the first time it is asked for (read only; offline it stays unknown).
+#[tauri::command]
+pub async fn reminder_more(
+ guid: String,
+ auth: State<'_, Auth>,
+ data: State<'_, Data>,
+) -> UiResult<ReminderMore> {
+ let (mut more, urgent_unread) = {
+ let library = data.0.lock().await;
+ let reminder = library.reminder(&guid).map_err(|e| e.to_string())?;
+ // The record as Apple sent it; the reminder as read for the window leaves it out.
+ let raw = library.reminder_raw(&guid).map_err(|e| e.to_string())?;
+ let raw = raw.as_deref();
+ let parts = library.reminder_parts(&guid).map_err(|e| e.to_string())?;
+ let mut more = more::more_from(
+ &guid,
+ raw,
+ reminder.as_ref().and_then(|r| r.timezone.as_deref()),
+ &parts,
+ );
+ if let Some(person) = more.messaging.as_mut() {
+ person.name = library
+ .contact_name_for(&person.handles)
+ .map_err(|e| e.to_string())?;
+ }
+ more.urgent = more::urgent_known(raw);
+ let unread = more.urgent.is_none() && raw.is_some();
+ (more, unread)
+ };
+ if urgent_unread {
+ if let Ok((http, root, params)) = crate::cloudkit_context(&auth).await {
+ more.urgent = more::urgent_cloudkit(&http, &root, params, &guid)
+ .await
+ .ok()
+ .flatten();
+ }
+ }
+ Ok(more)
+}
+
+/// Reminders whose tick now is the last of their repeat (End Repeat On Date): ticked, each is
+/// completed rather than moved on, so the window shows it done as it does a one-off.
+#[tauri::command]
+pub async fn reminders_ending(data: State<'_, Data>) -> UiResult<Vec<String>> {
+ let library = data.0.lock().await;
+ let at = now();
+ let mut out = Vec::new();
+ for (guid, end) in library.reminder_repeat_ends().map_err(|e| e.to_string())? {
+ if let Some(r) = library.reminder(&guid).map_err(|e| e.to_string())? {
+ let days = library
+ .reminder_repeat_days(&guid)
+ .map_err(|e| e.to_string())?;
+ if r.tick_ends_series_on(Some(end), &days, at) {
+ out.push(guid);
+ }
+ }
+ }
+ Ok(out)
+}
+
+/// What each of these reminders' rows shows beside its date, as the phone's list does:
+/// Weekdays or Weekends, the Urgent alarm, a place, a person, a link. Only rows with any of
+/// them come back. Urgent is read from Apple for rows not read yet — a few at a time, read
+/// only — and is shown off until it is known.
+#[tauri::command]
+pub async fn reminder_marks(
+ guids: Vec<String>,
+ auth: State<'_, Auth>,
+ data: State<'_, Data>,
+) -> UiResult<Vec<ReminderMarks>> {
+ /// Urgent files read in one call at most; the rest are read on the next.
+ const MOST_UNREAD: usize = 40;
+ let mut out = Vec::new();
+ let mut unread: Vec<(usize, String, String)> = Vec::new();
+ {
+ let library = data.0.lock().await;
+ for guid in guids.iter().take(2_000) {
+ let raw = library.reminder_raw(guid).map_err(|e| e.to_string())?;
+ let parts = library.reminder_parts(guid).map_err(|e| e.to_string())?;
+ let found = more::more_from(guid, raw.as_deref(), None, &parts);
+ let messaging = match found.messaging {
+ Some(person) => library
+ .contact_name_for(&person.handles)
+ .map_err(|e| e.to_string())?
+ .or_else(|| person.handles.first().cloned()),
+ None => None,
+ };
+ let url = library
+ .reminder_detail(guid)
+ .map_err(|e| e.to_string())?
+ .url;
+ let urgent = more::urgent_known(raw.as_deref());
+ let marks = ReminderMarks {
+ guid: guid.clone(),
+ days_of_week: found.repeat.map(|r| r.days_of_week).unwrap_or_default(),
+ urgent: urgent.unwrap_or(false),
+ location: found.location,
+ messaging,
+ url,
+ };
+ if urgent.is_none() && unread.len() < MOST_UNREAD {
+ if let Some(raw) = raw {
+ unread.push((out.len(), guid.clone(), raw));
+ }
+ }
+ out.push(marks);
+ }
+ }
+ if !unread.is_empty() {
+ if let Ok((http, root, params)) = crate::cloudkit_context(&auth).await {
+ use futures_util::StreamExt;
+ let read: Vec<(usize, Option<bool>)> = futures_util::stream::iter(unread)
+ .map(|(at, guid, raw)| {
+ let (http, root, params) = (http.clone(), root.clone(), params.clone());
+ async move {
+ (
+ at,
+ more::urgent_for(&http, &root, params, &guid, &raw).await,
+ )
+ }
+ })
+ .buffer_unordered(6)
+ .collect()
+ .await;
+ for (at, urgent) in read {
+ out[at].urgent = urgent.unwrap_or(false);
+ }
+ }
+ }
+ out.retain(|m| {
+ m.urgent
+ || !m.days_of_week.is_empty()
+ || m.location.is_some()
+ || m.messaging.is_some()
+ || m.url.is_some()
+ });
+ Ok(out)
+}
+
/// Every tag on the account, with how many reminders still to do carry each.
#[tauri::command]
pub async fn reminder_tags(data: State<'_, Data>) -> UiResult<Vec<TagCount>> {
diff --git a/src-tauri/src/search_provider.rs b/src-tauri/src/search_provider.rs
index 6ebebfc..5e83059 100644
--- a/src-tauri/src/search_provider.rs
+++ b/src-tauri/src/search_provider.rs
@@ -550,8 +550,9 @@ fn open_app(app: &AppHandle, reveal: Reveal) {
/// The library window, asked to search for `query`.
fn search_in_window(app: &AppHandle, query: String) {
- crate::show_window(app);
- app.emit_to("main", SEARCH, query).ok();
+ crate::show_window_then(app, move |app| {
+ app.emit_to("main", SEARCH, query).ok();
+ });
}
/// Takes Skykeep's place in the desktop's search, for as long as it runs. Nothing is lost if
diff --git a/src-tauri/src/settings.rs b/src-tauri/src/settings.rs
index b87e694..523a285 100644
--- a/src-tauri/src/settings.rs
+++ b/src-tauri/src/settings.rs
@@ -157,11 +157,12 @@ pub fn measure(dir: &Path) -> LocalStorage {
}
}
-/// Remove the cached pictures under `dir`, answering how the folder is used after. Files only:
-/// the folders stay, so a picture being saved this moment never finds its folder gone.
-pub fn clear(dir: &Path) -> LocalStorage {
+/// Remove the cached pictures under `dir` through `remove` (which may decline a file in use),
+/// answering how the folder is used after. Files only: the folders stay, so a picture being
+/// saved this moment never finds its folder gone.
+pub fn clear(dir: &Path, remove: &dyn Fn(&Path)) -> LocalStorage {
for f in clearable_files(dir) {
- let _ = std::fs::remove_file(f);
+ remove(&f);
}
measure(dir)
}
@@ -176,12 +177,30 @@ pub async fn local_storage(app: tauri::AppHandle) -> Result<LocalStorage, String
}
/// Let go of the pictures Apple still has (see `CLEARABLE`); answers how the copy is used now.
+/// A photo being read this moment, or waiting to be uploaded, stays (see `photo_cache`).
#[tauri::command]
pub async fn local_storage_clear(app: tauri::AppHandle) -> Result<LocalStorage, String> {
let dir = crate::state_dir(&app);
- tauri::async_runtime::spawn_blocking(move || clear(&dir))
- .await
- .map_err(|e| e.to_string())
+ let waiting: Vec<PathBuf> = {
+ use tauri::Manager;
+ app.state::<crate::Data>()
+ .0
+ .lock()
+ .await
+ .unfinished_uploads()
+ .map_err(|e| e.to_string())?
+ .into_iter()
+ .map(|u| PathBuf::from(u.path))
+ .collect()
+ };
+ tauri::async_runtime::spawn_blocking(move || {
+ let protected = crate::photo_cache::identities(&waiting);
+ clear(&dir, &|f| {
+ crate::photo_cache::remove_unless_in_use(f, &protected);
+ })
+ })
+ .await
+ .map_err(|e| e.to_string())
}
/// Whether this desktop shows alerts: on Linux an alert is shown by a notification service,
@@ -252,7 +271,9 @@ mod tests {
let t = folder();
let d = t.path();
let before = measure(d);
- let after = clear(d);
+ let after = clear(d, &|f| {
+ let _ = std::fs::remove_file(f);
+ });
for kept in [
"library.db",
"library.db-wal",
@@ -300,7 +321,9 @@ mod tests {
let linked = measure(d);
assert_eq!(linked.total, before.total);
assert_eq!(linked.clearable, before.clearable);
- clear(d);
+ clear(d, &|f| {
+ let _ = std::fs::remove_file(f);
+ });
assert!(!d.join("photos/open/V/Clip.mov").exists());
}
@@ -309,6 +332,9 @@ mod tests {
let t = tempfile::tempdir().unwrap();
assert_eq!(measure(t.path()), LocalStorage::default());
assert_eq!(measure(&t.path().join("none")), LocalStorage::default());
- assert_eq!(clear(&t.path().join("none")), LocalStorage::default());
+ assert_eq!(
+ clear(&t.path().join("none"), &|_| {}),
+ LocalStorage::default()
+ );
}
}
diff --git a/src-tauri/src/timing.rs b/src-tauri/src/timing.rs
new file mode 100644
index 0000000..522d58f
--- /dev/null
+++ b/src-tauri/src/timing.rs
@@ -0,0 +1,34 @@
+//! How quickly Skykeep opens, measured: with `SKYKEEP_TIMING=1` each step of a launch, of an
+//! app's window and of an opened file is printed to stderr — milliseconds since the process
+//! started, and the wall clock, to line up with the launcher's own. Silent otherwise.
+
+use std::sync::OnceLock;
+use std::time::{Instant, SystemTime, UNIX_EPOCH};
+
+static START: OnceLock<Instant> = OnceLock::new();
+
+fn on() -> bool {
+ static ON: OnceLock<bool> = OnceLock::new();
+ *ON.get_or_init(|| std::env::var_os("SKYKEEP_TIMING").is_some_and(|v| !v.is_empty()))
+}
+
+/// The process's start, as near as `main` can say it.
+pub fn start() {
+ START.get_or_init(Instant::now);
+}
+
+/// One step, printed when timing is asked for.
+pub fn mark(what: impl std::fmt::Display) {
+ if !on() {
+ return;
+ }
+ let since = START.get_or_init(Instant::now).elapsed();
+ let wall = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_millis())
+ .unwrap_or_default();
+ eprintln!(
+ "skykeep-timing {wall} +{:.1}ms {what}",
+ since.as_secs_f64() * 1000.0
+ );
+}
diff --git a/src-tauri/src/video.rs b/src-tauri/src/video.rs
index 411f703..c8ec3c6 100644
--- a/src-tauri/src/video.rs
+++ b/src-tauri/src/video.rs
@@ -27,6 +27,74 @@ pub fn video_base() -> Option<String> {
BASE.get().cloned()
}
+/// What the window's player can decode on this computer, so a video it cannot play says why
+/// rather than standing black: the GStreamer pieces WebKitGTK plays through, by the package that
+/// brings each. `missing` lists those packages; empty when everything is there (and always
+/// elsewhere than Linux, where the webview brings its own decoders).
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct VideoSupport {
+ pub h264: bool,
+ pub hevc: bool,
+ pub missing: Vec<&'static str>,
+}
+
+#[tauri::command]
+pub fn video_support() -> VideoSupport {
+ support()
+}
+
+#[cfg(target_os = "linux")]
+fn support() -> VideoSupport {
+ use gstreamer as gst;
+ if gst::init().is_err() {
+ return VideoSupport {
+ h264: false,
+ hevc: false,
+ missing: vec!["gstreamer"],
+ };
+ }
+ let any = |names: &[&str]| names.iter().any(|n| gst::ElementFactory::find(n).is_some());
+ let h264 = any(&[
+ "avdec_h264",
+ "vah264dec",
+ "vaapih264dec",
+ "openh264dec",
+ "nvh264dec",
+ "v4l2slh264dec",
+ ]);
+ let hevc = any(&[
+ "avdec_h265",
+ "vah265dec",
+ "vaapih265dec",
+ "nvh265dec",
+ "v4l2slh265dec",
+ ]);
+ let mut missing = Vec::new();
+ if !any(&["playbin3", "videoconvert"]) {
+ missing.push("gst-plugins-base");
+ }
+ if !any(&["qtdemux"]) {
+ missing.push("gst-plugins-good");
+ }
+ if !h264 || !hevc {
+ missing.push("gst-libav");
+ }
+ VideoSupport {
+ h264,
+ hevc,
+ missing,
+ }
+}
+
+#[cfg(not(target_os = "linux"))]
+fn support() -> VideoSupport {
+ VideoSupport {
+ h264: true,
+ hevc: true,
+ missing: Vec::new(),
+ }
+}
+
/// Listens on the loopback interface for as long as the app runs.
pub fn serve(app: AppHandle) {
tauri::async_runtime::spawn(async move {
@@ -498,6 +566,15 @@ mod tests {
)
}
+ /// This computer's decoders, as the window is told them: H.264 at least wherever the
+ /// player can play anything, and a package named for each piece that is missing.
+ #[test]
+ fn says_what_it_can_decode() {
+ let s = support();
+ assert_eq!(s.missing.contains(&"gst-libav"), !(s.h264 && s.hevc));
+ println!("{s:?}");
+ }
+
#[test]
fn only_our_secret_and_only_videos() {
let ok = ask(&["GET /s3cret/abc-1/original HTTP/1.1", "Range: bytes=0-"]);
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index 15085de..c1ab6dc 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -10,6 +10,8 @@
"app": {
"windows": [
{
+ "label": "main",
+ "create": false,
"title": "Skykeep",
"width": 1040,
"height": 720,
@@ -30,7 +32,10 @@
"active": true,
"targets": "all",
"icon": [
+ "icons/16x16.png",
+ "icons/24x24.png",
"icons/32x32.png",
+ "icons/48x48.png",
"icons/64x64.png",
"icons/128x128.png",
@@ -92,17 +97,26 @@
"/usr/share/applications/io.github.yashwanthkamireddi.Skykeep.Photos.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Skykeep.Photos.desktop",
"/usr/share/gnome-shell/search-providers/io.github.yashwanthkamireddi.Skykeep.search-provider.ini": "../packaging/io.github.yashwanthkamireddi.Skykeep.search-provider.ini",
"/usr/share/dbus-1/services/io.github.yashwanthkamireddi.Skykeep.SearchProvider.service": "../packaging/io.github.yashwanthkamireddi.Skykeep.SearchProvider.service",
- "/usr/share/krunner/dbusplugins/io.github.yashwanthkamireddi.Skykeep.krunner.desktop": "../packaging/io.github.yashwanthkamireddi.Skykeep.krunner.desktop"
+ "/usr/share/krunner/dbusplugins/io.github.yashwanthkamireddi.Skykeep.krunner.desktop": "../packaging/io.github.yashwanthkamireddi.Skykeep.krunner.desktop",
+ "/usr/share/icons/hicolor/16x16/apps/io.github.yashwanthkamireddi.Skykeep.png": "icons/16x16.png",
+ "/usr/share/icons/hicolor/24x24/apps/io.github.yashwanthkamireddi.Skykeep.png": "icons/24x24.png",
+ "/usr/share/icons/hicolor/32x32/apps/io.github.yashwanthkamireddi.Skykeep.png": "icons/32x32.png",
+ "/usr/share/icons/hicolor/48x48/apps/io.github.yashwanthkamireddi.Skykeep.png": "icons/48x48.png",
+ "/usr/share/icons/hicolor/64x64/apps/io.github.yashwanthkamireddi.Skykeep.png": "icons/64x64.png",
+ "/usr/share/icons/hicolor/128x128/apps/io.github.yashwanthkamireddi.Skykeep.png": "icons/128x128.png",
+ "/usr/share/icons/hicolor/256x256/apps/io.github.yashwanthkamireddi.Skykeep.png": "icons/[email protected]",
+ "/usr/share/icons/hicolor/512x512/apps/io.github.yashwanthkamireddi.Skykeep.png": "icons/icon.png"
}
},
"rpm": {
"depends": [
- "libsecret",
- "libheif",
- "gstreamer1",
- "gstreamer1-plugins-base",
- "gstreamer1-plugins-good",
- "gstreamer1-plugin-libav"
+ "libsecret-1.so.0()(64bit)",
+ "libheif.so.1()(64bit)",
+ "libgstreamer-1.0.so.0()(64bit)",
+ "(gstreamer1-plugins-base or gstreamer-plugins-base)",
+ "(gstreamer1-plugins-good or gstreamer-plugins-good)",
+ "(gstreamer1-plugin-libav or gstreamer-plugins-libav)",
+ "(gstreamer1-plugin-openh264 or gstreamer-plugin-openh264)"
],
"desktopTemplate": "../packaging/io.github.yashwanthkamireddi.Skykeep.desktop.in",
"files": {
@@ -115,7 +129,15 @@
"/usr/share/applications/io.github.yashwanthkamireddi.Skykeep.Photos.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Skykeep.Photos.desktop",
"/usr/share/gnome-shell/search-providers/io.github.yashwanthkamireddi.Skykeep.search-provider.ini": "../packaging/io.github.yashwanthkamireddi.Skykeep.search-provider.ini",
"/usr/share/dbus-1/services/io.github.yashwanthkamireddi.Skykeep.SearchProvider.service": "../packaging/io.github.yashwanthkamireddi.Skykeep.SearchProvider.service",
- "/usr/share/krunner/dbusplugins/io.github.yashwanthkamireddi.Skykeep.krunner.desktop": "../packaging/io.github.yashwanthkamireddi.Skykeep.krunner.desktop"
+ "/usr/share/krunner/dbusplugins/io.github.yashwanthkamireddi.Skykeep.krunner.desktop": "../packaging/io.github.yashwanthkamireddi.Skykeep.krunner.desktop",
+ "/usr/share/icons/hicolor/16x16/apps/io.github.yashwanthkamireddi.Skykeep.png": "icons/16x16.png",
+ "/usr/share/icons/hicolor/24x24/apps/io.github.yashwanthkamireddi.Skykeep.png": "icons/24x24.png",
+ "/usr/share/icons/hicolor/32x32/apps/io.github.yashwanthkamireddi.Skykeep.png": "icons/32x32.png",
+ "/usr/share/icons/hicolor/48x48/apps/io.github.yashwanthkamireddi.Skykeep.png": "icons/48x48.png",
+ "/usr/share/icons/hicolor/64x64/apps/io.github.yashwanthkamireddi.Skykeep.png": "icons/64x64.png",
+ "/usr/share/icons/hicolor/128x128/apps/io.github.yashwanthkamireddi.Skykeep.png": "icons/128x128.png",
+ "/usr/share/icons/hicolor/256x256/apps/io.github.yashwanthkamireddi.Skykeep.png": "icons/[email protected]",
+ "/usr/share/icons/hicolor/512x512/apps/io.github.yashwanthkamireddi.Skykeep.png": "icons/icon.png"
}
},
"appimage": {
diff --git a/src/App.tsx b/src/App.tsx
index e8cf327..c709507 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -12,19 +12,17 @@ type Phase = "checking" | "signin" | "code" | "library";
export default function App() {
const [phase, setPhase] = useState<Phase>("checking");
- // The window is shown once the first real screen (the library, or sign-in) has been drawn:
- // never the session check before it, never a half-drawn frame (see window_ready, main.rs).
+ // The window is shown once the first real screen (the library, or sign-in) is in the page:
+ // never the session check before it (see window_ready, main.rs). Said as soon as React has
+ // put it there, not after an animation frame: the window is hidden until then, and a hidden
+ // WebKitGTK window draws no frames, so waiting on one left every launch to the three-second
+ // fallback. The page is laid out by now and the window paints it as it maps.
const [shown, setShown] = useState(false);
useEffect(() => {
if (shown || phase === "checking") return;
setShown(true);
- requestAnimationFrame(() =>
- requestAnimationFrame(() => {
- // Started at login, the window stays in the tray unless the person is needed here.
- invoke("window_ready", { needsYou: phase !== "library" })
- .catch(() => {});
- }),
- );
+ // Started at login, the window stays in the tray unless the person is needed here.
+ invoke("window_ready", { needsYou: phase !== "library" }).catch(() => {});
}, [phase, shown]);
// On launch, try the stored session before showing anything. This is the whole promise:
@@ -37,6 +35,21 @@ export default function App() {
// Always resume rather than trusting stored metadata. Apple's service endpoints
// authenticate by cookie, and holding a token is not the same as being able to call
// them — resuming is what establishes the cookies that make the session usable.
+ if (status.hasStoredSession && status.libraryReady) {
+ // The library is this session's account's already: it opens at once on what it
+ // holds, and the session is taken up behind it — a round trip to Apple (seconds on
+ // a slow network) is never what stands between a launch and the window. The first
+ // refresh waits on it in the engine. Apple wanting a code shows the code screen;
+ // a session it will not take back leaves the library readable with the sign-in
+ // line over it, as a lapse does.
+ const resumed = api.resume();
+ setPhase("library");
+ const next = await resumed.catch(() => "signin" as const);
+ if (cancelled) return;
+ if (next === "code") setPhase("code");
+ else if (next === "signin") setLapsed(true);
+ return;
+ }
if (status.hasStoredSession) {
const next = await api.resume();
if (next !== "signin") return !cancelled && setPhase(next);
diff --git a/src/assets/skykeep-mark.png b/src/assets/skykeep-mark.png
index fbdecff..1fe0b18 100644
Binary files a/src/assets/skykeep-mark.png and b/src/assets/skykeep-mark.png differ
diff --git a/src/components/ImportSheet.tsx b/src/components/ImportSheet.tsx
index 367dc38..850d66b 100644
--- a/src/components/ImportSheet.tsx
+++ b/src/components/ImportSheet.tsx
@@ -14,12 +14,17 @@ import "../styles/intake.css";
* Mounted once per window; it shows the files that arrived for this window, one at a time.
*/
export function ImportSheet() {
- const [queue, setQueue] = useState<Arrival[]>([]);
+ // Each file with an id of its own, given as it arrives: the sheet is keyed on it and put
+ // away by it. Keyed on the queue's length, a second file arriving mid-import remade the
+ // sheet with Add live again (the events added twice); put away as "the first", a finished
+ // import whose sheet had already gone dropped the next file unseen.
+ const [queue, setQueue] = useState<{ id: number; arrival: Arrival }[]>([]);
+ const nextId = useRef(0);
const collect = useCallback(() => {
intakeApi
.pending()
- .then((more) => more.length && setQueue((q) => [...q, ...more]))
+ .then((more) => more.length && setQueue((q) => [...q, ...more.map((arrival) => ({ id: nextId.current++, arrival }))]))
.catch(() => {});
}, []);
@@ -31,15 +36,16 @@ export function ImportSheet() {
};
}, [collect]);
- const current = queue[0];
- if (!current) return null;
- const done = () => setQueue((q) => q.slice(1));
+ const head = queue[0];
+ if (!head) return null;
+ const current = head.arrival;
+ const done = () => setQueue((q) => q.filter((x) => x.id !== head.id));
return createPortal(
<div className="modal-veil ix-veil">
{current.kind === "events" ? (
- <EventsSheet key={current.file + queue.length} arrival={current} onDone={done} />
+ <EventsSheet key={head.id} arrival={current} onDone={done} />
) : current.kind === "contacts" ? (
- <ContactsSheet key={current.file + queue.length} arrival={current} onDone={done} />
+ <ContactsSheet key={head.id} arrival={current} onDone={done} />
) : (
<Shell label={`Can’t open “${current.file}”`} onCancel={done}>
<h2>Can’t open “{current.file}”</h2>
@@ -177,7 +183,8 @@ function EventsSheet({ arrival, onDone }: { arrival: Extract<Arrival, { kind: "e
const options = (calendars ?? []).map((c) => ({ value: c.guid, label: c.title }));
return (
- <Shell label={`Import “${arrival.file}”`} onCancel={onDone}>
+ // Not put away mid-import: the import finishing would then put away the next file.
+ <Shell label={`Import “${arrival.file}”`} onCancel={busy ? () => {} : onDone}>
<div className="ix-head">
<h2>{heading}</h2>
{fresh.length > 0 && calendars && calendars.length > 0 && (
@@ -258,7 +265,7 @@ function ContactsSheet({ arrival, onDone }: { arrival: Extract<Arrival, { kind:
}
return (
- <Shell label={`Import “${arrival.file}”`} onCancel={onDone}>
+ <Shell label={`Import “${arrival.file}”`} onCancel={busy ? () => {} : onDone}>
<h2>{heading}</h2>
<p className="ix-file">{arrival.file}</p>
<ul className="ix-list" aria-label="Contacts in this file">
diff --git a/src/components/Picker.tsx b/src/components/Picker.tsx
index 12bcaf4..7fbaba7 100644
--- a/src/components/Picker.tsx
+++ b/src/components/Picker.tsx
@@ -2,7 +2,9 @@ import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState } from
import { Portal } from "./Portal";
import { useTypeSelect } from "./RowMenu";
-export type PickerOption = { value: string; label: string };
+/** `divider` draws a rule above the choice, setting it apart from the ones before it;
+ * `disabled` shows a choice greyed, as a Mac menu shows one that cannot be taken here. */
+export type PickerOption = { value: string; label: string; divider?: boolean; disabled?: boolean };
/**
* A pop-up button, in the shape macOS actually uses.
@@ -112,6 +114,7 @@ export function Picker({
const choose = useCallback(
(index: number) => {
const option = options[index];
+ if (option?.disabled) return;
if (option) onChange(option.value);
close(true);
},
@@ -199,7 +202,13 @@ export function Picker({
setLit(true);
return;
}
- setActive((at) => Math.max(0, Math.min(to(at), options.length - 1)));
+ setActive((at) => {
+ let next = Math.max(0, Math.min(to(at), options.length - 1));
+ // A greyed choice is passed over, in the direction the key went.
+ const step = next >= at ? 1 : -1;
+ while (options[next]?.disabled && next + step >= 0 && next + step < options.length) next += step;
+ return options[next]?.disabled ? at : next;
+ });
};
// Typing goes to the choice that begins with it, as a Mac pop-up's menu does.
const typedTo = typeSelect(e, litNow.current ? active : -1);
@@ -274,8 +283,9 @@ export function Picker({
}}
role="option"
aria-selected={option.value === value}
+ aria-disabled={option.disabled || undefined}
tabIndex={index === active ? 0 : -1}
- className={lit && index === active ? "is-active" : undefined}
+ className={[lit && index === active ? "is-active" : "", option.divider ? "has-divider" : "", option.disabled ? "is-disabled" : ""].join(" ").trim() || undefined}
onKeyDown={onListKey}
onClick={() => choose(index)}
// The pointer highlights a row only once it moves. The menu opens over the
@@ -286,7 +296,7 @@ export function Picker({
if (at && at.x === e.clientX && at.y === e.clientY) return;
const first = at === null;
pointer.current = { x: e.clientX, y: e.clientY };
- if (first) return;
+ if (first || option.disabled) return;
byKeyboard.current = false;
setLit(true);
setActive(index);
diff --git a/src/components/QuickCapture.tsx b/src/components/QuickCapture.tsx
index dc46457..977ff99 100644
--- a/src/components/QuickCapture.tsx
+++ b/src/components/QuickCapture.tsx
@@ -81,14 +81,11 @@ export function QuickCapture({ initial }: { initial: Kind }) {
};
}, [kind]);
- // Shown once drawn, never as a blank frame (window_ready, main.rs).
+ // Shown once in the page (window_ready, main.rs) — not after an animation frame, which a
+ // hidden window never draws, so the capture waited out the three-second fallback.
useEffect(() => {
- requestAnimationFrame(() =>
- requestAnimationFrame(() => {
- invoke("window_ready", { needsYou: true }).catch(() => {});
- field.current?.focus();
- }),
- );
+ invoke("window_ready", { needsYou: true }).catch(() => {});
+ field.current?.focus();
}, []);
const close = () => void intakeApi.captureClose().catch(() => window.close());
diff --git a/src/components/ShortcutsSheet.tsx b/src/components/ShortcutsSheet.tsx
new file mode 100644
index 0000000..1c7508f
--- /dev/null
+++ b/src/components/ShortcutsSheet.tsx
@@ -0,0 +1,144 @@
+/**
+ * Every app's keys on one sheet (Ctrl+/), grouped by app and laid out as a Mac app's Help
+ * lists them: what it does on the left, the keys on the right. The app in front comes first.
+ * The same list as the README's, kept here as data so the two are read side by side.
+ */
+import { useRef } from "react";
+import { Portal } from "./Portal";
+import { useModalFocus } from "../lib/focus";
+
+type Row = [keys: string[][], action: string];
+export const SHORTCUTS: { app: string; key: string; rows: Row[] }[] = [
+ {
+ app: "Everywhere",
+ key: "",
+ rows: [
+ [[["Ctrl", "K"]], "Search everything"],
+ [[["Ctrl", "R"], ["F5"]], "Sync the app in front"],
+ [[["Ctrl", ","]], "Settings"],
+ [[["Ctrl", "/"]], "Keyboard shortcuts"],
+ ],
+ },
+ {
+ app: "Notes",
+ key: "notes",
+ rows: [
+ [[["Ctrl", "N"]], "New note"],
+ [[["Ctrl", "F"], ["Ctrl", "Shift", "F"]], "Search this folder / all notes"],
+ [[["↑"], ["↓"]], "Previous / next note"],
+ [[["Ctrl", "Delete"]], "Delete note"],
+ [[["Ctrl", "S"]], "Finish editing"],
+ ],
+ },
+ {
+ app: "Reminders",
+ key: "reminders",
+ rows: [
+ [[["Ctrl", "N"], ["Ctrl", "Shift", "N"]], "New reminder / new list"],
+ [[["Tab"], ["Shift", "Tab"]], "Make a subtask / move it back out"],
+ [[["Space"], ["Return"]], "Tick / edit"],
+ [[["Ctrl", "I"]], "Show details"],
+ [[["Ctrl", "F"]], "Search"],
+ ],
+ },
+ {
+ app: "Calendar",
+ key: "calendar",
+ rows: [
+ [[["Ctrl", "1–4"]], "Day, Week, Month, Year"],
+ [[["T"]], "Today"],
+ [[["Ctrl", "Shift", "T"]], "Go to Date"],
+ [[["←"], ["→"]], "Previous / next"],
+ [[["Ctrl", "N"]], "New event"],
+ [[["Ctrl", "D"], ["Ctrl", "C"], ["Ctrl", "V"]], "Duplicate / copy / paste event"],
+ [[["Ctrl", "Alt", "Arrows"]], "Nudge the selected event"],
+ ],
+ },
+ {
+ app: "Contacts",
+ key: "contacts",
+ rows: [
+ [[["Ctrl", "N"]], "New contact"],
+ [[["Ctrl", "F"]], "Search"],
+ [[["Ctrl", "A"]], "Select all"],
+ ],
+ },
+ {
+ app: "Drive",
+ key: "drivews",
+ rows: [
+ [[["Return"], ["Ctrl", "↓"]], "Open"],
+ [[["Ctrl", "↑"]], "Enclosing folder"],
+ [[["Space"]], "Quick preview"],
+ [[["F2"], ["Delete"]], "Rename / move to Recently Deleted"],
+ ],
+ },
+ {
+ app: "Photos",
+ key: "photos",
+ rows: [
+ [[["←"], ["→"]], "Previous / next"],
+ [[["."], ["F"]], "Favourite"],
+ [[["I"], ["Z"]], "Info / zoom to fit or full size"],
+ [[["Ctrl", "+"], ["Ctrl", "-"], ["Ctrl", "0"]], "Zoom in / out / reset"],
+ [[["Space"]], "Play a video or Live Photo"],
+ [[["Esc"]], "Close the viewer"],
+ ],
+ },
+];
+
+export function ShortcutsSheet({ front, onClose }: { front: string | null; onClose: () => void }) {
+ const sheetRef = useRef<HTMLDivElement | null>(null);
+ useModalFocus(sheetRef);
+ const groups = [...SHORTCUTS].sort((a, b) => Number(b.key === front && !!front) - Number(a.key === front && !!front));
+ return (
+ <Portal>
+ <div className="modal-veil" onClick={onClose}>
+ <div
+ ref={sheetRef}
+ className="modal-sheet shortcuts-sheet"
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="shortcuts-title"
+ onClick={(e) => e.stopPropagation()}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ e.stopPropagation();
+ onClose();
+ }
+ }}
+ >
+ <h2 id="shortcuts-title">Keyboard Shortcuts</h2>
+ <div className="shortcuts-groups" tabIndex={0} aria-label="Shortcuts by app">
+ {groups.map((g) => (
+ <section key={g.app} aria-labelledby={`shortcuts-${g.app}`}>
+ <h3 id={`shortcuts-${g.app}`}>{g.app}</h3>
+ <dl>
+ {g.rows.map(([keys, action]) => (
+ <div key={action} className="shortcuts-row">
+ <dt>{action}</dt>
+ <dd>
+ {keys.map((combo, i) => (
+ <span key={i} className="shortcuts-combo">
+ {combo.map((k) => (
+ <kbd key={k}>{k}</kbd>
+ ))}
+ </span>
+ ))}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ </section>
+ ))}
+ </div>
+ <div className="sheet-actions">
+ <button className="primary" autoFocus onClick={onClose}>
+ Done
+ </button>
+ </div>
+ </div>
+ </div>
+ </Portal>
+ );
+}
diff --git a/src/components/Toast.tsx b/src/components/Toast.tsx
index 8f05504..c7f2ce0 100644
--- a/src/components/Toast.tsx
+++ b/src/components/Toast.tsx
@@ -147,12 +147,19 @@ function ToastCard({ toast: t }: { toast: Toast }) {
// Gone by itself after a moment — longer when there is something to do — but never while
// the pointer or the keys are on it.
const held = useRef(false);
- const duration = t.duration === undefined ? (t.tone === "error" ? null : t.action ? 6000 : 4000) : t.duration;
+ const duration = t.duration === undefined ? (t.tone === "error" ? null : readingTime(t.message, !!t.action)) : t.duration;
useEffect(() => {
if (duration === null) return undefined;
+ // Counted only while it can be read: not while held, nor while the window is out of
+ // sight — a notice that ran out behind another window was never seen at all.
+ let left = duration;
+ let last = performance.now();
const timer = window.setInterval(() => {
- if (!held.current) dismiss();
- }, duration);
+ const now = performance.now();
+ if (!held.current && document.visibilityState === "visible") left -= now - last;
+ last = now;
+ if (left <= 0) dismiss();
+ }, 250);
return () => window.clearInterval(timer);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [duration]);
@@ -220,3 +227,14 @@ export function toastSaved(path: string, count = 1) {
},
});
}
+
+/**
+ * How long a notice stays: long enough to read it. At least five seconds (eight with an
+ * action to take), plus about a quarter of a second for each word past the first five, and
+ * never more than twelve — a long file name read in four seconds was gone before it was read.
+ */
+export function readingTime(message: string, hasAction: boolean): number {
+ const words = message.trim().split(/\s+/).filter(Boolean).length;
+ const base = hasAction ? 8000 : 5000;
+ return Math.min(12000, base + Math.max(0, words - 5) * 250);
+}
diff --git a/src/lib/contactLabels.ts b/src/lib/contactLabels.ts
new file mode 100644
index 0000000..8f94fb0
--- /dev/null
+++ b/src/lib/contactLabels.ts
@@ -0,0 +1,109 @@
+/**
+ * Apple's own names for the labels on a card — the interface's half of
+ * `quince-core/src/contacts_labels.rs`, which says why there are two spellings.
+ *
+ * Contacts on the phone keeps `_$!<Mobile>!$_`; Apple's web service hands the same label out as
+ * `MOBILE` and takes it back that way. A label is shown and compared here by what it means; a
+ * label picked here is written in the service's spelling, as icloud.com writes it; a label
+ * already on a card goes back exactly as it came.
+ */
+
+/** [service spelling, Apple's token, as a card shows it] */
+const KNOWN: [string, string, string][] = [
+ ["MOBILE", "_$!<Mobile>!$_", "mobile"],
+ ["IPHONE", "iPhone", "iPhone"],
+ ["APPLE WATCH", "_$!<AppleWatch>!$_", "Apple Watch"],
+ ["HOME", "_$!<Home>!$_", "home"],
+ ["WORK", "_$!<Work>!$_", "work"],
+ ["SCHOOL", "_$!<School>!$_", "school"],
+ ["MAIN", "_$!<Main>!$_", "main"],
+ ["HOME FAX", "_$!<HomeFAX>!$_", "home fax"],
+ ["WORK FAX", "_$!<WorkFAX>!$_", "work fax"],
+ ["OTHER FAX", "_$!<OtherFAX>!$_", "other fax"],
+ ["PAGER", "_$!<Pager>!$_", "pager"],
+ ["PHONE", "_$!<Phone>!$_", "phone"],
+ ["OTHER", "_$!<Other>!$_", "other"],
+ ["ICLOUD", "iCloud", "iCloud"],
+ ["HOMEPAGE", "_$!<HomePage>!$_", "homepage"],
+ ["BLOG", "_$!<Blog>!$_", "blog"],
+ ["ANNIVERSARY", "_$!<Anniversary>!$_", "anniversary"],
+ ["BIRTHDAY", "_$!<Birthday>!$_", "birthday"],
+ ["MOTHER", "_$!<Mother>!$_", "mother"],
+ ["FATHER", "_$!<Father>!$_", "father"],
+ ["PARENT", "_$!<Parent>!$_", "parent"],
+ ["BROTHER", "_$!<Brother>!$_", "brother"],
+ ["SISTER", "_$!<Sister>!$_", "sister"],
+ ["SON", "_$!<Son>!$_", "son"],
+ ["DAUGHTER", "_$!<Daughter>!$_", "daughter"],
+ ["CHILD", "_$!<Child>!$_", "child"],
+ ["FRIEND", "_$!<Friend>!$_", "friend"],
+ ["SPOUSE", "_$!<Spouse>!$_", "spouse"],
+ ["PARTNER", "_$!<Partner>!$_", "partner"],
+ ["ASSISTANT", "_$!<Assistant>!$_", "assistant"],
+ ["MANAGER", "_$!<Manager>!$_", "manager"],
+];
+
+/** Instant messaging services and social networks, by Apple's names for them. */
+const SERVICES: Record<string, string> = {
+ AIM: "AIM", YAHOO: "Yahoo", MSN: "MSN", ICQ: "ICQ", JABBER: "Jabber", SKYPE: "Skype",
+ GOOGLETALK: "Google Talk", FACEBOOK: "Facebook", QQ: "QQ", GADUGADU: "Gadu-Gadu",
+ TWITTER: "Twitter", FLICKR: "Flickr", LINKEDIN: "LinkedIn", MYSPACE: "Myspace", SINAWEIBO: "Sina Weibo",
+ GAMECENTER: "Game Center",
+};
+
+const byAny = new Map<string, [string, string, string]>();
+for (const k of KNOWN) for (const spelling of k) byAny.set(spelling.toLowerCase(), k);
+
+/** The label Apple means, in its service spelling; null for a custom one. */
+export function knownLabel(label: string | null | undefined): string | null {
+ if (!label) return null;
+ return byAny.get(label.trim().toLowerCase())?.[0] ?? null;
+}
+
+/** How a card shows a label: Apple's word for one it knows, a service by its name, else as typed. */
+export function labelText(label: string): string {
+ const k = byAny.get(label.trim().toLowerCase());
+ if (k) return k[2];
+ return SERVICES[label.trim().toUpperCase()] ?? label;
+}
+
+/** The labels icloud.com's editor offers for each kind of detail, "other" last as it adds it. */
+export const OFFERED: Record<string, string[]> = {
+ phone: ["MOBILE", "IPHONE", "APPLE WATCH", "HOME", "WORK", "SCHOOL", "MAIN", "HOME FAX", "WORK FAX", "PAGER", "OTHER"],
+ email: ["HOME", "WORK", "SCHOOL", "ICLOUD", "OTHER"],
+ url: ["HOMEPAGE", "HOME", "WORK", "SCHOOL", "OTHER"],
+ address: ["HOME", "WORK", "SCHOOL", "OTHER"],
+ date: ["ANNIVERSARY", "OTHER"],
+ related: ["MOTHER", "FATHER", "PARENT", "BROTHER", "SISTER", "SON", "DAUGHTER", "CHILD", "FRIEND", "SPOUSE", "PARTNER", "ASSISTANT", "MANAGER", "OTHER"],
+ im: ["AIM", "YAHOO", "MSN", "ICQ", "JABBER", "SKYPE", "GOOGLETALK", "FACEBOOK", "QQ", "GADUGADU"],
+ profile: ["TWITTER", "FACEBOOK", "FLICKR", "LINKEDIN", "MYSPACE", "SINAWEIBO"],
+};
+
+/** The label a new detail of each kind starts with, as icloud.com starts one. */
+export const FIRST_LABEL: Record<string, string> = {
+ phone: "MOBILE", email: "HOME", url: "HOMEPAGE", date: "ANNIVERSARY", related: "MOTHER", im: "SKYPE", profile: "TWITTER",
+};
+
+/** Whether a label is one of a kind's own (instant messaging and profiles: a service), whichever spelling. */
+export function offeredMatch(kind: string, label: string | null): string | null {
+ if (!label) return null;
+ const list = OFFERED[kind] ?? [];
+ const known = knownLabel(label);
+ if (known && list.includes(known)) return known;
+ const upper = label.trim().toUpperCase();
+ return list.includes(upper) && SERVICES[upper] ? upper : null;
+}
+
+/** A social profile's page, as icloud.com links one. */
+export function profileHref(label: string | null, user: string): string | null {
+ const u = user.replace(/^@+/, "");
+ switch ((label ?? "").toUpperCase()) {
+ case "TWITTER": return `https://twitter.com/${u}`;
+ case "FACEBOOK": return `https://www.facebook.com/${u}`;
+ case "LINKEDIN": return `https://www.linkedin.com/in/${u}`;
+ case "FLICKR": return `https://www.flickr.com/photos/${u}`;
+ case "MYSPACE": return `https://myspace.com/${u}`;
+ case "SINAWEIBO": return `https://weibo.com/n/${u}`;
+ default: return null;
+ }
+}
diff --git a/src/lib/fade.ts b/src/lib/fade.ts
index 6e9309f..71d3e24 100644
--- a/src/lib/fade.ts
+++ b/src/lib/fade.ts
@@ -19,7 +19,9 @@ export function fadeIn(el: HTMLElement | null, { from = 0, duration = 150 }: { f
const start = performance.now();
el.style.opacity = String(from);
const step = (now: number) => {
- const t = Math.min(1, (now - start) / duration);
+ // A frame's time can be from just before the fade began (it was started mid-frame): never
+ // below where it starts.
+ const t = Math.max(0, Math.min(1, (now - start) / duration));
// Ease out: most of the change early, settling gently.
const k = 1 - (1 - t) * (1 - t);
if (t >= 1) {
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 9842c3f..5af2312 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -1,6 +1,6 @@
import { convertFileSrc, invoke } from "@tauri-apps/api/core";
-export type Status = { hasStoredSession: boolean; signedIn: boolean };
+export type Status = { hasStoredSession: boolean; signedIn: boolean; libraryReady: boolean };
/** A change made here waiting for Apple. */
export type WaitingChange = { service: string; record: string; kind: string };
@@ -97,6 +97,8 @@ export const api = {
unsent: () => invoke<{ changes: number; files: number; photos: number }>("account_unsent"),
/** What waits to reach Apple, and what Apple turned down. */
outboxStatus: () => invoke<OutboxStatus>("outbox_status"),
+ /** What the network lock lets Skykeep reach: Apple's domains, and each subscribed calendar's host. */
+ networkReach: () => invoke<{ apple: string[]; subscribed: string[] }>("network_reach"),
/** A refused change, sent again. */
outboxResend: (id: number) => invoke<void>("outbox_resend", { id }),
/** A refused change let go of: Apple's version stands. */
@@ -105,6 +107,8 @@ export const api = {
eventSave: (draft: EventWrite) => invoke<string>("event_save", { draft }),
eventAlerts: (guid: string) => invoke<number[]>("event_alerts", { guid }),
+ /** An event's guests and their answers, the organizer first. Read only. */
+ eventGuests: (guid: string) => invoke<Guest[]>("event_guests", { guid }),
eventRepeat: (guid: string) => invoke<EventRepeat | null>("event_repeat", { guid }),
eventDelete: (guid: string, scope?: EventScope) => invoke<void>("event_delete", { guid, scope: scope ?? null }),
calendarSync: (from: string, to: string, timezone: string) =>
@@ -115,6 +119,13 @@ export const api = {
invoke<CalendarEvent[]>("calendar_events", { from, to }),
calendarList: () => invoke<Calendar[]>("calendar_list"),
photosList: (view: PhotoView) => invoke<Photo[]>("photos_list", { view }),
+ /** Every photo a grid shows, as it lays them out: ids, grouping dates and marks, no photos. */
+ photosIndex: (source: PhotoSource, order: PhotoOrder | null) => invoke<PhotoIndex>("photos_index", { source, order }),
+ /** A source's photos from `offset`, in its index's order: the first screen, before the index. */
+ photosPage: (source: PhotoSource, order: PhotoOrder | null, offset: number, limit: number) =>
+ invoke<Photo[]>("photos_page", { source, order, offset, limit }),
+ /** Photos by id, in the order asked; any gone are left out. */
+ photosGet: (ids: string[]) => invoke<Photo[]>("photos_get", { ids }),
photosCounts: () => invoke<[PhotoView, number][]>("photos_counts"),
/** The albums the person made, each with how many photos it holds. */
/** Each album, how many it shows, and its cover — the first photo it shows. */
@@ -123,6 +134,9 @@ export const api = {
/** A video (or a Live Photo's moving part) opened in this computer's own player. */
/** How a video's picture is turned, as its file records it (served upright: drawn here). */
photoVideoTurn: (id: string, which: "original" | "video") => invoke<Turn>("photo_video_turn", { id, which }),
+ /** How much larger than its box a film is drawn, so only its clean aperture shows (a Live
+ * Photo's moving part is recorded with a margin the still does not have). */
+ photoVideoZoom: (id: string, which: "original" | "video") => invoke<number>("photo_video_zoom", { id, which }),
/** The iCloud Drive folder on this computer: whether it is up, where, and what stopped it. */
driveFolderStatus: () => invoke<DriveFolder>("drive_folder_status"),
driveFolderSet: (on: boolean) => invoke<DriveFolder>("drive_folder_set", { on }),
@@ -144,10 +158,12 @@ export const api = {
photoPlay: (id: string) => invoke<void>("photo_play", { id }),
/** Where the window's player fetches videos from (a loopback server), or null without one. */
videoBase: () => invoke<string | null>("video_base"),
+ /** What this computer's player can decode; `missing` names the packages it lacks. */
+ videoSupport: () => invoke<{ h264: boolean; hevc: boolean; missing: string[] }>("video_support"),
/** The window full screen or back; answers whether it now is. */
windowFullscreen: (on: boolean) => invoke<boolean>("window_fullscreen", { on }),
/** What the window shows pictures at, so the app makes them before they are shown. */
- photosPrepare: (shown: { cell: number; fit: boolean; stageW: number; stageH: number; dpr: number }) =>
+ photosPrepare: (shown: { cell: number; fit: boolean; stageW: number; stageH: number; dpr: number; view?: PhotoView | null }) =>
invoke<void>("photos_prepare", { shown }),
/** Shared albums, made or joined, newest first — from Apple each time. */
photosSharedAlbums: () => invoke<SharedAlbum[]>("photos_shared_albums"),
@@ -203,8 +219,11 @@ export const api = {
invoke<Reminder[]>("reminders_in", { listGuid, includeDone }),
remindersDueBetween: (from: number, to: number) =>
invoke<Reminder[]>("reminders_due_between", { from, to }),
- reminderSetRepeat: (guid: string, listGuid: string, repeat: Repeat | null) =>
- invoke<void>("reminder_set_repeat", { guid, listGuid, repeat }),
+ /** A repeat, or null to stop it; `endAt` (seconds) ends it on that date, null never;
+ * `daysOfWeek` (1 Sunday … 7 Saturday) the weekdays a weekly one falls on, empty for its
+ * due date's day. */
+ reminderSetRepeat: (guid: string, listGuid: string, repeat: Repeat | null, endAt: number | null = null, daysOfWeek: number[] = []) =>
+ invoke<void>("reminder_set_repeat", { guid, listGuid, repeat, endAt, daysOfWeek }),
reminderSetDone: (guid: string, listGuid: string, done: boolean) =>
invoke<void>("reminder_set_done", { guid, listGuid, done }),
reminderEdit: (guid: string, listGuid: string, edit: ReminderEdit) =>
@@ -293,6 +312,12 @@ export const api = {
contactSave: (contact: Contact, base: Contact | null = null) => invoke<string>("contact_save", { contact, base }),
contactDelete: (guid: string) => invoke<void>("contact_delete", { guid }),
contactsList: (search: string | null) => invoke<Contact[]>("contacts_list", { search }),
+ /** Cards that look like one person. */
+ contactsDuplicates: () => invoke<Duplicates[]>("contacts_duplicates"),
+ /** These cards as one, shown at once and sent shortly after. Answers the kept card's id. */
+ contactsMerge: (guids: string[]) => invoke<string>("contacts_merge", { guids }),
+ /** Take back a merge iCloud does not have yet. Answers whether it was. */
+ contactsMergeUndo: (kept: string) => invoke<boolean>("contacts_merge_undo", { kept }),
/** These people as a vCard file in Downloads, written by Apple. Returns the path. */
contactsExport: (guids: string[], fileName: string) => invoke<string>("contacts_export", { guids, fileName }),
/** Everyone in a vCard file, added to Contacts. Returns [added, could not be read]. */
@@ -406,6 +431,15 @@ export type EventWrite = {
};
/** How an event repeats, in icloud.com's words. */
+/** Someone invited to an event. `status` is "pending" until they answer. */
+export type Guest = {
+ name: string | null;
+ email: string | null;
+ status: "accepted" | "declined" | "tentative" | "pending";
+ isMe: boolean;
+ isOrganizer: boolean;
+};
+
export type EventRepeat = { freq: "daily" | "weekly" | "monthly" | "yearly"; interval: number; count: number | null };
export type CalendarEvent = {
@@ -513,6 +547,8 @@ export type Reminder = {
sectionGuid?: string | null;
/** Due on a day rather than at a time. */
allDay?: boolean;
+ /** The named zone its time is kept in ("America/New_York"), as the phone's Time Zone row. */
+ timezone?: string | null;
etag: string | null;
};
@@ -596,14 +632,33 @@ export type Contact = {
lastName: string | null;
photoUrl: string | null;
photoSignature: string | null;
+ /** The square chosen, `x,y,width,height` in the picture's own pixels, from its bottom left. */
+ photoCrop?: string | null;
company: string | null;
isCompany: boolean;
birthday: string | null;
notes: string | null;
etag: string | null;
+ /**
+ * Every number, email, link, address (its lines), date (`date`, as Apple writes a birthday),
+ * related person (`related`), social profile (`profile`) and instant message (`im`, labelled
+ * by its service). Labels are Apple's own (`MOBILE` or `_$!<Mobile>!$_`) or as typed.
+ */
methods: ContactMethod[];
+ /** The rest of the name and work, as Apple's card holds them. */
+ prefix?: string | null;
+ suffix?: string | null;
+ nickname?: string | null;
+ phoneticFirstName?: string | null;
+ phoneticLastName?: string | null;
+ phoneticCompany?: string | null;
+ jobTitle?: string | null;
+ department?: string | null;
};
+/** Cards that look like one person, and what they share: `name`, `phone`, `email`. */
+export type Duplicates = { guids: string[]; reasons: string[] };
+
/** What to show, whichever name fields a contact happens to have. */
/**
* Where the interface loads a contact's picture from.
@@ -638,6 +693,11 @@ export function noteMediaSrc(id: string, part: "file" | "preview" | "drawing" |
return convertFileSrc(`note/${id}/${part}`, "quince");
}
+/** A picture attached to a reminder (`Attachment/<UUID>`), fetched from Apple once and kept. */
+export function reminderImageSrc(attachment: string): string {
+ return convertFileSrc(`rimg/${attachment.replace(/^Attachment\//, "")}`, "quince");
+}
+
/** One of a photo's pictures, served from the disk cache (fetched from Apple once). */
export function pictureSrc(id: string, size: "thumb" | "medium" | "full" | "original" | "video"): string {
return convertFileSrc(`pic/${id}/${size}`, "quince");
@@ -678,6 +738,20 @@ export type PhotoAlbum = {
parent?: string | null;
};
+/** Where a grid's photos come from (quince-core photos::Source). */
+export type PhotoSource = { view: PhotoView } | { album: string } | { query: string } | { burst: string };
+/** How a sortable view is sorted; null keeps the source's own order. */
+export type PhotoOrder = { by: "taken" | "added"; oldest: boolean };
+/** A grid's layout before its photos (quince-core photos::PhotoIndex). */
+export type PhotoIndex = {
+ ids: string[];
+ /** What each is grouped by: when taken, or when added if sorted by that. */
+ keys: number[];
+ /** Packed: bits 0–1 the kind (0 image, 1 video, 2 Live), bit 2 a favorite, bits 3–5 its stars. */
+ marks: number[];
+ first: number | null;
+ last: number | null;
+};
export type PhotoView = "library" | "favorites" | "videos" | "screenshots" | "panoramas" | "portrait" | "recents" | "hidden" | "rated" | "recentlyDeleted";
export type Photo = {
@@ -722,8 +796,21 @@ export function contactPhotoSrc(guid: string): string {
return convertFileSrc(`photo/${guid}`, "quince");
}
+/**
+ * A contact's picture, named by which picture and which square of it, so a picture changed
+ * here (or on the phone) is fetched anew rather than drawn from the webview's cache.
+ */
export function photoSrc(c: Contact): string | null {
- return c.photoUrl ? contactPhotoSrc(c.guid) : null;
+ if (!c.photoUrl) return null;
+ const which = c.photoSignature ?? (c.photoUrl.startsWith("data:") ? textHash(c.photoUrl) : c.photoUrl);
+ return `${contactPhotoSrc(c.guid)}?v=${encodeURIComponent(`${which}|${c.photoCrop ?? ""}`)}`;
+}
+
+/** A short, stable name for a long text. */
+function textHash(text: string): string {
+ let h = 5381;
+ for (let i = 0; i < text.length; i += 7) h = ((h * 33) ^ text.charCodeAt(i)) >>> 0;
+ return `${text.length.toString(36)}${h.toString(36)}`;
}
/** One thing the search across everything found (search.rs `Hit`): marks are [start, end)
@@ -804,10 +891,14 @@ export type Turn = [number, number, number, number];
* the window, which WebKitGTK honoured in one way of drawing and not another); here it is
* laid out in its own shape and turned into the box with the file's own matrix — CSS's
* matrix() and the file's are the same reading — a phone's quarter turn, or the front
- * camera's quarter turn and mirror.
+ * camera's quarter turn and mirror. `w` and `h` are the photo as shown — upright — never the
+ * sensor's sides Apple records: given those, a portrait Live Photo's film was laid out in a
+ * landscape box, turned, and came out half the size of its still. `zoom` draws it that much
+ * larger, for a film recorded with a margin round what the still shows (photoVideoZoom).
*/
-export function turnStyle(turn: Turn | null | undefined, w: number, h: number): Record<string, string> {
- if (!turn || (turn[0] === 1 && turn[1] === 0 && turn[2] === 0 && turn[3] === 1) || !w || !h) return {};
+export function turnStyle(turn: Turn | null | undefined, w: number, h: number, zoom = 1): Record<string, string> {
+ const z = zoom > 1 && zoom <= 1.5 ? zoom : 1;
+ if (!turn || (turn[0] === 1 && turn[1] === 0 && turn[2] === 0 && turn[3] === 1) || !w || !h) return z === 1 ? {} : { transform: `scale(${z})` };
const quarter = turn[0] === 0;
return {
position: "absolute",
@@ -818,7 +909,7 @@ export function turnStyle(turn: Turn | null | undefined, w: number, h: number):
maxWidth: "none",
maxHeight: "none",
translate: "-50% -50%",
- transform: `matrix(${turn[0]}, ${turn[1]}, ${turn[2]}, ${turn[3]}, 0, 0)`,
+ transform: `matrix(${turn[0] * z}, ${turn[1] * z}, ${turn[2] * z}, ${turn[3] * z}, 0, 0)`,
};
}
@@ -855,6 +946,28 @@ export const settingsApi = {
alertsShown: () => invoke<boolean | null>("alerts_shown"),
};
+/** Photos' originals and previews kept on this computer, held to a cap (src-tauri/src/photo_cache.rs). */
+export type PhotoCache = {
+ /** Originals and previews on disk, in bytes. */
+ used: number;
+ /** The cap chosen. */
+ cap: number;
+ /** What it is held to now: the cap, or less while the disk is short of space. */
+ limit: number;
+ /** The grid's thumbnails, which always stay. */
+ thumbnails: number;
+ /** The caps that can be chosen, smallest first. */
+ steps: number[];
+};
+/** Told when the cache changed in the background (a trim after the cap was lowered). */
+export const PHOTO_CACHE = "quince://photo-cache";
+export const photoCacheApi = {
+ status: () => invoke<PhotoCache>("photos_cache_status"),
+ /** Answers at once; the trim a lower cap starts reports through PHOTO_CACHE. */
+ set: (bytes: number) => invoke<PhotoCache>("photos_cache_set", { bytes }),
+ clear: () => invoke<PhotoCache>("photos_cache_clear"),
+};
+
/* ── Intake: files opened with Skykeep, and quick capture (src-tauri/src/intake.rs) ── */
/** Told to a window when a file has arrived for it; it collects with `intakeApi.pending`. */
@@ -944,8 +1057,37 @@ export type ReminderDetail = {
tags: string[];
url: string | null;
earlyAlerts: EarlyAlert[];
- /** File or image attachments, which are not shown here yet. */
+ /** File or image attachments, pictures included. */
otherAttachments: number;
+ /** Its pictures' attachment ids, as the phone lists them. */
+ images: string[];
+};
+
+/** A repeat whole, as the phone's Repeat and End Repeat rows show it. Frequency is Apple's:
+ * 0 daily, 1 weekly, 2 monthly, 3 yearly, 4 hourly. `other` names rule fields (chosen days)
+ * this app keeps but does not read. */
+export type RepeatRule = { frequency: number; interval: number; endAt: number | null; occurrenceCount: number; daysOfWeek: number[]; other: string[] };
+/** What a reminder's row shows beside its date, as the phone's list does. */
+export type ReminderMarks = {
+ guid: string;
+ daysOfWeek: number[];
+ urgent: boolean;
+ location: PlaceAlarm | null;
+ messaging: string | null;
+ url: string | null;
+};
+/** A place a reminder rings at; `proximity` is "arriving" or "leaving". */
+export type PlaceAlarm = { title: string | null; proximity: string | null; kind: string };
+/** The person a reminder comes up for when messaging them. */
+export type MessagingPerson = { name: string | null; handles: string[] };
+/** The rest of the phone's Details screen. `urgent` is null until known. */
+export type ReminderMore = {
+ guid: string;
+ repeat: RepeatRule | null;
+ timeZone: string | null;
+ urgent: boolean | null;
+ location: PlaceAlarm | null;
+ messaging: MessagingPerson | null;
};
/** A tag across the account, and how many reminders still to do carry it. */
@@ -968,6 +1110,11 @@ export type SmartListContents = { reminders: Reminder[]; unknown: string[] };
export const remindersApi = {
detail: (guid: string) => invoke<ReminderDetail>("reminder_detail", { guid }),
+ more: (guid: string) => invoke<ReminderMore>("reminder_more", { guid }),
+ /** Row marks for these reminders; only rows with any come back. */
+ marks: (guids: string[]) => invoke<ReminderMarks[]>("reminder_marks", { guids }),
+ /** Reminders whose tick now is the last of their repeat: ticked, each is completed. */
+ ending: () => invoke<string[]>("reminders_ending"),
tags: () => invoke<TagCount[]>("reminder_tags"),
tagged: (name: string) => invoke<Reminder[]>("reminders_tagged", { name }),
smartLists: () => invoke<ReminderSmartList[]>("reminder_smart_lists"),
@@ -1007,6 +1154,8 @@ export const notesLockApi = {
/** Lock every opened note again. */
noteLockForget: () => invoke<void>("note_lock_forget"),
/** Add the file at `path` at `atOffset` (UTF-16 units of `base`, the text on screen). */
+ /** A small picture of a file about to be added (empty for one that is not a picture). */
+ noteAttachPreview: (path: string) => invoke<ArrayBuffer>("note_attach_preview", { path }),
noteAttachFile: (guid: string, path: string, atOffset: number, base: string | null) =>
invoke<NoteAttached>("note_attach_file", { guid, path, atOffset, base }),
/**
diff --git a/src/lib/outbox.ts b/src/lib/outbox.ts
index 65f8b11..caa6007 100644
--- a/src/lib/outbox.ts
+++ b/src/lib/outbox.ts
@@ -27,7 +27,7 @@ export function changeWords(r: Pick<RefusedChange, "service" | "kind">): string
const words: Record<string, Record<string, string>> = {
notes: { save: "an edit to a note", create: "a new note", move: "a note's move", delete: "a note's deletion", pin: "a note's pin" },
reminders: { create: "a new reminder", edit: "a change to a reminder", delete: "a reminder's deletion", done: "a tick", advance: "a tick" },
- contacts: { save: "a change to a contact", delete: "a contact's deletion" },
+ contacts: { save: "a change to a contact", delete: "a contact's deletion", merge: "a merge of duplicate cards", address: "a change to a contact's address" },
calendar: { save: "a change to an event", delete: "an event's deletion" },
};
return words[r.service]?.[r.kind] ?? null;
diff --git a/src/lib/screen.ts b/src/lib/screen.ts
index 2058800..1a7abc4 100644
--- a/src/lib/screen.ts
+++ b/src/lib/screen.ts
@@ -20,3 +20,17 @@ export function useActiveRef() {
}, [active]);
return ref;
}
+
+/**
+ * Whether a menu, a picker's list or a sheet is open in front, which answers its own keys. A
+ * screen's own list of rows (a list box marked `data-rows`, as Notes and Contacts draw theirs)
+ * is not one, and nothing in a screen kept out of sight counts.
+ */
+export function overlayOpen(): boolean {
+ const open = document.querySelectorAll('[role="menu"], [role="listbox"], [role="dialog"], [role="alertdialog"], .confirm');
+ for (const el of open) {
+ if (el.matches("[data-rows]") || el.closest("[inert], [hidden]")) continue;
+ return true;
+ }
+ return false;
+}
diff --git a/src/lib/theme.ts b/src/lib/theme.ts
index e155178..0ceff82 100644
--- a/src/lib/theme.ts
+++ b/src/lib/theme.ts
@@ -27,3 +27,21 @@ export function setTheme(theme: Theme) {
}
applyTheme(theme);
}
+
+/**
+ * The desktop's Increase Contrast, where the engine does not say it itself: on Linux the app
+ * reads the Settings portal (appearance.rs) and the root is marked `data-contrast="more"`,
+ * which a11y.css treats as `prefers-contrast: more`. Followed as it changes.
+ */
+export function followContrast() {
+ const mark = (more: unknown) => {
+ if (more === true) document.documentElement.dataset.contrast = "more";
+ else delete document.documentElement.dataset.contrast;
+ };
+ void import("@tauri-apps/api/core")
+ .then(({ invoke }) => invoke<boolean>("system_contrast"))
+ .then(mark, () => {});
+ void import("@tauri-apps/api/event")
+ .then(({ listen }) => listen<boolean>("quince://contrast", (e) => mark(e.payload)))
+ .catch(() => {});
+}
diff --git a/src/main.tsx b/src/main.tsx
index e7eba27..c137ac8 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -10,12 +10,13 @@ import "./styles/calendar.css";
import "./styles/notes.css";
import "./styles/photos.css";
import "./styles/a11y.css";
-import { applyTheme, storedTheme } from "./lib/theme";
+import { applyTheme, followContrast, storedTheme } from "./lib/theme";
import { keepTinted } from "./lib/tint";
import { fadeSheetsIn } from "./lib/fade";
// Before the first paint, so the window opens in the appearance chosen.
applyTheme(storedTheme());
+followContrast();
keepTinted();
fadeSheetsIn();
diff --git a/src/screens/ContactsView.tsx b/src/screens/ContactsView.tsx
index 81713dc..128eb49 100644
--- a/src/screens/ContactsView.tsx
+++ b/src/screens/ContactsView.tsx
@@ -7,7 +7,7 @@ import { ConfirmSheet, useConfirm } from "../components/Confirm";
import { EmptyState } from "../components/EmptyState";
import { SearchField } from "../components/SearchField";
import { PaneTitle } from "../components/PaneTitle";
-import { ChevronLeft, Plus, UserPlus, UsersRound, UserRound } from "lucide-react";
+import { Camera, ChevronLeft, Plus, UserPlus, UsersRound, UserRound } from "lucide-react";
import {
api,
contactsApi,
@@ -16,6 +16,7 @@ import {
photoSrc,
type Contact,
type ContactList,
+ type Duplicates,
type ContactMethod,
type AddressEdit,
type AddressPart,
@@ -23,12 +24,15 @@ import {
} from "../lib/ipc";
import { Arriving } from "../components/EmptyState";
import { useArriving, useSync } from "../lib/sync";
-import { useActiveRef, useScreenActive } from "../lib/screen";
+import { overlayOpen, useActiveRef, useScreenActive } from "../lib/screen";
import { Picker } from "../components/Picker";
import { RowMenu, type MenuEntry } from "../components/RowMenu";
import { pickOpen } from "../lib/pick";
-import { dateText } from "../lib/when";
import { useReveal } from "../lib/reveal";
+import { FIRST_LABEL, OFFERED, labelText, offeredMatch, profileHref } from "../lib/contactLabels";
+import { DateField, dateWords } from "./contacts/DateField";
+import { PhotoSheet } from "./contacts/PhotoSheet";
+import { DuplicatesBanner, DuplicatesView } from "./contacts/Duplicates";
/** The sidebar row that is every contact rather than a list. */
const ALL = "";
@@ -42,19 +46,6 @@ const KINDS = [
{ value: "url", label: "link" },
] as const;
-/**
- * Apple's own labels for each kind of detail, as icloud.com's contact editor offers them
- * (contacts2 bundle). Stored in Apple's spelling, so a label picked here reads as the phone's
- * own "mobile" or "work" there, not as a custom label that happens to say the same thing.
- */
-const LABELS: Record<string, string[]> = {
- phone: ["MOBILE", "IPHONE", "APPLE WATCH", "HOME", "WORK", "SCHOOL", "MAIN", "HOME FAX", "WORK FAX", "PAGER"],
- email: ["HOME", "WORK", "SCHOOL", "ICLOUD"],
- url: ["HOMEPAGE", "HOME", "WORK", "SCHOOL"],
-};
-const SHOWN: Record<string, string> = { IPHONE: "iPhone", "APPLE WATCH": "Apple Watch", ICLOUD: "iCloud" };
-/** A label as Contacts writes it: Apple's names in their own case, anything else as typed. */
-const labelText = (label: string) => SHOWN[label] ?? (label === label.toUpperCase() ? label.toLowerCase() : label);
const CUSTOM = "\u0000custom";
/**
@@ -63,14 +54,46 @@ const CUSTOM = "\u0000custom";
* The image is allowed to fail — a photo Apple has moved, or no network yet — and when it
* does the initials underneath are what shows, rather than a broken frame.
*/
-function Avatar({ contact, large }: { contact: Contact; large?: boolean }) {
+function Avatar({ contact, large, preview }: { contact: Contact; large?: boolean; preview?: string | null }) {
return (
<span className={`avatar${large ? " large" : ""}`} aria-hidden="true">
- <Face src={photoSrc(contact)} initials={initials(contact)} />
+ <Face src={preview !== undefined ? preview : photoSrc(contact)} initials={initials(contact)} />
</span>
);
}
+/** The parts of a name and work that Contacts adds only when asked, in its order. */
+const NAME_FIELDS = [
+ { key: "prefix", label: "Prefix" },
+ { key: "phoneticFirstName", label: "Phonetic first name" },
+ { key: "middleName", label: "Middle name" },
+ { key: "phoneticLastName", label: "Phonetic last name" },
+ { key: "suffix", label: "Suffix" },
+ { key: "nickname", label: "Nickname" },
+ { key: "jobTitle", label: "Job title" },
+ { key: "department", label: "Department" },
+ { key: "phoneticCompany", label: "Phonetic company name" },
+] as const;
+type NameKey = (typeof NAME_FIELDS)[number]["key"];
+
+/** The details a card can gain from Add Field, by Apple's names for them. */
+const ADDABLE = [
+ { kind: "phone", label: "Phone" },
+ { kind: "email", label: "Email" },
+ { kind: "url", label: "URL" },
+ { kind: "date", label: "Date" },
+ { kind: "related", label: "Related Name" },
+ { kind: "profile", label: "Social Profile" },
+ { kind: "im", label: "Instant Message" },
+] as const;
+
+/** The whole name, as the top of a card shows it: prefix and suffix included. */
+function fullName(c: Contact): string {
+ const name = [c.prefix, c.firstName, c.middleName, c.lastName].filter(Boolean).join(" ");
+ if (!name.trim()) return displayName(c);
+ return c.suffix ? `${name}, ${c.suffix}` : name;
+}
+
const blank = (): Contact => ({
guid: "",
firstName: null,
@@ -91,13 +114,26 @@ const KIND_LABEL: Record<string, string> = {
email: "email",
url: "link",
address: "address",
- profile: "profile",
+ profile: "social profile",
+ date: "date",
+ related: "related name",
+ im: "instant message",
};
-/** What this app can safely write back. Apple stores an address as a structured thing and a
- * profile as an encoded handle; editing either as one line here would mangle it, so they
- * are shown and left alone rather than half-supported. */
-const EDITABLE_KINDS = new Set(["phone", "email", "url"]);
+/** What a value of each kind looks like, as a field's hint. */
+const PLACEHOLDER: Record<string, string> = {
+ phone: "+1 555 0100",
+ email: "[email protected]",
+ url: "example.com",
+ related: "Name",
+ profile: "Username",
+ im: "Username",
+};
+
+/** Every kind written back here. An address is written part by part, on its own (below). */
+const EDITABLE_KINDS = new Set(["phone", "email", "url", "date", "related", "profile", "im"]);
+/** The kinds a detail can be switched between, as the first three always could. */
+const SWITCHABLE = new Set(["phone", "email", "url"]);
/** Initials for the avatar, from whichever name fields exist. */
function initials(contact: Contact): string {
@@ -134,6 +170,22 @@ export function ContactsView() {
const [draft, setDraft] = useState<Contact | null>(null);
/** Details whose label is being typed rather than picked, by their place on the card. */
const [customAt, setCustomAt] = useState<Set<number>>(() => new Set());
+ /** The photo sheet, open over the form. */
+ const [photoSheet, setPhotoSheet] = useState(false);
+ /** A picture chosen in the form, small, shown until iCloud has it; null once taken away. */
+ const [draftPreview, setDraftPreview] = useState<string | null | undefined>(undefined);
+ /** Name and work fields added to the form, besides those already holding something. */
+ const [shownFields, setShownFields] = useState<Set<NameKey>>(() => new Set());
+ const [addMenu, setAddMenu] = useState<MenuAt | null>(null);
+ /** A detail just added takes the focus, once. */
+ const [focusAt, setFocusAt] = useState<number | null>(null);
+ /** A name field or the birthday just added takes the focus, once. */
+ const [focusName, setFocusName] = useState<string | null>(null);
+ /** Cards that look like one person, and whether they are what the pane shows. */
+ const [dupes, setDupes] = useState<Duplicates[]>([]);
+ const [showDupes, setShowDupes] = useState(false);
+ /** The cards just made one, while their merge can still be undone. */
+ const [lastMerge, setLastMerge] = useState<string[]>([]);
/**
* The card as the form opened it. Saving writes only what differs from it, over Apple's
* card as it is then — so a change made on the phone while the form was open stays.
@@ -161,10 +213,23 @@ export function ContactsView() {
setAddressCustom(new Set());
setAddedKey(null);
};
+ const resetForm = () => {
+ setCustomAt(new Set());
+ setDraftPreview(undefined);
+ setShownFields(new Set());
+ setFocusAt(null);
+ setFocusName(null);
+ };
+ const startNew = () => {
+ resetForm();
+ setShowDupes(false);
+ setDraft(blank());
+ startAddresses([]);
+ };
const edit = (c: Contact) => {
draftBase.current = c;
setDraft({ ...c });
- setCustomAt(new Set());
+ resetForm();
if (addresses?.guid === c.guid) startAddresses(addresses.list);
else {
startAddresses([]);
@@ -307,6 +372,61 @@ export function ContactsView() {
useEffect(() => {
readLists().catch((e) => setError(messageOf(e)));
}, [readLists, due]);
+
+ const readDupes = useCallback(async () => {
+ const found = await api.contactsDuplicates();
+ setDupes(Array.isArray(found) ? found : []);
+ }, []);
+ useEffect(() => {
+ readDupes().catch(() => {});
+ }, [readDupes, due, outbox.tick]);
+ /** Everyone by id, for the duplicates view to draw from. */
+ const byGuid = useMemo(() => new Map(contacts.map((c) => [c.guid, c])), [contacts]);
+
+ /**
+ * Cards made one: shown at once, sent shortly after (contacts_merge.rs), and undoable until
+ * they are. Merging a group the view shows goes on with the rest; the last shows the card.
+ */
+ const undoMerge = useCallback(async (kept: string[]) => {
+ const undone = await Promise.all(kept.map((k) => api.contactsMergeUndo(k).catch(() => false)));
+ setLastMerge([]);
+ await Promise.all([read(search), readLists(), readDupes()]).catch(() => {});
+ if (undone.every(Boolean)) toast({ message: "Merge undone.", tone: "done" });
+ else toast({ message: "iCloud already has this merge, so the cards stay merged.", tone: "error" });
+ }, [read, readLists, readDupes, search]);
+ const mergeGroups = async (groups: Duplicates[]) => {
+ if (groups.length === 0) return;
+ const name = (g: Duplicates) => {
+ const people = g.guids.map((id) => byGuid.get(id)).filter((c): c is Contact => !!c);
+ return people.map(displayName).find((n) => /\p{L}/u.test(n)) ?? "this person";
+ };
+ setBusy(true);
+ setError(null);
+ const kept: string[] = [];
+ try {
+ for (const g of groups) kept.push(await api.contactsMerge(g.guids));
+ } catch (e) {
+ setError(messageOf(e));
+ } finally {
+ setBusy(false);
+ }
+ await Promise.all([read(search), readLists(), readDupes()]).catch(() => {});
+ if (kept.length === 0) return;
+ setLastMerge(kept);
+ const left = dupes.length - groups.length;
+ if (left <= 0) {
+ setShowDupes(false);
+ setOpenGuid(kept[0]);
+ }
+ toast({
+ message: groups.length === 1
+ ? `Merged ${groups[0].guids.length} cards into one for ${name(groups[0])}.`
+ : `Merged the cards of ${groups.length} people.`,
+ tone: "done",
+ duration: 10000,
+ action: { label: "Undo", run: () => void undoMerge(kept) },
+ });
+ };
// A list deleted elsewhere is not left open, empty, with nothing to say why.
useEffect(() => {
if (list !== ALL && !lists.some((l) => l.guid === list)) setList(ALL);
@@ -494,11 +614,13 @@ export function ContactsView() {
const saveDraft = useCallback(async () => {
if (!draft) return;
- const saving = draft;
+ // A birthday added and left empty is none.
+ const saving = { ...draft, birthday: draft.birthday || null };
let guid = saving.guid;
// Addresses are written part by part on their own; the rest of the card only if it changed.
+ // A new card's go as additions, queued behind the card itself.
const base = addressBase.current;
- const edits = saving.guid ? addressEdits(base, draftAddresses) : [];
+ const edits = addressEdits(base, draftAddresses);
const after = predicted(base, draftAddresses);
const cardChanged = !saving.guid || JSON.stringify(saving) !== JSON.stringify(draftBase.current);
if (!cardChanged) {
@@ -506,15 +628,16 @@ export function ContactsView() {
if (edits.length) sendAddresses(saving.guid, base, edits, after);
return;
}
- if (edits.length) setAddresses({ guid: saving.guid, list: after });
+ if (edits.length && saving.guid) setAddresses({ guid: saving.guid, list: after });
const ok = await write(async () => {
guid = await api.contactSave(saving, saving.guid ? draftBase.current : null);
});
if (ok) {
setDraft(null);
setOpenGuid(guid);
+ readDupes().catch(() => {});
if (edits.length) sendAddresses(guid, base, edits, after);
- } else if (edits.length) setAddresses({ guid: saving.guid, list: base });
+ } else if (edits.length && saving.guid) setAddresses({ guid: saving.guid, list: base });
}, [draft, draftAddresses, sendAddresses, write]);
/**
@@ -631,6 +754,7 @@ export function ContactsView() {
}
}
setPicked([]);
+ setShowDupes(false);
setOpenGuid(contact.guid);
setDetail(true);
},
@@ -680,7 +804,7 @@ export function ContactsView() {
keys.current = (e: KeyboardEvent) => {
if (!live.current || e.defaultPrevented) return;
// A menu, a picker's list or a sheet open over the screen has the keys to itself.
- if (document.querySelector('[role="menu"], [role="listbox"], [role="dialog"], [role="alertdialog"]')) return;
+ if (overlayOpen()) return;
const target = e.target as HTMLElement | null;
const inSearch = target === searchRef.current;
const typing = !inSearch && !!target?.closest?.("input, textarea, select, [contenteditable]");
@@ -690,7 +814,7 @@ export function ContactsView() {
e.preventDefault();
if (!busy) {
setPicked([]);
- setDraft(blank());
+ startNew();
}
return;
}
@@ -827,7 +951,7 @@ export function ContactsView() {
<header className="pane-head contacts-head">
<PaneTitle count={`${shown.length} ${shown.length === 1 ? "contact" : "contacts"}`}>{openList?.name ?? "Contacts"}</PaneTitle>
<div className="contacts-head-actions">
- <button className="icon-button" aria-label="New contact" title="New Contact" disabled={busy} onClick={() => setDraft(blank())}>
+ <button className="icon-button" aria-label="New contact" title="New Contact" disabled={busy} onClick={startNew}>
<UserPlus size={18} strokeWidth={2} aria-hidden="true" />
</button>
<button
@@ -877,10 +1001,26 @@ export function ContactsView() {
/>
)}
+ {dupes.length > 0 && list === ALL && !search && !showDupes && (
+ <DuplicatesBanner
+ count={dupes.length}
+ onOpen={() => {
+ setPicked([]);
+ setDraft(null);
+ setShowDupes(true);
+ setDetail(true);
+ }}
+ />
+ )}
<div className="contact-rows-wrap">
<ul
className={`contact-rows${listFocused ? " is-focused" : ""}`}
ref={rowsRef}
+ // A list box of people: the open card is the selected option, or every picked one.
+ role="listbox"
+ aria-label="Contacts"
+ aria-multiselectable="true"
+ data-rows=""
// Whether the focus is in the list, for the selection's colour — a class rather than
// :focus-within, which made WebKit restyle every row at each arrow press.
onFocus={() => setListFocused(true)}
@@ -901,7 +1041,7 @@ export function ContactsView() {
{lettered.map(({ contact, letter, starts }) => (
<Fragment key={contact.guid}>
{starts && (
- <li className="contact-letter" data-letter={letter} aria-hidden="true">{letter}</li>
+ <li className="contact-letter" data-letter={letter} role="presentation" aria-hidden="true">{letter}</li>
)}
<ContactRow
contact={contact}
@@ -976,7 +1116,7 @@ export function ContactsView() {
<article className="contact-detail" aria-label="Contact">
{!draft && (
- <button className="compact-back" onClick={() => setDetail(false)}>
+ <button className="compact-back" onClick={() => { setDetail(false); setShowDupes(false); }}>
<ChevronLeft size={18} strokeWidth={2.25} aria-hidden="true" />
<span>Contacts</span>
</button>
@@ -989,62 +1129,106 @@ export function ContactsView() {
void saveDraft();
}}
>
- <h2>{draft.guid ? "Edit contact" : "New contact"}</h2>
-
- <div className="contact-names">
- <label>
- <span>First</span>
- <input
- value={draft.firstName ?? ""}
- autoFocus
- onChange={(e) => setDraft({ ...draft, firstName: e.target.value || null })}
- />
- </label>
- <label>
- <span>Last</span>
- <input
- value={draft.lastName ?? ""}
- onChange={(e) => setDraft({ ...draft, lastName: e.target.value || null })}
- />
- </label>
- <label>
- <span>Company</span>
- <input
- value={draft.company ?? ""}
- onChange={(e) => setDraft({ ...draft, company: e.target.value || null })}
- />
- </label>
+ <div className="contact-form-head">
+ <button
+ type="button"
+ className="contact-photo-edit"
+ aria-label={draft.photoUrl ? "Edit photo" : "Add photo"}
+ onClick={() => setPhotoSheet(true)}
+ >
+ <Avatar contact={draft} large preview={draftPreview} />
+ <span className="contact-photo-badge" aria-hidden="true">
+ <Camera size={13} strokeWidth={2} />
+ </span>
+ </button>
+ <h2>{draft.guid ? "Edit contact" : "New contact"}</h2>
</div>
+ {photoSheet && (
+ <PhotoSheet
+ hasPhoto={!!draft.photoUrl}
+ onCancel={() => setPhotoSheet(false)}
+ onRemove={() => {
+ setPhotoSheet(false);
+ setDraftPreview(null);
+ setDraft({ ...draft, photoUrl: null, photoSignature: null, photoCrop: null });
+ }}
+ onDone={(photo) => {
+ setPhotoSheet(false);
+ setDraftPreview(photo.preview);
+ setDraft({ ...draft, photoUrl: photo.url, photoSignature: null, photoCrop: photo.crop });
+ }}
+ />
+ )}
+
+ {(() => {
+ const shown = (key: NameKey) => shownFields.has(key) || !!draft[key];
+ const field = (key: NameKey | "firstName" | "lastName" | "company", label: string, first?: boolean) => (
+ <label key={key}>
+ <span>{label}</span>
+ <input
+ value={draft[key] ?? ""}
+ autoFocus={first || focusName === key}
+ onChange={(e) => setDraft({ ...draft, [key]: e.target.value || null })}
+ />
+ </label>
+ );
+ // The name as Contacts orders it, each phonetic spelling beside its part; then
+ // the work, on lines of its own.
+ return (
+ <>
+ <div className="contact-names">
+ {shown("prefix") && field("prefix", "Prefix")}
+ {field("firstName", "First", true)}
+ {shown("phoneticFirstName") && field("phoneticFirstName", "Phonetic first")}
+ {shown("middleName") && field("middleName", "Middle")}
+ {field("lastName", "Last")}
+ {shown("phoneticLastName") && field("phoneticLastName", "Phonetic last")}
+ {shown("suffix") && field("suffix", "Suffix")}
+ {shown("nickname") && field("nickname", "Nickname")}
+ </div>
+ <div className="contact-names">
+ {field("company", "Company")}
+ {shown("phoneticCompany") && field("phoneticCompany", "Phonetic company")}
+ {shown("jobTitle") && field("jobTitle", "Job title")}
+ {shown("department") && field("department", "Department")}
+ </div>
+ </>
+ );
+ })()}
<ul className="contact-method-rows">
{draft.methods.map((m, index) =>
// An existing card's addresses are written part by part, below.
m.kind === "address" && draft.guid ? null : !EDITABLE_KINDS.has(m.kind) ? (
- // Shown so it is not a surprise that it exists, but not offered for
- // editing — this app cannot write a structured address back safely.
+ // A new card's address lines, from a vCard: kept as they came.
<li key={index} className="contact-method-fixed">
<span>{KIND_LABEL[m.kind] ?? m.kind}</span>
<span className="contact-address">{m.value}</span>
- <span className="badge">edited on an Apple device</span>
</li>
) : (
<li key={index}>
- <Picker
- label={`Kind of detail ${index + 1}`}
- className="contact-kind"
- value={m.kind}
- onChange={(kind) => editMethod(index, { kind })}
- options={KINDS.map((k) => ({ value: k.value, label: k.label }))}
- />
+ {SWITCHABLE.has(m.kind) ? (
+ <Picker
+ label={`Kind of detail ${index + 1}`}
+ className="contact-kind"
+ value={m.kind}
+ onChange={(kind) => editMethod(index, { kind })}
+ options={KINDS.map((k) => ({ value: k.value, label: k.label }))}
+ />
+ ) : (
+ <span className="contact-kind-fixed">{KIND_LABEL[m.kind] ?? m.kind}</span>
+ )}
{(() => {
- const standard = LABELS[m.kind] ?? [];
- // Apple's names match whatever their case, so "mobile" is the phone's own.
- const match = standard.find((v) => v === m.label?.toUpperCase());
- const custom = customAt.has(index) || (m.label !== null && !match);
+ const standard = OFFERED[m.kind] ?? [];
+ // Apple's names match in either spelling, so "mobile" is the phone's own.
+ const match = offeredMatch(m.kind, m.label);
+ // A service is chosen from Apple's list alone, as icloud.com offers it.
+ const fixedList = m.kind === "im";
+ const custom = !fixedList && (customAt.has(index) || (m.label !== null && !match));
return (
<span className="contact-label-cell">
<Picker
- label={`Label for detail ${index + 1}`}
+ label={`${m.kind === "im" ? "Service" : "Label"} for detail ${index + 1}`}
className="contact-label-pick"
value={custom ? CUSTOM : (match ?? "")}
onChange={(v) => {
@@ -1053,12 +1237,14 @@ export function ContactsView() {
return;
}
setCustomAt((was) => { const next = new Set(was); next.delete(index); return next; });
- editMethod(index, { label: v || null });
+ // The label already on the card, in whichever spelling it came, when
+ // it is the one picked again.
+ editMethod(index, { label: v ? (match === v ? m.label : v) : null });
}}
options={[
...(m.label === null && !custom ? [{ value: "", label: "no label" }] : []),
...standard.map((v) => ({ value: v, label: labelText(v) })),
- { value: CUSTOM, label: "Custom" },
+ ...(fixedList ? [] : [{ value: CUSTOM, label: "Custom" }]),
]}
/>
{custom && (
@@ -1073,13 +1259,24 @@ export function ContactsView() {
</span>
);
})()}
- <input
- className="contact-method-value"
- value={m.value}
- placeholder={m.kind === "email" ? "[email protected]" : "+1 555 0100"}
- aria-label={`Value for detail ${index + 1}`}
- onChange={(e) => editMethod(index, { value: e.target.value })}
- />
+ {m.kind === "date" ? (
+ <DateField
+ compact
+ label={`Date ${index + 1}`}
+ value={m.value || null}
+ autoFocus={focusAt === index}
+ onChange={(v) => editMethod(index, { value: v ?? "" })}
+ />
+ ) : (
+ <input
+ className="contact-method-value"
+ value={m.value}
+ placeholder={PLACEHOLDER[m.kind] ?? ""}
+ aria-label={`Value for detail ${index + 1}`}
+ autoFocus={focusAt === index}
+ onChange={(e) => editMethod(index, { value: e.target.value })}
+ />
+ )}
<button
type="button"
className="quiet danger"
@@ -1091,6 +1288,7 @@ export function ContactsView() {
});
// Places shift up by one; which were being typed is worked out again.
setCustomAt(new Set());
+ setFocusAt(null);
}}
>
✕
@@ -1100,7 +1298,7 @@ export function ContactsView() {
)}
</ul>
- {draft.guid && draftAddresses.length > 0 && (
+ {draftAddresses.length > 0 && (
<ul className="contact-method-rows contact-address-rows" aria-label="Addresses">
{draftAddresses.map((d, i) => (
<AddressEditor
@@ -1126,65 +1324,76 @@ export function ContactsView() {
</ul>
)}
+ {draft.birthday !== null && (
+ <div className="contact-birthday-field">
+ <span className="contact-kind-fixed">birthday</span>
+ <DateField
+ label="Birthday"
+ value={draft.birthday || null}
+ autoFocus={focusName === "birthday"}
+ onChange={(v) => setDraft({ ...draft, birthday: v ?? "" })}
+ />
+ <button
+ type="button"
+ className="quiet danger"
+ aria-label="Remove birthday"
+ onClick={() => setDraft({ ...draft, birthday: null })}
+ >
+ ✕
+ </button>
+ </div>
+ )}
+
<div className="contact-form-adds">
<button
type="button"
className="quiet"
- onClick={() =>
- setDraft({
- ...draft,
- methods: [...draft.methods, { kind: "phone", label: "MOBILE", value: "" }],
- })
- }
+ aria-haspopup="menu"
+ onClick={(e) => {
+ const r = e.currentTarget.getBoundingClientRect();
+ setAddMenu({ x: r.left, y: r.bottom + 4, alignRight: false });
+ }}
>
- Add phone, email or link
+ <Plus size={14} strokeWidth={2} aria-hidden="true" />
+ Add Field
</button>
- {draft.guid && (
- <button
- type="button"
- className="quiet"
- onClick={() => {
- const key = ++addressKey.current;
- setDraftAddresses((all) => [...all, { key, from: null, address: blankAddress() }]);
- setAddedKey(key);
- }}
- >
- Add address
- </button>
- )}
- </div>
-
- <div className="contact-birthday-field">
- <label>
- <span>Birthday</span>
- <input
- type="date"
- aria-label="Birthday"
- value={draft.birthday ? (draft.birthday.startsWith(NO_YEAR) ? `2000${draft.birthday.slice(4, 10)}` : draft.birthday.slice(0, 10)) : ""}
- onChange={(e) => {
- const v = e.target.value;
- if (!v) return setDraft({ ...draft, birthday: null });
- const unknown = draft.birthday?.startsWith(NO_YEAR) ?? false;
- setDraft({ ...draft, birthday: unknown ? `${NO_YEAR}${v.slice(4)}` : v });
- }}
+ {addMenu && (
+ <RowMenu
+ at={addMenu}
+ onClose={() => setAddMenu(null)}
+ entries={[
+ ...ADDABLE.map((a) => ({
+ label: a.label,
+ run: () => {
+ setFocusAt(draft.methods.length);
+ setDraft({ ...draft, methods: [...draft.methods, { kind: a.kind, label: FIRST_LABEL[a.kind] ?? null, value: "" }] });
+ },
+ })),
+ {
+ label: "Address",
+ run: () => {
+ const key = ++addressKey.current;
+ setDraftAddresses((all) => [...all, { key, from: null, address: blankAddress() }]);
+ setAddedKey(key);
+ },
+ },
+ ...(draft.birthday === null
+ ? [{ label: "Birthday", run: () => { setFocusName("birthday"); setDraft({ ...draft, birthday: "" }); } }]
+ : []),
+ ...(() => {
+ const hidden = NAME_FIELDS.filter((f) => !shownFields.has(f.key) && !draft[f.key]);
+ return hidden.length
+ ? [null, ...hidden.map((f) => ({
+ label: f.label.charAt(0).toUpperCase() + f.label.slice(1),
+ run: () => {
+ setFocusName(f.key);
+ setShownFields((was) => new Set(was).add(f.key));
+ },
+ }))]
+ : [];
+ })(),
+ ]}
/>
- </label>
- {draft.birthday && (
- <label className="contact-birthday-noyear">
- <input
- type="checkbox"
- checked={draft.birthday.startsWith(NO_YEAR)}
- onChange={(e) =>
- setDraft({
- ...draft,
- birthday: e.target.checked
- ? `${NO_YEAR}${draft.birthday!.slice(4, 10)}`
- : `${new Date().getFullYear()}${draft.birthday!.slice(4, 10)}`,
- })
- }
- />
- Year unknown
- </label>
)}
</div>
@@ -1205,13 +1414,27 @@ export function ContactsView() {
busy || !(draft.firstName || draft.lastName || draft.company)
}
>
- {busy ? "Saving…" : draft.guid ? "Save" : "Add contact"}
+ {busy ? "Saving" : draft.guid ? "Save" : "Add contact"}
</button>
<button type="button" className="quiet" onClick={() => setDraft(null)}>
Cancel
</button>
</div>
</form>
+ ) : showDupes ? (
+ <DuplicatesView
+ groups={dupes}
+ book={byGuid}
+ Face={Avatar}
+ busy={busy}
+ onMerge={(g) => void mergeGroups([g])}
+ onMergeAll={() => void mergeGroups(dupes)}
+ onShow={(guid) => {
+ setShowDupes(false);
+ setOpenGuid(guid);
+ showRow(guid, false);
+ }}
+ />
) : multi ? (
<div className="contact-many">
<div className="contact-many-faces" aria-hidden="true">
@@ -1257,7 +1480,14 @@ export function ContactsView() {
<div className="contact-head">
<Avatar contact={open} large />
<div className="contact-head-names">
- <h2>{displayName(open)}</h2>
+ {(open.phoneticFirstName || open.phoneticLastName) && (
+ <p className="contact-phonetic">{[open.phoneticFirstName, open.phoneticLastName].filter(Boolean).join(" ")}</p>
+ )}
+ <h2>{fullName(open)}</h2>
+ {open.nickname && <p className="contact-nickname">{`\u201c${open.nickname}\u201d`}</p>}
+ {(open.jobTitle || open.department) && (
+ <p className="contact-company">{[open.jobTitle, open.department].filter(Boolean).join(", ")}</p>
+ )}
{open.company && !open.isCompany && (
<p className="contact-company">{open.company}</p>
)}
@@ -1291,6 +1521,10 @@ export function ContactsView() {
<a href={`tel:${m.value.replace(/[^\d+#*,;]/g, "")}`}>{m.value}</a>
) : m.kind === "url" ? (
<a href={webHref(m.value)}>{m.value}</a>
+ ) : m.kind === "date" ? (
+ dateWords(m.value)
+ ) : m.kind === "profile" && profileHref(m.label, m.value) ? (
+ <a href={profileHref(m.label, m.value)!}>{m.label?.toUpperCase() === "TWITTER" ? `@${m.value.replace(/^@+/, "")}` : m.value}</a>
) : m.kind === "address" ? (
// A postal address is several lines and stays that way.
<>
@@ -1332,7 +1566,7 @@ export function ContactsView() {
{open.birthday && (
<div>
<dt>birthday</dt>
- <dd>{birthdayText(open.birthday)}</dd>
+ <dd>{dateWords(open.birthday)}</dd>
</div>
)}
</dl>
@@ -1346,6 +1580,11 @@ export function ContactsView() {
<button className="quiet" disabled={busy} onClick={() => edit(open)}>
Edit
</button>
+ {lastMerge.includes(open.guid) && outbox.waiting.has(open.guid) && (
+ <button className="quiet" onClick={() => void undoMerge(lastMerge)}>
+ Undo Merge
+ </button>
+ )}
<button
className="quiet"
aria-haspopup="menu"
@@ -1401,6 +1640,7 @@ const ContactRow = memo(function ContactRow({ contact, current, mine, draggable,
}) {
return (
<li
+ role="presentation"
// Dragged onto a list, a person joins it — as in Contacts on the Mac.
draggable={draggable}
onDragStart={(e) => actions.dragStart(contact, e)}
@@ -1409,8 +1649,9 @@ const ContactRow = memo(function ContactRow({ contact, current, mine, draggable,
>
<button
className="contact-row"
+ role="option"
data-guid={contact.guid}
- aria-current={current}
+ aria-selected={current}
onClick={(e) => actions.click(contact, e)}
>
<Avatar contact={contact} />
@@ -1540,17 +1781,6 @@ function NameField({ initial, label, onDone, onCancel }: {
);
}
-/** The year Apple writes for a birthday given without one. */
-const NO_YEAR = "1604";
-
-/** "17 March", or "17 March 1998" when the year is known — as a contact card shows it. */
-function birthdayText(raw: string): string {
- const [y, m, d] = raw.slice(0, 10).split("-").map(Number);
- if (!m || !d) return raw;
- const date = new Date(y === Number(NO_YEAR) ? 2000 : y, m - 1, d);
- return dateText(date, y === Number(NO_YEAR) ? { day: "numeric", month: "long" } : { dateStyle: "long" });
-}
-
/**
* The order Contacts keeps: by last name, then first — a company by its name — letters
* before anything else, accents and case aside, and a card with no name at all ("#") last.
@@ -1632,7 +1862,7 @@ const PART_NAME: Record<(typeof ADDRESS_PARTS)[number], string> = {
postalCode: "Postcode",
country: "Country",
};
-const ADDRESS_LABELS = ["HOME", "WORK", "OTHER"];
+const ADDRESS_LABELS = OFFERED.address;
const ALL_PARTS: AddressPart[] = ["street", "subLocality", "city", "subAdministrativeArea", "state", "postalCode", "country", "countryCode"];
const blankAddress = (): PostalAddress => ({
diff --git a/src/screens/DriveView.tsx b/src/screens/DriveView.tsx
index e24883c..87da50b 100644
--- a/src/screens/DriveView.tsx
+++ b/src/screens/DriveView.tsx
@@ -1,5 +1,5 @@
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { useActiveRef, useScreenActive } from "../lib/screen";
+import { overlayOpen, useActiveRef, useScreenActive } from "../lib/screen";
import { useModalFocus } from "../lib/focus";
import { useSync } from "../lib/sync";
import { toastSaved, useErrorToast } from "../components/Toast";
@@ -569,8 +569,12 @@ export function DriveView() {
// back to the previous location".
const hereRef = useRef(here.id);
hereRef.current = here.id;
- /** Items deleted here that Apple's listing may still carry for a moment after. */
+ /** Items deleted or moved out of a folder that Apple's listing of it may still carry for a
+ * moment after — each kept as "folder:item", so it is hidden only in the folder it left.
+ * By item alone, an item moved into another folder, or recovered from Recently Deleted,
+ * stayed hidden everywhere until the app restarted. */
const [gone, setGone] = useState<Set<string>>(new Set());
+ const goneKey = (folder: string, item: string) => `${folder}:${item}`;
// A folder load is asynchronous and the id it was for is not always the one still on
// screen by the time it resolves — a fast double click used to let a second, third,
@@ -668,8 +672,8 @@ export function DriveView() {
}, []);
// Apple sends no push for iCloud Drive (measured: none in 25 s for a folder made or
// deleted), and icloud.com reads a folder only as it is opened. The folder in front is
- // checked again every ten seconds while the window shows it, and at once when the window
- // comes back — one small request; none while hidden — so a file saved on the phone appears
+ // checked again every ten seconds while the window has the focus, and at once when the
+ // window comes back — one small request; none while hidden or in the background — so a file saved on the phone appears
// here as it would in Finder.
const shown = useScreenActive();
const shownNow = useRef(shown);
@@ -681,7 +685,12 @@ export function DriveView() {
const look = () => {
if (document.visibilityState === "visible" && !writingRef.current) void refresh();
};
- const t = window.setInterval(look, 10_000);
+ // The timed check only while the window has the focus: one merely open behind another, or
+ // on another workspace, asked Apple every ten seconds all day for a folder nobody was
+ // looking at. Coming back to it (focus) looks at once, so nothing is missed.
+ const t = window.setInterval(() => {
+ if (document.hasFocus()) look();
+ }, 10_000);
document.addEventListener("visibilitychange", look);
window.addEventListener("focus", look);
return () => {
@@ -755,7 +764,8 @@ export function DriveView() {
async (list: DriveItem[]) => {
if (list.length === 0) return;
setError(null);
- const ids = list.map((i) => i.drivewsid);
+ const from = hereRef.current;
+ const ids = list.map((i) => goneKey(from, i.drivewsid));
setGone((g) => new Set([...g, ...ids]));
const refused: string[] = [];
let reason = "";
@@ -780,7 +790,7 @@ export function DriveView() {
if (refused.length) {
setGone((g) => {
const next = new Set(g);
- for (const id of refused) next.delete(id);
+ for (const id of refused) next.delete(goneKey(from, id));
return next;
});
setError(list.length === 1 ? reason : `${refused.length} of ${list.length} items could not be deleted: ${reason}`);
@@ -820,7 +830,8 @@ export function DriveView() {
const going = list.filter((i) => i.drivewsid !== destinationId);
if (going.length === 0) return;
// Out of this folder at once; back, with the reason, if Apple refuses.
- setGone((g) => new Set([...g, ...going.map((i) => i.drivewsid)]));
+ const from = hereRef.current;
+ setGone((g) => new Set([...g, ...going.map((i) => goneKey(from, i.drivewsid))]));
const refused: string[] = [];
let reason = "";
for (const item of going) {
@@ -834,7 +845,7 @@ export function DriveView() {
if (refused.length) {
setGone((g) => {
const next = new Set(g);
- for (const id of refused) next.delete(id);
+ for (const id of refused) next.delete(goneKey(from, id));
return next;
});
setError(going.length === 1 ? reason : `${refused.length} of ${going.length} items could not be moved: ${reason}`);
@@ -1099,8 +1110,8 @@ export function DriveView() {
/** The rows as shown, sorted once per change to what is here or to the order. */
const rows = useMemo(
- () => sortItems(items.filter((item) => !gone.has(item.drivewsid)), sortBy, reversed),
- [items, gone, sortBy, reversed],
+ () => sortItems(items.filter((item) => !gone.has(goneKey(here.id, item.drivewsid))), sortBy, reversed),
+ [items, gone, sortBy, reversed, here.id],
);
const pickedItems = useMemo(() => rows.filter((r) => picked.includes(r.drivewsid)), [rows, picked]);
const primary = useMemo(() => (selected ? rows.find((r) => r.drivewsid === selected) ?? null : null), [rows, selected]);
@@ -1201,7 +1212,7 @@ export function DriveView() {
if (renaming || creatingFolder || moving || info) return;
const target = e.target as HTMLElement | null;
if (target?.closest?.("input, textarea, select, [contenteditable], .drive-bar, .upload-menu")) return;
- if (!peeking && document.querySelector('[role="menu"], [role="listbox"], [role="dialog"], [role="alertdialog"]')) return;
+ if (!peeking && overlayOpen()) return;
// Return and Space press a focused button of their own; on a row or nowhere, they are Drive's.
// A row's ⋯ is a button of its own inside the rows: Return there opens its menu, not the file.
const ownButton = !!target?.closest?.("button, a[href]") && !target?.closest?.(".drive-row-hit");
@@ -1343,7 +1354,7 @@ export function DriveView() {
<span className="drive-count" aria-live="polite">
{loaded
? (() => {
- const n = items.filter((x) => !gone.has(x.drivewsid)).length;
+ const n = items.filter((x) => !gone.has(goneKey(here.id, x.drivewsid))).length;
return `${n} item${n === 1 ? "" : "s"}${available ? `, ${available} available` : ""}`;
})()
: "\u00a0"}
diff --git a/src/screens/Library.tsx b/src/screens/Library.tsx
index 80c098b..fdded5f 100644
--- a/src/screens/Library.tsx
+++ b/src/screens/Library.tsx
@@ -1,4 +1,4 @@
-import { ToastHost } from "../components/Toast";
+import { ToastHost, toast } from "../components/Toast";
import { EmptyState } from "../components/EmptyState";
import { StatusLine } from "../components/StatusLine";
import { lazy, Suspense, useEffect, useLayoutEffect, useRef, useState } from "react";
@@ -52,6 +52,7 @@ import { ScreenBoundary } from "../components/ScreenBoundary";
import { ScreenActive } from "../lib/screen";
import { AppIcon } from "../components/AppIcon";
import { GlobalSearch } from "../components/GlobalSearch";
+import { ShortcutsSheet } from "../components/ShortcutsSheet";
/**
* What the sidebar holds: the services with a real screen behind them, most used first.
@@ -96,6 +97,55 @@ function UpdateKeys({ screen }: { screen: string | null }) {
return null;
}
+/**
+ * Ctrl+, opens Settings and Ctrl+/ (or Ctrl+?) the Keyboard Shortcuts sheet, from any app —
+ * as ⌘, and the Help menu's shortcuts do on a Mac. Typing in a field keeps its own Ctrl+/.
+ */
+function AppKeys({ screen, onSettings }: { screen: string | null; onSettings: () => void }) {
+ const [sheet, setSheet] = useState(false);
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ if (!(e.ctrlKey || e.metaKey) || e.altKey || e.defaultPrevented) return;
+ if (e.key === ",") {
+ e.preventDefault();
+ onSettings();
+ } else if (e.key === "/" || e.key === "?") {
+ e.preventDefault();
+ setSheet(true);
+ }
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [onSettings]);
+ return sheet ? <ShortcutsSheet front={screen} onClose={() => setSheet(false)} /> : null;
+}
+
+/**
+ * The first time a library arrives on this computer, one line on what to try: change
+ * something on the phone and watch it land here — the moment that shows what Skykeep is.
+ * Once per computer, only for a library that had nothing synced when the window opened.
+ */
+const FIRST_HINT_KEY = "quince.firstSyncHint";
+function FirstSyncHint() {
+ const { report } = useSync();
+ const startedEmpty = useRef<boolean | null>(null);
+ useEffect(() => {
+ if (!report) return;
+ const synced = report.services.some((s) => s.lastSyncedAt);
+ if (startedEmpty.current === null) startedEmpty.current = !synced;
+ if (!startedEmpty.current || !synced) return;
+ startedEmpty.current = false;
+ try {
+ if (window.localStorage.getItem(FIRST_HINT_KEY)) return;
+ window.localStorage.setItem(FIRST_HINT_KEY, "1");
+ } catch {
+ return;
+ }
+ toast({ message: "Your iCloud is here. Edit a reminder or note on your iPhone and watch it change here in seconds.", duration: 9000 });
+ }, [report]);
+ return null;
+}
+
/*
* A result picked in the desktop's own search (GNOME Shell, KRunner) arrives as an event for
* this window: the item is handed to its screen (which takes it when it is up), and the
@@ -350,6 +400,8 @@ export function Library({ onSignOut }: { onSignOut: (keep: boolean) => Promise<v
return (
<SyncProvider>
<UpdateKeys screen={selected} />
+ <AppKeys screen={selected} onSettings={() => choose("settings")} />
+ <FirstSyncHint />
<div className={`library enter-library${sidebarOpen ? " is-sidebar-open" : ""}${rail ? " is-rail" : ""}`}>
{/* Only in a narrow window, where the sidebar gives its room to the content. */}
<button
diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsx
index 60db486..57c7814 100644
--- a/src/screens/NotesView.tsx
+++ b/src/screens/NotesView.tsx
@@ -7,18 +7,19 @@ import { SearchField } from "../components/SearchField";
import { PaneTitle } from "../components/PaneTitle";
import { Unsent, Waiting } from "../components/Unsent";
import { useOutbox } from "../lib/outbox";
-import { ChevronLeft, Folder, FolderOpen, FolderPlus, ListChecks, LockKeyhole, LockKeyholeOpen, Paperclip, Pin, PinOff, Share, SquarePen, Trash2 } from "lucide-react";
+import { ArrowDownUp, ChevronLeft, Folder, FolderOpen, FolderPlus, ListChecks, LockKeyhole, LockKeyholeOpen, Paperclip, Pin, PinOff, Share, SquarePen, Trash2 } from "lucide-react";
import { pickOpen, pickSave } from "../lib/pick";
import { getCurrentWebview } from "@tauri-apps/api/webview";
-import { editorDate, groupNotes, listDate, mergeEdits, splitTitle } from "./notes/model";
+import { DEFAULT_ORDER, editorDate, groupNotes, listDate, mergeEdits, splitTitle, type NoteOrder } from "./notes/model";
import { api, messageOf, nestFolders, notesLockApi, type Note, type NoteFolder, type UnlockedNote } from "../lib/ipc";
import { LockScreen } from "./notes/LockedNote";
import { fileName, useAttachEnabled } from "./notes/attach";
import { toast } from "../components/Toast";
-import { useActiveRef } from "../lib/screen";
+import { overlayOpen, useActiveRef } from "../lib/screen";
import { RowMenu } from "../components/RowMenu";
+import { Spinner } from "../components/Spinner";
import { FormattedBody, type Run } from "./notes/Formatted";
-import { carryRuns, runsFit } from "./notes/rich";
+import { carryRuns, runsFit, sameFormatting } from "./notes/rich";
import { NoteEditor, refreshTables, type EditorHandle, type EditorStatus } from "./notes/NoteEditor";
import { FormatPanel } from "./notes/FormatPanel";
import { NotePicture } from "./notes/NotePicture";
@@ -106,6 +107,26 @@ export function NotesView() {
if (fit) setFoldersWidth(Math.max(208, Math.min(fit, 320)));
}, [folders]);
const [folderMenu, setFolderMenu] = useState<{ folder: NoteFolder; x: number; y: number; alignRight: boolean } | null>(null);
+ // How the list is ordered (View menu), kept on this computer: a convenience, so a storage
+ // that is missing or full only means the default order.
+ const [listOrder, setListOrder] = useState<NoteOrder>(() => {
+ try {
+ const kept = JSON.parse(localStorage.getItem("notes.order") ?? "null");
+ if (kept && ["edited", "created", "title"].includes(kept.by) && typeof kept.groupByDate === "boolean") return kept;
+ } catch {
+ /* the default */
+ }
+ return DEFAULT_ORDER;
+ });
+ const orderBy = (next: NoteOrder) => {
+ setListOrder(next);
+ try {
+ localStorage.setItem("notes.order", JSON.stringify(next));
+ } catch {
+ /* kept for this session only */
+ }
+ };
+ const [viewMenu, setViewMenu] = useState<{ x: number; y: number; alignRight: boolean } | null>(null);
const [renamingFolder, setRenamingFolder] = useState<string | null>(null);
const [folder, setFolder] = useState<string>(ALL);
const [notes, setNotes] = useState<Note[]>([]);
@@ -350,7 +371,9 @@ export function NotesView() {
let cancelled = false;
api.noteRuns(openGuid).then(
(runs) => { if (!cancelled) setLoadedRuns({ guid: openGuid, runs: Array.isArray(runs) ? runs : [] }); },
- () => {},
+ // Unreadable formatting still opens the note — as text only (formatSafe stays false),
+ // which saves the words and leaves Apple's formatting as it is.
+ () => { if (!cancelled) setLoadedRuns((cur) => (cur?.guid === openGuid ? cur : { guid: openGuid, runs: [] })); },
);
return () => { cancelled = true; };
}, [openGuid, revision, outbox.tick]);
@@ -368,6 +391,9 @@ export function NotesView() {
const editorRef = useRef<EditorHandle | null>(null);
/** A new note's id once it is made, so the editor it was typed in stays the one shown. */
const adoptedKey = useRef<string | null>(null);
+ /** Which New Note this is: each gets an editor of its own, so a second New Note can never
+ * start out holding the first one's text (and save it again as a copy). */
+ const composeSeq = useRef(0);
/** The formatting on screen now, beside `draft` — the text on screen now. */
const draftRuns = useRef<Run[] | null>(null);
@@ -458,8 +484,10 @@ export function NotesView() {
setEdits((n) => n + 1);
setSaved(false);
// Compared only when the text is back to what Apple holds — never on an ordinary key,
- // which in a long note would be a second walk of the whole thing per keystroke.
- const unchanged = typed === body && (!formatSafe || JSON.stringify(typedRuns) === JSON.stringify(runs));
+ // which in a long note would be a second walk of the whole thing per keystroke. The
+ // formatting is compared as formatting, not as runs: Apple's come in pieces where the
+ // editor's are merged, and that difference alone queued a save of a note only opened.
+ const unchanged = typed === body && (!formatSafe || sameFormatting(typed, typedRuns, runs));
pending.current = unchanged ? null : { guid: open.guid, body: typed, runs: formatSafe ? typedRuns : null };
},
[open, body, runs, formatSafe]
@@ -561,6 +589,12 @@ export function NotesView() {
setDraft(latest);
setEdits((n) => n + 1);
pending.current = { guid, body: latest, runs: typedRuns };
+ // Its formatting known from the start — what was set while composing, or the title line
+ // Notes gives a new note — so the editor writes formatting from the first key. Without
+ // it a key typed before the first save dropped the title, and every save after was
+ // words only, so what was set here never reached Apple.
+ const plain: Run = { length: latest.length, style: null, indent: 0, checked: null, bold: false, italic: false, underline: false, strike: false, link: null };
+ setLoadedRuns({ guid, runs: typedRuns ?? titled(latest, latest.length ? [plain] : []) });
// In the list at once, so the note is open — and its editor still there — before the
// list is read again.
const now = Math.floor(Date.now() / 1000);
@@ -601,6 +635,8 @@ export function NotesView() {
const create = useCallback(async () => {
if (composingRef.current) await commitComposing();
await flush();
+ composeSeq.current += 1;
+ adoptedKey.current = null;
setComposing({ folderGuid: folder === ALL ? null : folder, body: "" });
setOpenGuid(null);
setDetail(true);
@@ -680,12 +716,12 @@ export function NotesView() {
const gone = open.guid;
// The note below opens in its place, or the one above at the end, as in Notes: the order
// is the list's as shown, pinned notes first.
- const order = groupNotes(notes).flatMap((g) => g.notes.map((n) => n.guid));
+ const order = groupNotes(notes, new Date(), listOrder).flatMap((g) => g.notes.map((n) => n.guid));
const at = order.indexOf(gone);
const next = order[at + 1] ?? order[at - 1] ?? null;
setOpenGuid(next);
await write(() => api.noteDelete(gone), (rows) => rows.filter((n) => n.guid !== gone));
- }, [open, write, notes, confirm]);
+ }, [open, write, notes, confirm, listOrder]);
/** Out of Recently Deleted and back into Notes — Apple's "Notes" folder where there is one. */
const recover = useCallback(async () => {
@@ -740,6 +776,9 @@ export function NotesView() {
*/
const attachOn = useAttachEnabled();
const [attaching, setAttaching] = useState(false);
+ /** Files on their way into the note, shown at once with a picture of each where there is
+ * one — beside the text, never in it, so nothing half-added is ever saved. */
+ const [adding, setAdding] = useState<{ name: string; src: string | null }[]>([]);
const [dropping, setDropping] = useState(false);
const attach = useCallback(
async (paths: string[]) => {
@@ -752,6 +791,20 @@ export function NotesView() {
let text = shown?.text ?? body;
let at = editorRef.current?.caret() ?? text?.length ?? 0;
setAttaching(true);
+ setAdding(paths.map((p) => ({ name: fileName(p), src: null })));
+ // Each file's picture, made on this computer while it uploads (a moment for a photo).
+ const previews: string[] = [];
+ paths.forEach((p, i) =>
+ void notesLockApi
+ .noteAttachPreview(p)
+ .then((buf) => {
+ if (!buf || buf.byteLength === 0) return;
+ const src = URL.createObjectURL(new Blob([buf]));
+ previews.push(src);
+ setAdding((list) => list.map((x, j) => (j === i ? { ...x, src } : x)));
+ })
+ .catch(() => {}),
+ );
try {
for (const path of paths) {
const added = await notesLockApi.noteAttachFile(guid, path, at, text);
@@ -768,6 +821,8 @@ export function NotesView() {
setError(messageOf(e));
} finally {
setAttaching(false);
+ setAdding([]);
+ previews.forEach((u) => URL.revokeObjectURL(u));
}
},
[open, flush, body, read]
@@ -827,7 +882,10 @@ export function NotesView() {
return () => window.clearTimeout(timer);
}, [saved]);
- const canEdit = Boolean(composing) || Boolean(open && !open.locked && open.editable && body !== null);
+ // Editable once the words AND their formatting are in. Opened on the words alone, the editor
+ // came up plain; a key typed before the formatting arrived was then saved as the note's
+ // formatting, and took its titles, checklists and bold off every device.
+ const canEdit = Boolean(composing) || Boolean(open && !open.locked && open.editable && body !== null && runs !== null);
const canAttach = attachOn && !composing && !inTrash && Boolean(open && !open.locked && open.editable && body !== null);
canAttachRef.current = canAttach;
@@ -857,7 +915,7 @@ export function NotesView() {
/** Up and Down through the list as it is shown, pinned notes first. */
const step = useCallback(
(by: 1 | -1) => {
- const order = groupNotes(notes).flatMap((g) => g.notes.map((n) => n.guid));
+ const order = groupNotes(notes, new Date(), listOrder).flatMap((g) => g.notes.map((n) => n.guid));
if (order.length === 0) return;
const at = openGuid ? order.indexOf(openGuid) : -1;
const next = at < 0 ? order[0] : order[Math.max(0, Math.min(order.length - 1, at + by))];
@@ -865,7 +923,7 @@ export function NotesView() {
if (next !== openGuid) void selectNote(next);
focusRow(next);
},
- [notes, openGuid, selectNote]
+ [notes, openGuid, selectNote, listOrder]
);
/** Into the search field: this folder (Ctrl+F) or every folder (Ctrl+Shift+F). */
@@ -890,7 +948,7 @@ export function NotesView() {
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (!live.current || e.defaultPrevented || e.isComposing) return;
- if (document.querySelector('[role="menu"], [role="dialog"], [role="alertdialog"], [role="listbox"], .confirm')) return;
+ if (overlayOpen()) return;
const target = e.target as HTMLElement | null;
const typing = Boolean(target?.closest?.("input, textarea, select, [contenteditable='true']"));
const mod = (e.ctrlKey || e.metaKey) && !e.altKey;
@@ -981,7 +1039,7 @@ export function NotesView() {
// Another folder is another list, and a narrow window shows that list, not a note from the last.
useEffect(() => setDetail(false), [folder]);
- const sections = useMemo(() => groupNotes(notes), [notes]);
+ const sections = useMemo(() => groupNotes(notes, new Date(), listOrder), [notes, listOrder]);
const heading = searching
? "Search"
: folder === ALL
@@ -1127,6 +1185,33 @@ export function NotesView() {
<section className="notes-list" aria-label="Notes">
<header className="pane-head notes-list-head">
<PaneTitle count={`${notes.length} ${notes.length === 1 ? "note" : "notes"}`}>{heading}</PaneTitle>
+ <button
+ className="icon-button"
+ aria-label="View Options"
+ title="View Options"
+ aria-haspopup="menu"
+ aria-expanded={!!viewMenu}
+ onClick={(e) => {
+ const r = e.currentTarget.getBoundingClientRect();
+ setViewMenu({ x: r.right, y: r.bottom + 4, alignRight: true });
+ }}
+ >
+ <ArrowDownUp size={17} strokeWidth={2} aria-hidden="true" />
+ </button>
+ {viewMenu && (
+ <RowMenu
+ at={viewMenu}
+ onClose={() => setViewMenu(null)}
+ entries={[
+ { label: "Date Edited", checked: listOrder.by === "edited", run: () => orderBy({ ...listOrder, by: "edited" }) },
+ { label: "Date Created", checked: listOrder.by === "created", run: () => orderBy({ ...listOrder, by: "created" }) },
+ { label: "Title", checked: listOrder.by === "title", run: () => orderBy({ ...listOrder, by: "title" }) },
+ ...(listOrder.by === "title"
+ ? []
+ : [null, { label: "Group By Date", checked: listOrder.groupByDate, run: () => orderBy({ ...listOrder, groupByDate: !listOrder.groupByDate }) }]),
+ ]}
+ />
+ )}
<button
className="icon-button"
aria-label="New note"
@@ -1187,18 +1272,20 @@ export function NotesView() {
<Unsent refused={outbox.refused} what="an edit to a note" onResend={(r) => void outbox.resend(r)} onDiscard={(r) => void outbox.discard(r)} />
- <div className="note-rows" ref={rowsRef}>
+ {/* One list box of notes, a group per heading: the open note is its selected option.
+ The heading is drawn for the eye; the group's name says it to a screen reader. */}
+ <div className="note-rows" ref={rowsRef} role="listbox" aria-label="Notes" data-rows="">
{sections.map((section) => (
<Fragment key={section.key}>
- <h2 className="notes-section">{section.heading}</h2>
- {/* A list per heading: a list holds its items and nothing else. */}
- <div role="list" aria-label={section.heading}>
+ <div className="notes-section" aria-hidden="true">{section.heading}</div>
+ <div role="group" aria-label={section.heading}>
{section.notes.map((note) => (
- <div role="listitem" key={note.guid}>
+ <div role="presentation" className="note-item" key={note.guid}>
<button
className="note-row"
+ role="option"
data-guid={note.guid}
- aria-current={openGuid === note.guid}
+ aria-selected={openGuid === note.guid}
onClick={(e) => {
pickedBy.current = e.detail > 0 ? "pointer" : "keys";
// A locked note clicked again, already open: on into its password field.
@@ -1418,6 +1505,7 @@ export function NotesView() {
* saved is always the two put back together.
*/}
{canEdit ? (
+ <>
<div className="note-editor"
onKeyDown={(e) => {
if ((e.metaKey || e.ctrlKey) && e.key === "s") {
@@ -1428,11 +1516,11 @@ export function NotesView() {
>
<NoteEditor
// One editor per note, so nothing typed in one can be shown in another.
- key={composing || (open && adoptedKey.current === open.guid) ? "composing" : open?.guid}
+ key={composing || (open && adoptedKey.current === open.guid) ? `composing-${composeSeq.current}` : open?.guid}
ref={editorRef}
text={composing ? composing.body : (draft ?? body ?? "")}
runs={composing ? draftRuns.current : formatSafe ? runs : null}
- editable
+ editable={!attaching}
autoFocus={Boolean(composing)}
label={composing ? "New note" : `${open?.title ?? "Note"}`}
placeholder={composing ? "New Note" : undefined}
@@ -1441,6 +1529,30 @@ export function NotesView() {
onBlur={leave}
/>
</div>
+ {attaching && (
+ // The note waits while a file goes in, so nothing typed meanwhile is lost when
+ // it comes back from Apple with the file in place.
+ <div className="note-adding" role="status" aria-live="polite">
+ <div className="note-adding-card">
+ {adding.map((f, i) => (
+ <div className="note-adding-file" key={`${f.name}-${i}`}>
+ {f.src ? (
+ <img className="note-adding-thumb" src={f.src} alt="" draggable={false} />
+ ) : (
+ <span className="note-adding-thumb is-file" aria-hidden="true">
+ <Paperclip size={18} strokeWidth={2} />
+ </span>
+ )}
+ <span className="note-adding-name">{f.name}</span>
+ </div>
+ ))}
+ <span className="note-adding-state">
+ <Spinner small /> Adding to the note
+ </span>
+ </div>
+ </div>
+ )}
+ </>
) : open?.locked && opened ? (
/* Opened with its password: read here, written on an Apple device. */
<div className="note-editor is-readonly is-unlocked">
diff --git a/src/screens/PhotosView.tsx b/src/screens/PhotosView.tsx
index e8ce811..e3c8355 100644
--- a/src/screens/PhotosView.tsx
+++ b/src/screens/PhotosView.tsx
@@ -4,7 +4,7 @@
* from the disk cache and are fetched once.
*/
import { useActiveRef, useScreenActive } from "../lib/screen";
-import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import { listen } from "@tauri-apps/api/event";
import { getCurrentWebview } from "@tauri-apps/api/webview";
import { pickOpen } from "../lib/pick";
@@ -17,6 +17,8 @@ import {
PHOTO_UPLOAD,
type Photo,
type PhotoAlbum,
+ type PhotoOrder,
+ type PhotoSource,
type PhotoView,
type UploadEvent,
turnStyle,
@@ -41,6 +43,7 @@ import { DownloadOptions, type Want } from "./photos/DownloadOptions";
import { AdjustDate } from "./photos/AdjustDate";
import { useReveal } from "../lib/reveal";
import { Picker } from "../components/Picker";
+import { PAGE, PhotoList, PhotoStore } from "./photos/list";
/** The sidebar, in Photos' order, each with the symbol Photos gives it. */
const VIEWS: { key: PhotoView; label: string; Icon: LucideIcon }[] = [
@@ -87,9 +90,9 @@ const AlbumGlyph = () => (
);
/** "3 Photos Selected", "1 Video Selected", "5 Items Selected" — Photos' words. */
-const pickedWords = (list: Photo[]) => {
- const videos = list.filter((p) => p.kind === "video").length;
- const n = list.length;
+const pickedWords = (kinds: Photo["kind"][]) => {
+ const videos = kinds.filter((k) => k === "video").length;
+ const n = kinds.length;
const noun = videos === 0 ? "Photo" : videos === n ? "Video" : "Item";
return `${n.toLocaleString()} ${n === 1 ? noun : `${noun}s`} Selected`;
};
@@ -104,8 +107,6 @@ type Sort = { by: "taken" | "added"; oldest: boolean };
const SORTS_KEY = "quince.photos.sort";
const defaultSort = (view: PhotoView): Sort => ({ by: view === "recents" ? "added" : "taken", oldest: false });
const sortKey = (p: Photo, by: Sort["by"]) => (by === "added" ? (p.addedAt ?? p.takenAt) : p.takenAt);
-const sortList = (list: Photo[], s: Sort) =>
- [...list].sort((a, b) => (sortKey(b, s.by) - sortKey(a, s.by)) * (s.oldest ? -1 : 1) || (a.id < b.id ? -1 : 1));
const readSorts = (): Partial<Record<PhotoView, Sort>> => {
try {
return JSON.parse(window.localStorage.getItem(SORTS_KEY) ?? "{}") ?? {};
@@ -132,40 +133,6 @@ const clock = (s: number | null) => {
return `${m}:${String(Math.round(s % 60)).padStart(2, "0")}`;
};
-/** Whether two reads of one photo are the same in every field. */
-function samePhoto(a: Photo, b: Photo): boolean {
- for (const k in b) {
- const x = (a as Record<string, unknown>)[k];
- const y = (b as Record<string, unknown>)[k];
- if (x === y) continue;
- if (Array.isArray(x) && Array.isArray(y) && x.length === y.length && x.every((v, i) => v === y[i])) continue;
- return false;
- }
- return true;
-}
-
-/**
- * A fresh read laid over the last one: each photo unchanged keeps the object it had, and a list
- * unchanged throughout is the last list itself. Every pass, and each service landing in one,
- * reads the library again; a read that came back new objects for the same photos drew every
- * month and every tile of the grid again for nothing.
- */
-function keepSame(before: Photo[] | null, read: Photo[]): Photo[] {
- if (!before || before.length === 0) return read;
- const had = new Map(before.map((p) => [p.id, p]));
- let same = before.length === read.length;
- const out = read.map((p, i) => {
- const old = had.get(p.id);
- if (old && samePhoto(old, p)) {
- if (before[i] !== old) same = false;
- return old;
- }
- same = false;
- return p;
- });
- return same ? before : out;
-}
-
/** A photo's frame when fitted: its own shape, as large as the square cell lets it be. */
const fitFrame = (p: Photo): React.CSSProperties =>
p.width >= p.height
@@ -181,7 +148,7 @@ const SLIP = 26;
const SHOWN = 54;
const GAP = 2;
const REACH = 30;
-function Filmstrip({ photos, at, onPick }: { photos: Photo[]; at: number; onPick: (index: number) => void }) {
+function Filmstrip({ photos, at, onPick }: { photos: PhotoList; at: number; onPick: (index: number) => void }) {
// Enough either side to fill the window's width and more, so a slip is always built (and its
// picture decoded) before it can be seen: built at the edge of the screen, slips came in
// blank and filled in as each step was taken.
@@ -191,12 +158,20 @@ function Filmstrip({ photos, at, onPick }: { photos: Photo[]; at: number; onPick
// Each slip has its place by its index in the whole library, so the slips built as the
// window moves along never jump; the strip is placed to put the shown one's centre in the middle.
const shift = -(at * (SLIP + GAP) + SHOWN / 2);
+ // The slips' photos on their way; one not here yet holds its place as an empty slip.
+ useEffect(() => void photos.need(from, to), [photos, from, to]);
const slips = [];
for (let i = from; i <= to; i++) {
- const p = photos[i];
+ const p = photos.at(i);
+ const place = { transform: `translateX(${i * (SLIP + GAP) + (i > at ? SHOWN - SLIP : 0)}px)` };
+ if (!p) {
+ slips.push(<span key={photos.ids[i]} className="px-slip is-waiting" style={place} aria-hidden="true" />);
+ continue;
+ }
slips.push(
<button
key={p.id}
+ data-id={p.id}
className={`px-slip${i === at ? " is-shown" : ""}`}
// Placed by transform, eased with its neighbours: the shown one widens as they make
// room, all on the compositor — before, each step jumped every slip into place.
@@ -251,6 +226,20 @@ function viewSrc(p: Photo): string {
const w = Math.min(box.w, box.h * r, (p.width || 4000) * 1.5);
return fitSrc(p.id, Math.max(w, w / r) * (window.devicePixelRatio || 1));
}
+/**
+ * A small picture of a photo the window has already got and decoded — the grid's tile or the
+ * strip's slip, whichever is on the page — to paint under the viewer's picture until that is
+ * decoded. Apple's thumbnail by its own address was a picture not yet fetched: on opening, the
+ * stage showed empty (black in the dark) for the frames it took to come.
+ */
+function loadedThumb(id: string): string {
+ const esc = typeof CSS !== "undefined" && CSS.escape ? CSS.escape(id) : id;
+ for (const sel of [`.px-slip[data-id="${esc}"] img`, `.px-tile[data-id="${esc}"] img`]) {
+ const img = document.querySelector<HTMLImageElement>(sel);
+ if (img && img.complete && img.naturalWidth) return img.currentSrc || img.src;
+ }
+ return pictureSrc(id, "thumb");
+}
function warm(p: Photo): Promise<boolean> {
const url = viewSrc(p);
if (decoded.has(url)) return Promise.resolve(true);
@@ -435,10 +424,10 @@ function changedBetween(from: Set<string>, to: Set<string>): string[] {
}
/** A month's photo ids, made once per list of them. */
const monthIds = new WeakMap<object, Set<string>>();
-function idsOf(items: { photo: Photo }[]): Set<string> {
+function idsOf(items: Item[]): Set<string> {
let ids = monthIds.get(items);
if (!ids) {
- ids = new Set(items.map((x) => x.photo.id));
+ ids = new Set(items.map((x) => x.id));
monthIds.set(items, ids);
}
return ids;
@@ -450,7 +439,7 @@ function idsOf(items: { photo: Photo }[]): Set<string> {
* month again — every one was handed the whole selection — 166 ms on a 20,000-photo library.
*/
function sameMonth(a: MonthProps, b: MonthProps): boolean {
- if (a.label !== b.label || a.month !== b.month || a.items !== b.items || a.deleted !== b.deleted || a.eager !== b.eager || a.across !== b.across
+ if (a.label !== b.label || a.month !== b.month || a.items !== b.items || a.list !== b.list || a.deleted !== b.deleted || a.eager !== b.eager || a.across !== b.across
|| a.fit !== b.fit || a.cell !== b.cell || a.act !== b.act) return false;
if (a.chosen !== b.chosen) {
// Only the photos whose selection changed are looked at (worked out once per change, not
@@ -495,10 +484,14 @@ function buildNext() {
if (builds.length) buildFrame = requestAnimationFrame(buildNext);
}
+/** A place in the grid: the photo there, by id, and where it is in the whole list. */
+type Item = { id: string; index: number };
+
type MonthProps = {
label: string;
month: string;
- items: { photo: Photo; index: number }[];
+ items: Item[];
+ list: PhotoList;
chosen: Set<string>;
anchor: number | null;
deleted: boolean;
@@ -513,6 +506,7 @@ const Month = memo(function Month({
label,
month,
items,
+ list,
chosen,
anchor,
deleted,
@@ -524,7 +518,8 @@ const Month = memo(function Month({
}: {
label: string;
month: string;
- items: { photo: Photo; index: number }[];
+ items: Item[];
+ list: PhotoList;
chosen: Set<string>;
anchor: number | null;
deleted: boolean;
@@ -544,31 +539,74 @@ const Month = memo(function Month({
builtNow.current = built;
const step = useRef(across);
step.current = across;
+ /*
+ * Its photos, a page at a time, fetched once it comes near (the first months at once) and
+ * again whenever it comes back near after they were let go (see photos/list). Until then it
+ * has only its ids, and draws as one block exactly as tall as its rows will be.
+ */
+ const [near, setNear] = useState(eager);
+ const seen = useRef<{ version: number; items: Item[] | null; sig: string }>({ version: -1, items: null, sig: "" });
+ // Watched once near, or once it has begun to build (its own watcher saw it first).
+ const watching = near || built > 0;
+ const sig = useSyncExternalStore(list.store.subscribe, () => {
+ if (!watching) return "";
+ const store = list.store;
+ if (seen.current.version === store.version && seen.current.items === items) return seen.current.sig;
+ // How many from its start are here, and each one's change count: a photo read again or
+ // changed here (a heart) draws its tile again, and nothing else does.
+ let ready = 0;
+ let turns = 0;
+ for (const { id } of items) {
+ if (!store.get(id)) break;
+ ready++;
+ turns += store.turns(id);
+ }
+ seen.current = { version: store.version, items, sig: `${ready}:${turns}` };
+ return seen.current.sig;
+ });
+ const ready = watching ? Number(sig.split(":")[0] || 0) : 0;
+ useEffect(() => {
+ if (eager && items.length) void list.need(items[0].index, items[items.length - 1].index);
+ }, [eager, list, items]);
+ // One watcher: near the screen (within 4000px), its photos are asked for and it is built a few
+ // rows a frame; gone far again before it was built, its building waits until it comes back —
+ // a fling to the foot of the library builds the months it lands on, not every month it
+ // passed on the way (they queued first, and the screen it landed on waited behind them).
useEffect(() => {
const el = ref.current;
- if (builtNow.current >= items.length) return undefined;
let gone = false;
- const start = () =>
+ let queued = false;
+ let close = false;
+ const start = () => {
+ if (queued || builtNow.current >= items.length) return;
+ queued = true;
buildSoon(() => {
if (gone) return true;
+ if (!close) {
+ queued = false;
+ return true;
+ }
const rows = Math.max(2, Math.round(BUILD_TILES / step.current));
const next = Math.min(items.length, builtNow.current + rows * step.current);
builtNow.current = next;
setBuilt(next);
+ if (next >= items.length) queued = false;
return next >= items.length;
});
- if (!el || typeof IntersectionObserver === "undefined") {
+ };
+ if (!el || typeof IntersectionObserver === "undefined" || !items.length) {
+ close = true;
start();
return () => {
gone = true;
};
}
- // Built well ahead and then kept: a month taken down and built again as it scrolls back
- // showed as a heading over nothing while its tiles came back.
const watch = new IntersectionObserver(
([e]) => {
- if (!e.isIntersecting) return;
- watch.disconnect();
+ close = e.isIntersecting;
+ if (!close) return;
+ setNear(true);
+ void list.need(items[0].index, items[items.length - 1].index);
start();
},
{ root: el.closest(".px-scroll"), rootMargin: "4000px 0px" },
@@ -578,16 +616,19 @@ const Month = memo(function Month({
gone = true;
watch.disconnect();
};
- }, [items.length]); // eslint-disable-line react-hooks/exhaustive-deps
- // Built part way when the zoom changed: what is built stays on whole rows.
- const shownCount = built >= items.length ? items.length : Math.floor(built / across) * across;
+ }, [list, items]); // eslint-disable-line react-hooks/exhaustive-deps
+ // Built part way when the zoom changed, or its photos part way here: what shows stays on whole
+ // rows, and the rest is the block below.
+ const upTo = Math.min(built, ready);
+ const shownCount = upTo >= items.length ? items.length : Math.floor(upTo / across) * across;
const live = shownCount > 0;
return (
<section ref={ref} className="px-month" aria-label={label || undefined} data-month={month || undefined}>
{label && <h2 className="px-month-title">{label}</h2>}
{live && (
<div className="px-grid" role="listbox" aria-multiselectable="true" aria-label={label || "Photos"}>
- {(shownCount < items.length ? items.slice(0, shownCount) : items).map(({ photo, index }) => {
+ {(shownCount < items.length ? items.slice(0, shownCount) : items).map(({ id, index }) => {
+ const photo = list.store.get(id)!;
const t = deleted ? timeLeft(photo, true) : null;
return (
<Tile
@@ -648,8 +689,14 @@ export function PhotosView() {
}
return next;
});
- /** The view's photos as read; `photos`, below, is them in the order chosen to show. */
- const [raw, setPhotos] = useState<Photo[] | null>(null);
+ /**
+ * The view's photos: its index whole, in the order chosen (sorted where they are kept), and
+ * the photos themselves from the store as the grid and the viewer come near them. A page
+ * landing draws this screen once a frame at most; the months draw only where it landed.
+ */
+ const store = useMemo(() => new PhotoStore(), []);
+ const [photos, setPhotos] = useState<PhotoList | null>(null);
+ useSyncExternalStore(store.subscribe, () => store.version);
/**
* A burst opened from its chosen photo, as Photos' "View all": the viewer goes through the
* burst's photos in the order they were shot, counted "3 of 64", until Done (or the viewer
@@ -681,7 +728,7 @@ export function PhotosView() {
const [open, setOpen] = useState<number | null>(null);
const [info, setInfo] = useState(false);
/** A slideshow playing: what it shows, and where it begins. */
- const [show, setShow] = useState<{ list: Photo[]; start: number } | null>(null);
+ const [show, setShow] = useState<{ ids: string[]; start: number } | null>(null);
/** Photos selected in the grid, as on a Mac: a click selects, a double-click opens. */
const [chosen, setChosen] = useState<Set<string>>(new Set());
const anchor = useRef<number | null>(null);
@@ -725,37 +772,60 @@ export function PhotosView() {
return was;
});
};
- // Sorted where it is drawn, in the same render as the months made from it. Sorted after the
- // render instead, a view's first frame grouped one order by another's dates: months came
- // twice ("December 2025" four times over), and the repeated keys left stale months on screen.
- const photos = useMemo(
- () => (raw && sort && !inBurst ? sortList(raw, sort) : raw),
- [raw, sort?.by, sort?.oldest, inBurst !== null], // eslint-disable-line react-hooks/exhaustive-deps
- );
+ // The order asked of the library for what is being chosen now (the backend sorts: a view is
+ // sorted where it is kept, and its index and pages come in that order).
+ const wantSortable = !searching && !album && view !== "recentlyDeleted" && view !== "rated";
+ const want = wantSortable ? (sorts[view] ?? defaultSort(view)) : null;
// Reads can pass each other: a sync's read of one view can land after another view was
// chosen. Only the newest read may draw, or a view shows another's photos under its title.
const reads = useRef(0);
/** A burst is being gone through: the library's reads wait until it is left (see viewBurst). */
const burstOpen = useRef(false);
+ const drawnNow = useRef(drawn);
+ drawnNow.current = drawn;
+ const photosNow = useRef(photos);
+ photosNow.current = photos;
const read = useCallback(async () => {
if (burstOpen.current) return;
const mine = ++reads.current;
- const [list, c, a] = await Promise.all([
- searching ? api.photosSearch(searching) : album ? api.photosInAlbum(album.id) : api.photosList(view),
- api.photosCounts(),
- api.photosAlbums(),
- ]);
+ const source: PhotoSource = searching ? { query: searching } : album ? { album: album.id } : { view };
+ const order: PhotoOrder | null = want;
+ const d = drawnNow.current;
+ const again = photosNow.current !== null && d.view === view && d.album?.id === album?.id && d.query === searching;
+ const index = api.photosIndex(source, order);
+ let indexed = false;
+ // Another place chosen: its first screen from its first page, which is small and comes at
+ // once, painted before the whole index (a large library's takes a moment) is here.
+ if (!again) {
+ api.photosPage(source, order, 0, PAGE).then(
+ (page) => {
+ if (indexed || mine !== reads.current) return;
+ setPhotos(PhotoList.of(page, store, (p) => sortKey(p, order?.by ?? "taken")));
+ setDrawn({ view, album, query: searching });
+ },
+ () => {},
+ );
+ }
+ const [read, c, a] = await Promise.all([index, api.photosCounts(), api.photosAlbums()]);
+ indexed = true;
if (mine !== reads.current) return;
- setPhotos((before) => keepSame(before, list));
+ const next = new PhotoList(read, store);
+ // Read again (a sync landed, a change was made): what is held is fetched again where the
+ // grid is, and only a list that changed is drawn again.
+ if (again) store.refresh();
+ store.use(next);
+ setPhotos((before) => (next.same(before) ? before : next));
+ const near = again ? store.near : 0;
+ void next.need(near - PAGE, near + PAGE);
// The same view read again is the same view drawn: a new object here built every month
// afresh and faded the grid in again at each landing.
- setDrawn((d) => (d.view === view && d.album === album && d.query === searching ? d : { view, album, query: searching }));
+ setDrawn((was) => (was.view === view && was.album === album && was.query === searching ? was : { view, album, query: searching }));
setCounts(Object.fromEntries(c));
setAlbums(a);
// An album deleted elsewhere is not left open, empty.
if (album && !a.some(([x]) => x.id === album.id)) setAlbum(null);
- }, [view, album, searching]);
+ }, [view, album, searching, want?.by, want?.oldest]); // eslint-disable-line react-hooks/exhaustive-deps
// A pass that lands while another screen is in front is read when this one comes back, once,
// not at every landing: a screen out of sight is still mounted (lib/screen), and each pass
// lands a service at a time.
@@ -772,27 +842,53 @@ export function PhotosView() {
// the line under the title.
const byDay = zoom >= DAYS_FROM;
const months = useMemo(() => {
- const out: { label: string; month: string; items: { photo: Photo; index: number }[] }[] = [];
+ const out: { label: string; month: string; items: Item[] }[] = [];
// An album keeps its own order, and Recently Deleted is in the order things were deleted:
// grouped by the month they were taken, the same month came back again and again. Both are
// one grid, as icloud.com shows them.
- if (drawn.album || drawn.view === "recentlyDeleted") return [{ label: "", month: "", items: (photos ?? []).map((photo, index) => ({ photo, index })) }];
+ if (!photos) return out;
+ if (drawn.album || drawn.view === "recentlyDeleted") return [{ label: "", month: "", items: photos.ids.map((id, index) => ({ id, index })) }];
const thisYear = new Date().getFullYear();
- (photos ?? []).forEach((photo, index) => {
+ const rated = drawn.view === "rated" && !drawn.album;
+ // Named once a month (or day), not once a photo: fifty thousand dates formatted on every
+ // read was most of laying the grid out.
+ const names = new Map<number, [string, string]>();
+ let lastKey = NaN;
+ let lastLabel = "";
+ let lastMonth = "";
+ photos.ids.forEach((id, index) => {
// Rated is grouped by how many stars, as icloud.com's Rated page is.
- const stars = photo.rating ?? 0;
- const rated = drawn.view === "rated" && !drawn.album;
- const at = sortKey(photo, sort?.by ?? "taken");
- const month = rated ? "" : monthOf(at);
- const label = rated ? `${stars} ${stars === 1 ? "Star" : "Stars"}` : byDay ? dayOf(at, thisYear) : month;
+ let label: string;
+ let month: string;
+ if (rated) {
+ const stars = photos.marks[index] >> 3;
+ label = `${stars} ${stars === 1 ? "Star" : "Stars"}`;
+ month = "";
+ } else {
+ const at = photos.keys[index];
+ if (at !== lastKey) {
+ lastKey = at;
+ const d = new Date(at * 1000);
+ const bucket = byDay ? d.getFullYear() * 400 + d.getMonth() * 32 + d.getDate() : d.getFullYear() * 12 + d.getMonth();
+ let named = names.get(bucket);
+ if (!named) {
+ const m = monthOf(at);
+ named = [m, byDay ? dayOf(at, thisYear) : m];
+ names.set(bucket, named);
+ }
+ [lastMonth, lastLabel] = named;
+ }
+ label = lastLabel;
+ month = lastMonth;
+ }
const last = out[out.length - 1];
- if (last && last.label === label) last.items.push({ photo, index });
- else out.push({ label, month, items: [{ photo, index }] });
+ if (last && last.label === label) last.items.push({ id, index });
+ else out.push({ label, month, items: [{ id, index }] });
});
return out;
- }, [photos, sort?.by, drawn, byDay]);
+ }, [photos, drawn, byDay]);
- const shown = open !== null ? photos?.[open] ?? null : null;
+ const shown = open !== null ? photos?.at(open) ?? null : null;
/**
* The picture last painted on the stage, kept beneath the next one until that one is decoded:
* a step never shows a blank, nor the soft thumbnail before the sharp picture (the flicker on
@@ -821,6 +917,8 @@ export function PhotosView() {
);
const painted = useRef<Photo | null>(null);
const underEl = useRef<HTMLImageElement | null>(null);
+ // The last picture painted, held under a step until the next one is decoded at the size the
+ // stage draws it: the previous sharp photo, never the soft thumbnail, and never an empty frame.
const under = shown && shown.kind !== "video" && painted.current && painted.current.id !== shown.id && painted.current.kind !== "video" && !decoded.has(viewSrc(shown)) ? painted.current : null;
if (!shown || shown.kind === "video") painted.current = null;
// The viewer follows the photo, not its place: when the list moves under it — its date
@@ -836,14 +934,14 @@ export function PhotosView() {
return;
}
// Only a list that changed sends it looking; a step to another photo is a new photo.
- if (moved && openId.current && photos[open]?.id !== openId.current) {
- const again = photos.findIndex((p) => p.id === openId.current);
+ if (moved && openId.current && photos.ids[open] !== openId.current) {
+ const again = photos.indexOf(openId.current);
if (again >= 0) {
setOpen(again);
return;
}
}
- openId.current = photos[open]?.id ?? null;
+ openId.current = photos.ids[open] ?? null;
}, [open, photos]);
/*
@@ -917,7 +1015,7 @@ export function PhotosView() {
};
const fitted = (p: Photo): React.CSSProperties => {
// The grid's thumbnail, already decoded, painted under the picture: never a black stage.
- const under = { backgroundImage: `url("${pictureSrc(p.id, "thumb")}")` };
+ const under = { backgroundImage: `url("${loadedThumb(p.id)}")` };
if (!p.width || !p.height) return under;
// Both sides set, each the smaller of the room across and the room down in the photo's own
// proportion: WebKit sized a replaced image's height from its width alone, ignoring
@@ -934,6 +1032,9 @@ export function PhotosView() {
maxHeight: "none",
};
};
+ /** A photo's shape as shown, upright (its picture's own, once learned): the box a film is
+ * turned into. */
+ const shapeOf = (p: Photo) => ({ w: trueShape.get(p.id) ?? (p.width && p.height ? p.width / p.height : 4 / 3), h: 1 });
const still = () => typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
// A photo opens and closes at once, with no animation: every way of animating it — the photo
// growing out of its tile, the backdrop fading, the bars fading, the grid behind it hidden or
@@ -965,13 +1066,20 @@ export function PhotosView() {
backTo.current = openNow.current;
setOpen(null);
}, []); // eslint-disable-line react-hooks/exhaustive-deps
+ // A step lands only on a photo that is here — the next ones are fetched well ahead (below) —
+ // so the stage never shows nothing; a key held at the edge of what is here waits for it.
const step = useCallback(
- (by: number) =>
- setOpen((at) => {
- if (at === null || !photos) return at;
- const to = Math.max(0, Math.min(photos.length - 1, at + by));
- return to;
- }),
+ (by: number) => {
+ const at = openNow.current;
+ if (at === null || !photos) return;
+ const to = Math.max(0, Math.min(photos.length - 1, at + by));
+ if (to === at) return;
+ if (!photos.at(to)) {
+ void photos.need(to - PAGE / 2, to + PAGE / 2);
+ return;
+ }
+ setOpen(to);
+ },
[photos],
);
@@ -1033,8 +1141,10 @@ export function PhotosView() {
const viewBurst = async (p: Photo) => {
if (!p.burst) return;
try {
- const list = await api.photosBurst(p.burst);
+ const list = new PhotoList(await api.photosIndex({ burst: p.burst }, null), store);
+ await list.need(0, list.length - 1);
reads.current++; // a sync's read landing now must not put the library back over it
+ store.use(list);
setPhotos(list);
setInBurst({ from: p.id, count: list.length });
// Opened by the photo, not a place: the list is drawn as it is shown.
@@ -1055,7 +1165,7 @@ export function PhotosView() {
const [reopen, setReopen] = useState<string | null>(null);
useEffect(() => {
if (!reopen || !photos) return;
- const at = photos.findIndex((x) => x.id === reopen);
+ const at = photos.indexOf(reopen);
setReopen(null);
if (at >= 0) setOpen(at);
}, [reopen, photos]);
@@ -1090,10 +1200,10 @@ export function PhotosView() {
const at = backTo.current;
backTo.current = null;
if (open !== null || at === null || inBurst) return;
- const p = photos?.[at];
- if (!p) return;
+ const id = photos?.ids[at];
+ if (!id) return;
anchor.current = at;
- setChosen((c) => (c.size === 1 && c.has(p.id) ? c : new Set([p.id])));
+ setChosen((c) => (c.size === 1 && c.has(id) ? c : new Set([id])));
reach(at);
}, [open === null]); // eslint-disable-line react-hooks/exhaustive-deps
/**
@@ -1165,7 +1275,7 @@ export function PhotosView() {
const [moving, setMoving] = useState<string | null>(null);
useEffect(() => setMoving(null), [shown?.id]);
/** How the film being played is turned, as its file records it (see turnStyle). */
- const [turn, setTurn] = useState<{ key: string; value: Turn } | null>(null);
+ const [turn, setTurn] = useState<{ key: string; value: Turn; zoom: number } | null>(null);
/** Videos Apple keeps no streaming copy of: played from the original instead. */
const [noCopy, setNoCopy] = useState<Set<string>>(() => new Set());
// A video plays from Apple's streaming copy (H.264, its header first: it starts at once), not
@@ -1176,10 +1286,15 @@ export function PhotosView() {
if (!turnFor || turn?.key === turnFor) return undefined;
let live = true;
const [id, which] = turnFor.split("/") as [string, "original" | "video"];
+ // Its turn and its margin, both read from the film's header.
+ const zoom = api.photoVideoZoom(id, which).catch(() => 1);
api.photoVideoTurn(id, which).then(
- (value) => live && setTurn({ key: turnFor, value }),
+ async (value) => {
+ const z = await zoom;
+ if (live) setTurn({ key: turnFor, value, zoom: z });
+ },
// Not known: drawn as served, as it was before.
- () => live && setTurn({ key: turnFor, value: [1, 0, 0, 1] }),
+ () => live && setTurn({ key: turnFor, value: [1, 0, 0, 1], zoom: 1 }),
);
return () => {
live = false;
@@ -1189,8 +1304,11 @@ export function PhotosView() {
const [unplayable, setUnplayable] = useState<Set<string>>(() => new Set());
// The window's player reads only http(s): videos come from the app's own loopback server.
const [videoBase, setVideoBase] = useState<string | null>(null);
+ /** What this computer's player can decode: why a video it cannot play is a still. */
+ const [videoSupport, setVideoSupport] = useState<{ missing: string[] } | null>(null);
useEffect(() => {
api.videoBase().then(setVideoBase, () => setVideoBase(null));
+ api.videoSupport().then(setVideoSupport, () => setVideoSupport(null));
}, []);
const unzoom = (glide = true) => paint({ k: 1, x: 0, y: 0 }, glide);
// Kept so the image's edge never comes in past the middle of the stage.
@@ -1273,17 +1391,19 @@ export function PhotosView() {
// tore in WebKitGTK.)
useEffect(() => {
if (open === null || !photos) return;
+ // The photos either side, well past where a held key gets to before they land.
+ void photos.need(open - PAGE / 2, open + PAGE / 2);
for (const by of [1, -1, 2, -2]) {
- const p = photos[open + by];
+ const p = photos.at(open + by);
if (p && p.kind !== "video") void warm(p);
}
- }, [open, photos]);
+ }, [open, photos, open !== null && photos?.at(open + 1), open !== null && photos?.at(open - 1)]); // eslint-disable-line react-hooks/exhaustive-deps
// The viewer's keys: arrows to go through, Escape to close, I for the details.
const live = useActiveRef();
useEffect(() => {
if (open === null) return undefined;
- const current = photos?.[open] ?? null;
+ const current = photos?.at(open) ?? null;
const onKey = (e: KeyboardEvent) => {
if (!live.current) return;
// Keys typed into a field — the caption — are words, not commands.
@@ -1318,7 +1438,7 @@ export function PhotosView() {
// F as well as ".", and H as well as Ctrl+L, as icloud.com takes them.
else if ((e.key === "." || (e.key.toLowerCase() === "f" && !e.ctrlKey && !e.metaKey)) && current && view !== "recentlyDeleted") void change(current, "favorite", !current.favorite);
else if (((e.ctrlKey || e.metaKey) ? e.key.toLowerCase() === "l" : e.key.toLowerCase() === "h") && current && view !== "recentlyDeleted") void change(current, "hidden", view !== "hidden");
- else if ((e.key === "Delete" || e.key === "Backspace") && current && album) void removeFrom([current]);
+ else if ((e.key === "Delete" || e.key === "Backspace") && current && album) void removeFrom([current.id]);
else if ((e.key === "Delete" || e.key === "Backspace") && current && view !== "recentlyDeleted") void change(current, "deleted", true);
else if ((e.key === "Delete" || e.key === "Backspace") && current && view === "recentlyDeleted" && !album) void change(current, "expunged", true);
else return;
@@ -1333,8 +1453,9 @@ export function PhotosView() {
* it refuses, which puts the photo back as it was and says why.
*/
const [ask, asking] = useConfirm();
- const change = (p: Photo, flag: Flag, on: boolean) => changeAll([p], flag, on);
- const changeAll = async (list: Photo[], flag: Flag, on: boolean) => {
+ const change = (p: Photo, flag: Flag, on: boolean) => changeAll([p.id], flag, on);
+ /** A flag set on photos by id — what is here changes at once, the rest when it is read. */
+ const changeAll = async (list: string[], flag: Flag, on: boolean) => {
if (list.length === 0) return;
const n = list.length;
// Asked first, in icloud.com's words: a delete reaches every device.
@@ -1376,7 +1497,8 @@ export function PhotosView() {
return;
}
const before = photos;
- const ids = new Set(list.map((p) => p.id));
+ const ids = new Set(list);
+ const was = list.map((id) => store.get(id)).filter((p): p is Photo => Boolean(p));
// Which changes take a photo out of the view it is in.
const leaves =
flag === "expunged" ? true
@@ -1384,11 +1506,8 @@ export function PhotosView() {
: flag === "deleted" ? (on ? view !== "recentlyDeleted" : view === "recentlyDeleted")
: flag === "hidden" ? (on ? view !== "hidden" : view === "hidden")
: !on && view === "favorites";
- setPhotos((all) =>
- leaves
- ? (all ?? []).filter((x) => !ids.has(x.id))
- : (all ?? []).map((x) => (ids.has(x.id) ? { ...x, [flag]: on } : x)),
- );
+ if (leaves) setPhotos((all) => all?.without(ids) ?? all);
+ else store.patch(ids, (x) => ({ ...x, [flag]: on }));
if (leaves) {
setChosen((c) => new Set([...c].filter((id) => !ids.has(id))));
// The viewer goes on to the next photo, or the one before at the end, or closes.
@@ -1400,10 +1519,11 @@ export function PhotosView() {
}
try {
// The whole selection in one call: the library changes at once, Apple hears it batched.
- await api.photosSetFlag(list.map((p) => p.id), flag, on);
+ await api.photosSetFlag(list, flag, on);
read().catch(() => {});
} catch (e) {
setPhotos(before);
+ store.put(was);
setError(messageOf(e));
read().catch(() => {});
}
@@ -1491,7 +1611,7 @@ export function PhotosView() {
};
/** Out of the album open; the photos stay in the library. */
- const removeFrom = async (gone: Photo[]) => {
+ const removeFrom = async (gone: string[]) => {
if (!album) return;
const n = gone.length;
const sure = await ask({
@@ -1501,8 +1621,8 @@ export function PhotosView() {
});
if (!sure) return;
const before = photos;
- const ids = new Set(gone.map((p) => p.id));
- setPhotos((list) => (list ?? []).filter((x) => !ids.has(x.id)));
+ const ids = new Set(gone);
+ setPhotos((list) => list?.without(ids) ?? list);
setAlbums((list) => list.map((x) => (x[0].id === album.id ? [x[0], Math.max(0, x[1] - n)] : x)));
setOpen((at) => {
if (at === null || !photos) return at;
@@ -1518,17 +1638,19 @@ export function PhotosView() {
}
};
- // Where each photo is, by id: the selection is turned into photos by looking them up, in the
- // order they are shown — not by walking the whole library on every click.
- const placeOf = useMemo(() => new Map((photos ?? []).map((p, i) => [p.id, i] as const)), [photos]);
+ // The selection in the order shown, by id, looked up where each one is — not by walking the
+ // whole library on every click. Its photos need not be here: an action on it fetches any
+ // that are not (store.load).
const selected = useMemo(() => {
- const all = photos ?? [];
+ if (!photos) return [];
return [...chosen]
- .map((id) => placeOf.get(id))
- .filter((i): i is number => i !== undefined)
- .sort((x, y) => x - y)
- .map((i) => all[i]);
- }, [photos, chosen, placeOf]);
+ .map((id) => [id, photos.indexOf(id)] as const)
+ .filter(([, i]) => i >= 0)
+ .sort((x, y) => x[1] - y[1])
+ .map(([id]) => id);
+ }, [photos, chosen]);
+ const kindsOf = (ids: string[]) => ids.map((id) => photos?.kind(photos.indexOf(id)) ?? "image");
+ const anyPlain = (ids: string[]) => ids.some((id) => !(photos?.favorite(photos.indexOf(id)) ?? false));
// A photo found by the search across everything: the whole library shown, and the photo
// opened in the viewer once the library's photos are here.
@@ -1544,14 +1666,17 @@ export function PhotosView() {
useEffect(() => {
const id = revealing.current;
if (!id || view !== "library" || album) return;
- const at = (photos ?? []).findIndex((p) => p.id === id);
+ const at = photos?.indexOf(id) ?? -1;
if (at < 0) return;
revealing.current = null;
void openAt(at);
}, [photos, view, album]); // eslint-disable-line react-hooks/exhaustive-deps
const openAt = async (index: number) => {
- const p = photos?.[index];
+ if (!photos) return;
+ // Opened from a tile it is here; from a search, its page is fetched first.
+ if (!photos.at(index)) await photos.need(index - PAGE / 2, index + PAGE / 2);
+ const p = photos.at(index);
if (!p) return;
// Open at full quality: the whole picture decoded first — from disk, a moment — but never
// waited on for longer than a blink (a click must answer at once); past that it opens on
@@ -1567,12 +1692,11 @@ export function PhotosView() {
// A click as Photos takes it: alone it selects that one, with Ctrl (⌘) it adds or takes
// away, with Shift it selects everything from the last one chosen.
const pick = (index: number, e: { shiftKey: boolean; ctrlKey: boolean; metaKey: boolean }) => {
- const list = photos ?? [];
- const id = list[index]?.id;
- if (!id) return;
+ const id = photos?.ids[index];
+ if (!photos || !id) return;
if (e.shiftKey && anchor.current !== null) {
const [a, b] = [Math.min(anchor.current, index), Math.max(anchor.current, index)];
- const span = list.slice(a, b + 1).map((p) => p.id);
+ const span = photos.ids.slice(a, b + 1);
setChosen((c) => new Set([...(e.ctrlKey || e.metaKey ? c : []), ...span]));
return;
}
@@ -1642,31 +1766,31 @@ export function PhotosView() {
if (!live.current) return;
const t = e.target as HTMLElement | null;
if (t?.closest?.("input, textarea, [contenteditable], .row-menu, [role=dialog]") || naming) return;
- const list = photos ?? [];
+ const list = photos?.ids ?? [];
const ctrl = e.ctrlKey || e.metaKey;
// Ctrl+A is the photos' wherever the focus rests on this screen — the app list keeps it
// after Photos is chosen there — never the page's text.
const selectAll = ctrl && e.key.toLowerCase() === "a";
if (!selectAll && !t?.closest?.(".px") && t !== document.body) return;
if (ctrl && e.key.toLowerCase() === "a") {
- setChosen(new Set(list.map((p) => p.id)));
+ setChosen(new Set(list));
} else if (e.key === "Escape" && chosen.size) {
setChosen(new Set());
} else if ((e.key === "Enter" || e.key === " ") && t?.closest?.(".px-tile[data-index]") && !t.closest(".px-tile")!.matches('[aria-selected="true"]')) {
// The photo the keys rest on — Tab lands on one before any is chosen — opens.
e.preventDefault();
const at = Number(t.closest(".px-tile")!.getAttribute("data-index"));
- setChosen(new Set([list[at].id]));
+ setChosen(new Set([list[at]]));
anchor.current = at;
openAt(at);
} else if ((e.key === "Enter" || e.key === " ") && selected.length) {
- openAt(list.indexOf(selected[0]));
+ openAt(photos!.indexOf(selected[0]));
} else if (e.key.startsWith("Arrow") && list.length) {
const from = anchor.current ?? (e.key === "ArrowLeft" || e.key === "ArrowUp" ? list.length : -1);
const to = from < 0 ? 0 : from >= list.length ? list.length - 1 : neighbour(from, e.key);
if (to === null) return e.preventDefault();
- if (e.shiftKey && anchor.current !== null) setChosen((c) => new Set([...c, list[to].id]));
- else setChosen(new Set([list[to].id]));
+ if (e.shiftKey && anchor.current !== null) setChosen((c) => new Set([...c, list[to]]));
+ else setChosen(new Set([list[to]]));
anchor.current = to;
reach(to);
} else if ((e.key === "Delete" || e.key === "Backspace") && selected.length) {
@@ -1679,13 +1803,13 @@ export function PhotosView() {
} else if (!ctrl && e.key.toLowerCase() === "i" && selected.length) {
// I: the selected photo, opened with its details.
setInfo(true);
- openAt(list.indexOf(selected[0]));
+ openAt(photos!.indexOf(selected[0]));
} else if ((ctrl ? e.key.toLowerCase() === "l" : e.key.toLowerCase() === "h") && selected.length && view !== "recentlyDeleted") {
// ⌘L in Photos: hide, or in Hidden, unhide.
void changeAll(selected, "hidden", view !== "hidden");
} else if ((e.key === "." || (!ctrl && e.key.toLowerCase() === "f")) && selected.length && view !== "recentlyDeleted") {
// As Photos: if any is not a favorite, all become favorites; else all stop being.
- void changeAll(selected, "favorite", selected.some((p) => !p.favorite));
+ void changeAll(selected, "favorite", anyPlain(selected));
} else return;
e.preventDefault();
};
@@ -1754,7 +1878,7 @@ export function PhotosView() {
// Only the photo itself, not the hairline gap after it.
if (x2 < left0 + c * pitch || x1 > left0 + c * pitch + pitch - gap) continue;
const it = items[r * across + c];
- if (it) next.add(it.photo.id);
+ if (it) next.add(it.id);
}
}
}
@@ -1790,7 +1914,7 @@ export function PhotosView() {
swept.current = true;
// The keys go on from the sweep's last photo.
const ids = [...chosenNow.current];
- const at = ids.length ? Math.max(...ids.map((id) => placeOf.get(id) ?? -1)) : -1;
+ const at = ids.length ? Math.max(...ids.map((id) => photos?.indexOf(id) ?? -1)) : -1;
anchor.current = at >= 0 ? at : anchor.current;
}
};
@@ -1804,9 +1928,9 @@ export function PhotosView() {
// A slideshow of what is selected when that is more than one photo, else of the whole view
// from this photo on, as Photos starts one.
const startShow = (from: Photo) => {
- const list = selected.length > 1 && chosen.has(from.id) ? selected : (photos ?? []);
+ const ids = selected.length > 1 && chosen.has(from.id) ? selected : (photos?.ids ?? []);
setMenu(null);
- setShow({ list, start: Math.max(0, list.findIndex((p) => p.id === from.id)) });
+ setShow({ ids, start: Math.max(0, ids.indexOf(from.id)) });
};
const albumEntries = (ids: string[]): MenuEntry[] => [
@@ -1818,14 +1942,14 @@ export function PhotosView() {
const photoMenu = (p: Photo, at: { x: number; y: number; alignRight: boolean }) => {
// A right-click on a selected photo acts on the whole selection; on any other, it
// selects that one first, as Photos does.
- const group = chosen.has(p.id) && selected.length > 1 ? selected : [p];
+ const group = chosen.has(p.id) && selected.length > 1 ? selected : [p.id];
if (!chosen.has(p.id)) {
setChosen(new Set([p.id]));
- anchor.current = photos?.findIndex((x) => x.id === p.id) ?? null;
+ anchor.current = photos?.indexOf(p.id) ?? null;
}
if (group.length > 1) {
const n = group.length;
- const anyPlain = group.some((x) => !x.favorite);
+ const plain = anyPlain(group);
setMenu({
at,
entries:
@@ -1836,13 +1960,13 @@ export function PhotosView() {
{ label: `Delete ${n} Items`, danger: true, run: () => void changeAll(group, "expunged", true) },
]
: [
- { label: anyPlain ? "Favorite" : "Unfavorite", run: () => void changeAll(group, "favorite", anyPlain) },
+ { label: plain ? "Favorite" : "Unfavorite", run: () => void changeAll(group, "favorite", plain) },
null,
{ label: `Download ${n} Items`, run: () => void downloadAs(group, "originals") },
- { label: "More Download Options", run: () => setOptions(group) },
+ { label: "More Download Options", run: () => void store.load(group).then(setOptions, (e) => setError(messageOf(e))) },
null,
{ label: "Start Slideshow", run: () => startShow(p) },
- { label: "Add to Album", submenu: albumEntries(group.map((x) => x.id)) },
+ { label: "Add to Album", submenu: albumEntries(group) },
null,
view === "hidden" && !album
? { label: `Unhide ${n} Photos`, run: () => void changeAll(group, "hidden", false) }
@@ -1873,7 +1997,7 @@ export function PhotosView() {
? { label: "Unhide Photo", run: () => void change(p, "hidden", false) }
: { label: "Hide Photo", run: () => void change(p, "hidden", true) },
album
- ? { label: "Remove from Album", danger: true, run: () => void removeFrom([p]) }
+ ? { label: "Remove from Album", danger: true, run: () => void removeFrom([p.id]) }
: { label: "Delete", danger: true, run: () => void change(p, "deleted", true) },
];
setMenu({ at, entries });
@@ -1887,10 +2011,10 @@ export function PhotosView() {
const dragging2 = useRef<string[] | null>(null);
const [dropOn, setDropOn] = useState<string | null>(null);
const dragFrom = (p: Photo, e: React.DragEvent) => {
- const ids = chosen.has(p.id) ? selected.map((x) => x.id) : [p.id];
+ const ids = chosen.has(p.id) ? selected : [p.id];
if (!chosen.has(p.id)) {
setChosen(new Set([p.id]));
- anchor.current = photos?.findIndex((x) => x.id === p.id) ?? null;
+ anchor.current = photos?.indexOf(p.id) ?? null;
}
dragging2.current = ids;
e.dataTransfer.effectAllowed = "copy";
@@ -2019,12 +2143,11 @@ export function PhotosView() {
void words(p, titleField.current?.value ?? p.title ?? "", captionField.current?.value ?? p.caption ?? "");
};
const keywords = async (p: Photo, words: string[]) => {
- const before = photos;
- setPhotos((all) => (all ?? []).map((x) => (x.id === p.id ? { ...x, keywords: words } : x)));
+ store.patch([p.id], (x) => ({ ...x, keywords: words }));
try {
await api.photoSetKeywords(p.id, words);
} catch (e) {
- setPhotos(before);
+ store.put([p]);
setError(messageOf(e));
}
};
@@ -2032,14 +2155,14 @@ export function PhotosView() {
const rate = async (p: Photo, rating: number) => {
const before = photos;
const leaves = view === "rated" && rating === 0;
- setPhotos((all) =>
- leaves ? (all ?? []).filter((x) => x.id !== p.id) : (all ?? []).map((x) => (x.id === p.id ? { ...x, rating } : x)),
- );
+ if (leaves) setPhotos((all) => all?.without(new Set([p.id])) ?? all);
+ else store.patch([p.id], (x) => ({ ...x, rating }));
try {
await api.photoSetRating(p.id, rating);
read().catch(() => {});
} catch (e) {
setPhotos(before);
+ store.put([p]);
setError(messageOf(e));
}
};
@@ -2047,12 +2170,11 @@ export function PhotosView() {
const words = async (p: Photo, title: string, caption: string) => {
const [t, c] = [title.trim(), caption.trim()];
if (t === (p.title ?? "") && c === (p.caption ?? "")) return;
- const before = photos;
- setPhotos((all) => (all ?? []).map((x) => (x.id === p.id ? { ...x, title: t || null, caption: c || null } : x)));
+ store.patch([p.id], (x) => ({ ...x, title: t || null, caption: c || null }));
try {
await api.photoSetText(p.id, t, c);
} catch (e) {
- setPhotos(before);
+ store.put([p]);
setError(messageOf(e));
}
};
@@ -2078,24 +2200,23 @@ export function PhotosView() {
const [adjusting, setAdjusting] = useState<Photo | null>(null);
const redate = async (p: Photo, takenAt: number) => {
setAdjusting(null);
- const before = photos;
- setPhotos((all) => (all ?? []).map((x) => (x.id === p.id ? { ...x, takenAt } : x)));
+ store.patch([p.id], (x) => ({ ...x, takenAt }));
try {
await api.photoSetDate(p.id, takenAt);
read().catch(() => {});
} catch (e) {
- setPhotos(before);
+ store.put([p]);
setError(messageOf(e));
}
};
/** Download Options open for these photos. */
const [options, setOptions] = useState<Photo[] | null>(null);
- const downloadAs = async (list: Photo[], want: Want) => {
+ const downloadAs = async (list: string[], want: Want) => {
setOptions(null);
let last = "";
try {
- for (const p of list) last = await api.photoDownload(p.id, want);
+ for (const id of list) last = await api.photoDownload(id, want);
toastSaved(last, list.length);
} catch (e) {
setError(messageOf(e));
@@ -2193,9 +2314,8 @@ export function PhotosView() {
// Under the title, the stretch of time shown — "September – October 2026" — as Photos has it.
const span = useMemo(() => {
- if (!photos || photos.length === 0) return null;
- const times = photos.map((p) => p.takenAt);
- const [a, b] = [new Date(Math.min(...times) * 1000), new Date(Math.max(...times) * 1000)];
+ if (!photos || photos.length === 0 || photos.first === null || photos.last === null) return null;
+ const [a, b] = [new Date(photos.first * 1000), new Date(photos.last * 1000)];
const month = (d: Date, year: boolean) => d.toLocaleDateString(undefined, year ? { month: "long", year: "numeric" } : { month: "long" });
if (a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth()) return month(b, true);
return `${month(a, a.getFullYear() !== b.getFullYear())} – ${month(b, true)}`;
@@ -2203,7 +2323,8 @@ export function PhotosView() {
// At the foot of the library, what it holds: "132 Photos, 2 Videos".
const tally = useMemo(() => {
if (!photos || photos.length === 0) return null;
- const videos = photos.filter((p) => p.kind === "video").length;
+ let videos = 0;
+ for (const m of photos.marks) if ((m & 3) === 1) videos++;
const stills = photos.length - videos;
const part = (n: number, one: string) => `${n.toLocaleString()} ${n === 1 ? one : `${one}s`}`;
return [stills && part(stills, "Photo"), videos && part(videos, "Video")].filter(Boolean).join(", ");
@@ -2223,11 +2344,10 @@ export function PhotosView() {
return months
.filter((m) => m.month && m.items.length && !seen.has(m.month) && seen.add(m.month))
.map((m) => {
- const cover = m.items[0].photo;
- const d = new Date(sortKey(cover, sort?.by ?? "taken") * 1000);
- return { label: m.month, year: d.getFullYear(), month: d.getMonth(), cover };
+ const d = new Date(photos!.keys[m.items[0].index] * 1000);
+ return { label: m.month, year: d.getFullYear(), month: d.getMonth(), cover: { id: m.items[0].id } };
});
- }, [months, drawn, sort?.by]);
+ }, [months, drawn]); // eslint-disable-line react-hooks/exhaustive-deps
const goToMonth = (label: string) => {
const el = scroller.current;
const at = el?.querySelector<HTMLElement>(`.px-month[data-month="${CSS.escape(label)}"]`);
@@ -2405,17 +2525,28 @@ export function PhotosView() {
watch.observe(el);
return () => watch.disconnect();
}, []);
- const cell = Math.round(((gridWidth || 1200) / across) * (window.devicePixelRatio || 1));
+ // The screen's pixel density, followed as it changes (the window moved to another screen, the
+ // page zoomed): no size watcher sees that, and tiles stayed at the old density's pictures.
+ const [dpr, setDpr] = useState(() => window.devicePixelRatio || 1);
+ useEffect(() => {
+ const at = window.matchMedia?.(`(resolution: ${dpr}dppx)`);
+ if (!at) return undefined;
+ const changed = () => setDpr(window.devicePixelRatio || 1);
+ at.addEventListener("change", changed);
+ return () => at.removeEventListener("change", changed);
+ }, [dpr]);
+ const cell = Math.round(((gridWidth || 1200) / across) * dpr);
// The app makes, ahead, every picture the grid and the viewer are about to show at these
// sizes (photos_prepare): the first look at a photo is as sharp as the hundredth. Told again
// when they change, once the window has settled.
useEffect(() => {
const t = window.setTimeout(() => {
const box = stageBox.w ? stageBox : { w: Math.max(320, window.innerWidth - 400), h: Math.max(240, window.innerHeight - 140) };
- api.photosPrepare({ cell, fit, stageW: box.w, stageH: box.h, dpr: window.devicePixelRatio || 1 }).catch(() => {});
+ // The view on screen has its pictures made first (Hidden is not in the library's).
+ api.photosPrepare({ cell, fit, stageW: box.w, stageH: box.h, dpr, view }).catch(() => {});
}, 400);
return () => window.clearTimeout(t);
- }, [cell, fit, open !== null]); // eslint-disable-line react-hooks/exhaustive-deps
+ }, [cell, fit, open !== null, view, dpr]); // eslint-disable-line react-hooks/exhaustive-deps
// A new album or folder, at the top or in a folder: named in place in the sidebar.
const startNew = (parent: string | null, folder: boolean) => {
@@ -2773,7 +2904,7 @@ export function PhotosView() {
countClassName="px-span"
count={
selected.length > 0
- ? pickedWords(selected)
+ ? pickedWords(kindsOf(selected))
: drawn.query
? photos?.length === 1 ? "1 Result" : `${(photos?.length ?? 0).toLocaleString()} Results`
: (here ?? span) || undefined
@@ -2796,7 +2927,7 @@ export function PhotosView() {
</button>
</>
) : (
- <button className="tool has-label danger px-word" onClick={() => void changeAll(photos, "expunged", true)}>
+ <button className="tool has-label danger px-word" onClick={() => void changeAll(photos.ids, "expunged", true)}>
Delete All
</button>
)}
@@ -2950,6 +3081,7 @@ export function PhotosView() {
label={m.label}
month={m.month}
items={m.items}
+ list={photos!}
chosen={chosen}
anchor={anchor.current}
deleted={drawn.view === "recentlyDeleted" && !drawn.album}
@@ -3061,7 +3193,7 @@ export function PhotosView() {
<Download size={17} />
</button>
{album ? (
- <button className="px-full-btn" aria-label="Remove from Album" title="Remove from Album (Delete)" onClick={() => void removeFrom([shown])}>
+ <button className="px-full-btn" aria-label="Remove from Album" title="Remove from Album (Delete)" onClick={() => void removeFrom([shown.id])}>
<CopyMinus size={17} />
</button>
) : (
@@ -3136,7 +3268,7 @@ export function PhotosView() {
<CopyPlus size={17} />
</button>
{album ? (
- <button className="tool px-cap" aria-label="Remove from Album" title="Remove from Album (Delete)" onClick={() => void removeFrom([shown])}>
+ <button className="tool px-cap" aria-label="Remove from Album" title="Remove from Album (Delete)" onClick={() => void removeFrom([shown.id])}>
<CopyMinus size={17} />
</button>
) : (
@@ -3176,7 +3308,8 @@ export function PhotosView() {
<VideoPlayer
key={film}
turn={turn?.key === film ? turn.value : undefined}
- shape={{ w: shown.width, h: shown.height }}
+ zoom={turn?.key === film ? turn.zoom : 1}
+ shape={shapeOf(shown)}
src={`${videoBase}/${film}`}
poster={viewSrc(shown)}
label={shown.filename ?? "Video"}
@@ -3191,12 +3324,22 @@ export function PhotosView() {
) : shown.kind === "video" ? (
// This computer's engine could not play it (no codec for it): a still, and Play
// opens it in the system's own player.
- <button className="px-video" aria-label="Play in your video player" onClick={() => void play(shown)}>
- <img key={shown.id} className="px-shown" src={pictureSrc(shown.id, "medium")} alt={shown.filename ?? ""} decoding="async" style={fitted(shown)} />
- <span className="px-play" aria-hidden="true">
- <Play size={28} strokeWidth={0} fill="currentColor" />
- </span>
- </button>
+ <div className="px-video-hold">
+ <button className="px-video" aria-label="Play in your video player" onClick={() => void play(shown)}>
+ <img key={shown.id} className="px-shown" src={viewSrc(shown)} alt={shown.filename ?? ""} decoding="async" style={fitted(shown)} />
+ <span className="px-play" aria-hidden="true">
+ <Play size={28} strokeWidth={0} fill="currentColor" />
+ </span>
+ </button>
+ {/* Why it is a still: said plainly, with what would fix it. */}
+ {videoBase && (
+ <p className="px-video-note" role="status">
+ {videoSupport && videoSupport.missing.length > 0
+ ? `This video can't play here: this computer is missing ${videoSupport.missing.join(" and ")}. Install it, then reopen Skykeep. Until then, Play opens it in your video player.`
+ : "This video can't play here. Play opens it in your video player."}
+ </p>
+ )}
+ </div>
) : (
<>
{under && (
@@ -3242,6 +3385,9 @@ export function PhotosView() {
alt={shown.filename ?? ""}
decoding="async"
draggable={false}
+ // Opening from the grid, the tile's own picture (already decoded) is painted
+ // under it until it is decoded; on a step the last sharp photo is (px-under),
+ // never a thumbnail.
style={under ? { ...fitted(shown), backgroundImage: "none" } : fitted(shown)}
onLoad={(e) => {
const img = e.currentTarget;
@@ -3268,20 +3414,27 @@ export function PhotosView() {
// The moving part, laid exactly over the still, played once and gone —
// turned as it was recorded (a selfie's is a quarter turn and a mirror),
// and not shown until that turn is known, so it never shows sideways.
- <video
- key={`${shown.id}-live`}
- className="px-live"
- src={`${videoBase}/${shown.id}/video`}
- style={
- turn?.key === `${shown.id}/video`
- ? turnStyle(turn.value, shown.width, shown.height)
- : { visibility: "hidden" }
- }
- autoPlay
- playsInline
- onEnded={() => setMoving(null)}
- onError={() => setMoving(null)}
- />
+ // In the still's own box, clipped to it: the film drawn the still's size and
+ // shape whatever its own pixels, and only once a frame of it is here — until
+ // then, and once it ends, the still itself shows, never a black frame.
+ <div className="px-live-frame" key={`${shown.id}-live`}>
+ <video
+ className="px-live"
+ src={`${videoBase}/${shown.id}/video`}
+ style={{
+ ...(turn?.key === `${shown.id}/video` ? turnStyle(turn.value, shapeOf(shown).w, shapeOf(shown).h, turn.zoom) : {}),
+ opacity: 0,
+ }}
+ autoPlay
+ playsInline
+ onTimeUpdate={(e) => {
+ const v = e.currentTarget;
+ if (v.style.opacity === "0" && v.currentTime > 0.04 && v.readyState >= 2 && turn?.key === `${shown.id}/video`) v.style.opacity = "1";
+ }}
+ onEnded={() => setMoving(null)}
+ onError={() => setMoving(null)}
+ />
+ </div>
)}
{/* Zoomed in, the whole picture: only then are its own pixels the ones seen. */}
{zoomed && (
@@ -3492,7 +3645,7 @@ export function PhotosView() {
"fixed" was fixed to the screen and a slideshow played inside a box, not the window. */}
{show && (
<Portal>
- <Slideshow photos={show.list} start={show.start} onClose={() => setShow(null)} />
+ <Slideshow ids={show.ids} start={show.start} load={(ids) => store.load(ids)} videoBase={videoBase} onClose={() => setShow(null)} />
</Portal>
)}
{adjusting && (
@@ -3502,7 +3655,7 @@ export function PhotosView() {
)}
{options && (
<Portal>
- <DownloadOptions photos={options} onPick={(w) => void downloadAs(options, w)} onClose={() => setOptions(null)} />
+ <DownloadOptions photos={options} onPick={(w) => void downloadAs(options.map((p) => p.id), w)} onClose={() => setOptions(null)} />
</Portal>
)}
<UploadPanel uploads={[...uploads.values()]} onDismiss={dismissUploads} cancel={api.photosUploadCancel} />
diff --git a/src/screens/RemindersView.tsx b/src/screens/RemindersView.tsx
index 5fc6471..cb0fc8a 100644
--- a/src/screens/RemindersView.tsx
+++ b/src/screens/RemindersView.tsx
@@ -1,6 +1,6 @@
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { fadeIn, fadeOut } from "../lib/fade";
-import { useActiveRef } from "../lib/screen";
+import { overlayOpen, useActiveRef } from "../lib/screen";
import { useModalFocus } from "../lib/focus";
import { listen } from "@tauri-apps/api/event";
import { usePending } from "../lib/pending";
@@ -13,7 +13,7 @@ import { SearchField } from "../components/SearchField";
import { PaneTitle } from "../components/PaneTitle";
import { Portal } from "../components/Portal";
import { TimeField } from "../components/TimeField";
-import { ChevronLeft, ListFilter, X } from "lucide-react";
+import { AlarmClock, ChevronLeft, Link2, ListFilter, MapPin, MessageCircle, X } from "lucide-react";
import {
api,
MOST_AT_ONCE,
@@ -25,7 +25,11 @@ import {
type ReminderCounts,
type SmartList,
remindersApi,
+ reminderImageSrc,
type ReminderDetail,
+ type ReminderMore,
+ type ReminderMarks,
+ type RepeatRule,
type ReminderSmartList,
type TagCount,
} from "../lib/ipc";
@@ -35,7 +39,9 @@ import { Picker } from "../components/Picker";
import { RowMenu } from "../components/RowMenu";
import { Glyph, emblemGlyph, type GlyphName } from "../components/Glyph";
import { dateText, timeText } from "../lib/when";
+import { parseReminder, understood, type QuickReminder } from "./reminderQuick.ts";
import { useReveal } from "../lib/reveal";
+import { instantIn, wallIn, zoneName, type Wall } from "./calendar/model";
/** Apple's built-in views, in Apple's order, each with the glyph and system colour its app uses. */
const SMART: { kind: SmartList; title: string; glyph: GlyphName; colour: string }[] = [
@@ -87,6 +93,13 @@ function daysApart(from: Date, to: Date): number {
* "9:30 PM" and not "Tomorrow 9:30 PM". Saying it twice is the sort of thing that makes a
* screen read as almost-right.
*/
+/** A repeat in words, as the phone's Repeat row says it: "Daily", "Every 2 Weeks". */
+function repeatWords(r: { frequency: number; interval: number }): string {
+ const unit = ["Day", "Week", "Month", "Year", "Hour"][r.frequency] ?? "Day";
+ if (r.interval === 1) return ["Daily", "Weekly", "Monthly", "Yearly", "Hourly"][r.frequency] ?? "Daily";
+ return `Every ${r.interval} ${unit}s`;
+}
+
function dueLabel(seconds: number, dated = false, allDay = false): { text: string; overdue: boolean } {
const due = new Date(seconds * 1000);
const now = new Date();
@@ -132,24 +145,53 @@ const PRIORITIES = [
const priorityMark = (priority: number) =>
PRIORITIES.find((p) => p.value === priority)?.mark ?? "";
-const REPEAT_UNITS = ["day", "week", "month", "year"] as const;
+/** Apple's frequencies by number: 0 daily, 1 weekly, 2 monthly, 3 yearly, 4 hourly. */
+const REPEAT_UNITS = ["day", "week", "month", "year", "hour"] as const;
-/** What Apple's own repeat menu offers. "never" is the absence of a rule, not a rule. */
-const REPEATS = [
+/**
+ * The iPhone's Repeat menu, in its order. Each preset is a frequency and an interval, which
+ * is how the phone writes them; Weekdays and Weekends are weekly with chosen days (1 Sunday …
+ * 7 Saturday), as the phone writes those.
+ */
+const WEEKDAYS = [2, 3, 4, 5, 6];
+const WEEKENDS = [1, 7];
+const REPEATS: { key: string; label: string; repeat: { frequency: number; interval: number } | null; days?: number[]; divider?: boolean; disabled?: boolean }[] = [
{ key: "never", label: "Never", repeat: null },
- { key: "0:1", label: "Every day", repeat: { frequency: 0, interval: 1 } },
- { key: "1:1", label: "Every week", repeat: { frequency: 1, interval: 1 } },
- { key: "1:2", label: "Every 2 weeks", repeat: { frequency: 1, interval: 2 } },
- { key: "2:1", label: "Every month", repeat: { frequency: 2, interval: 1 } },
- { key: "3:1", label: "Every year", repeat: { frequency: 3, interval: 1 } },
-] as const;
+ { key: "4:1", label: "Hourly", repeat: { frequency: 4, interval: 1 }, divider: true },
+ { key: "0:1", label: "Daily", repeat: { frequency: 0, interval: 1 } },
+ { key: "weekdays", label: "Weekdays", repeat: { frequency: 1, interval: 1 }, days: WEEKDAYS },
+ { key: "weekends", label: "Weekends", repeat: { frequency: 1, interval: 1 }, days: WEEKENDS },
+ { key: "1:1", label: "Weekly", repeat: { frequency: 1, interval: 1 } },
+ { key: "1:2", label: "Biweekly", repeat: { frequency: 1, interval: 2 } },
+ { key: "2:1", label: "Monthly", repeat: { frequency: 2, interval: 1 } },
+ { key: "2:3", label: "Every 3 Months", repeat: { frequency: 2, interval: 3 } },
+ { key: "2:6", label: "Every 6 Months", repeat: { frequency: 2, interval: 6 } },
+ { key: "3:1", label: "Yearly", repeat: { frequency: 3, interval: 1 } },
+ { key: "custom", label: "Custom", repeat: null, divider: true },
+];
+/** The Custom screen's Frequency menu, in the phone's order. */
+const FREQUENCIES = [
+ { value: "4", label: "Hourly" },
+ { value: "0", label: "Daily" },
+ { value: "1", label: "Weekly" },
+ { value: "2", label: "Monthly" },
+ { value: "3", label: "Yearly" },
+];
+
+const sameDays = (a: number[], b: number[]) => a.length === b.length && a.every((d, i) => d === b[i]);
-/** Which choice a reminder's stored rule corresponds to, or a description of one we don't
- * offer — Apple allows schedules this menu deliberately doesn't try to express. */
-function repeatKey(r: Reminder): string {
+/** Which choice a reminder's rule is: a preset — Weekdays and Weekends by their days — or
+ * Custom for any other schedule. */
+function repeatKey(r: Reminder, rule?: RepeatRule | null, days: number[] = rule?.daysOfWeek ?? []): string {
if (r.recurFrequency === null || r.recurFrequency === undefined) return "never";
- const key = `${r.recurFrequency}:${r.recurInterval ?? 1}`;
- return REPEATS.some((option) => option.key === key) ? key : "custom";
+ if (rule && rule.other.length > 0) return "custom";
+ const every = r.recurInterval ?? 1;
+ if (days.length > 0) {
+ if (r.recurFrequency !== 1 || every !== 1) return "custom";
+ return sameDays(days, WEEKDAYS) ? "weekdays" : sameDays(days, WEEKENDS) ? "weekends" : "custom";
+ }
+ const key = `${r.recurFrequency}:${every}`;
+ return REPEATS.some((option) => option.key === key && option.repeat && !option.days) ? key : "custom";
}
/** "Every day", "Every 2 weeks" — or null when this happens only once. */
@@ -167,10 +209,15 @@ function repeatLabel(r: Reminder): string | null {
* The arrow alone says something repeats without saying how often, which is the one thing
* worth knowing about it at a glance.
*/
-function repeatWord(r: Reminder): string | null {
+function repeatWord(r: Reminder, days: number[] = []): string | null {
if (r.recurFrequency === null || r.recurFrequency === undefined) return null;
+ if (r.recurFrequency === 1 && (r.recurInterval ?? 1) === 1 && days.length > 0) {
+ if (sameDays(days, WEEKDAYS)) return "Weekdays";
+ if (sameDays(days, WEEKENDS)) return "Weekends";
+ return days.map((d) => WEEKDAY_SHORT[d - 1]).join(", ");
+ }
if ((r.recurInterval ?? 1) > 1) return repeatLabel(r);
- return ["Daily", "Weekly", "Monthly", "Yearly"][r.recurFrequency] ?? "Repeats";
+ return ["Daily", "Weekly", "Monthly", "Yearly", "Hourly"][r.recurFrequency] ?? "Repeats";
}
/**
@@ -199,24 +246,58 @@ const asShown = (r: Reminder): Reminder =>
/**
- * Tags, links, early alerts and sections can be changed from here once Apple's side of those
- * writes is switched on. Mirrors `REMINDER_DETAIL_WRITES` in
+ * Tags, links, early alerts and sections can be changed from here: on since each was seen on
+ * his iPhone as written (2026-10-22). Mirrors `REMINDER_DETAIL_WRITES` in
* crates/quince-icloud/src/reminders_details.rs: turn both on together.
*/
-export const REMINDER_DETAIL_WRITES = false;
+export const REMINDER_DETAIL_WRITES = true;
/** Apple's early-alert units, by its numbering. */
const ALERT_UNITS = ["minute", "hour", "day", "week", "month"] as const;
-/** "30 minutes early", "1 day early". */
+/** "30 minutes before", "1 day before" — the phone's Early Reminder words. */
function earlyText(count: number, unit: number): string {
const word = ALERT_UNITS[unit] ?? "minute";
- return `${count} ${word}${count === 1 ? "" : "s"} early`;
+ return `${count} ${word}${count === 1 ? "" : "s"} before`;
}
/** What the phone's Early Reminder menu offers, as [count, unit]. */
const EARLY_CHOICES: [number, number][] = [
[5, 0], [15, 0], [30, 0], [1, 1], [2, 1], [1, 2], [2, 2], [1, 3], [1, 4],
];
+/** This computer's own zone. */
+const LOCAL_ZONE = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
+/** "11:00 AM GMT-4": a time on another zone's clock, as the phone writes it in a row. */
+function zonedClock(zone: string, s: number): string {
+ try {
+ const time = new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit", timeZone: zone }).format(new Date(s * 1000));
+ return `${time} ${zoneName(zone, s).offset.replace("−", "-")}`;
+ } catch {
+ return "";
+ }
+}
+/** A link as the phone's chip shows it: its site, without "www.". */
+const hostOf = (url: string) => {
+ try {
+ return new URL(url).hostname.replace(/^www\./, "");
+ } catch {
+ return url.replace(/^https?:\/\//, "").replace(/\/.*$/, "");
+ }
+};
+
+/** The zone a reminder's time is read in: its own, or this computer's. */
+const zoneOf = (r: Reminder) => r.timezone || LOCAL_ZONE;
+/** This computer's clock reading at `s`. */
+const localWall = (s: number): Wall => {
+ const d = new Date(s * 1000);
+ return { y: d.getFullYear(), m: d.getMonth() + 1, d: d.getDate(), h: d.getHours(), min: d.getMinutes() };
+};
+/** "2026-10-22" and "11:00" on the clock of `zone`, as an instant. */
+function timedInstant(day: string, time: string, zone: string): number {
+ const [y, m, d] = day.split("-").map(Number);
+ const [h, min] = time.split(":").map(Number);
+ return instantIn(zone, { y, m, d, h, min });
+}
+
/** A smart list's own colour, or Apple's grey for one that has none. */
const smartColour = (s: ReminderSmartList) =>
s.colour && /^#[0-9a-f]{6}$/i.test(s.colour) ? s.colour : "var(--sys-gray)";
@@ -290,7 +371,18 @@ export function RemindersView() {
const [syncing, setSyncing] = useState(false);
/** Every reminder with a write still on its way — a set, since several can be at once. */
const [openGuid, setOpenGuid] = useState<string | null>(null);
+ /** The reminder open now — read after an await, when the one open before it may have changed. */
+ const openRef = useRef<string | null>(null);
+ openRef.current = openGuid;
const [draft, setDraft] = useState("");
+ /** The line is added exactly as typed, its dates and marks left in the title (the preview's
+ * Add as Typed). Cleared once the line changes or is added. */
+ const [literal, setLiteral] = useState(false);
+ const quick = useMemo<QuickReminder | null>(() => {
+ if (literal || !draft.trim()) return null;
+ const q = parseReminder(draft);
+ return understood(q) ? q : null;
+ }, [draft, literal]);
const [newList, setNewList] = useState("");
const [addingList, setAddingList] = useState(false);
const [renaming, setRenaming] = useState<string | null>(null);
@@ -315,6 +407,12 @@ export function RemindersView() {
const [unknownRules, setUnknownRules] = useState<string[]>([]);
/** The open reminder's tags, link and early alerts. */
const [detailOf, setDetailOf] = useState<ReminderDetail | null>(null);
+ /** The rest of the open reminder's Details: its repeat whole, zone, Urgent, place, person. */
+ const [moreOf, setMoreOf] = useState<ReminderMore | null>(null);
+ /** Each row's marks beside its date, by reminder: Weekdays, Urgent, a place, a person, a link. */
+ const [marks, setMarks] = useState<Map<string, ReminderMarks>>(() => new Map());
+ /** Repeating reminders whose next tick is their last: past End Repeat, ticked means done. */
+ const [ending, setEnding] = useState<Set<string>>(() => new Set());
/** A repeating reminder that was just ticked forward, and where it landed. */
const [moved, setMoved] = useState<{ guid: string; text: string } | null>(
null,
@@ -582,10 +680,12 @@ export function RemindersView() {
// Read by the click itself: a double-click's second click comes before the redraw.
const held = useRef(new Set<string>());
const SETTLE_MS = 1500;
+ /** Whether ticking it moves it on: a repeat, unless this is the last time before its end. */
+ const rollsOn = (r: Reminder) => repeatLabel(r) !== null && !ending.has(r.guid);
const toggle = (r: Reminder) => {
if (r.guid.startsWith(STAND_IN)) return;
const wasOpen = !r.completedAt;
- const repeating = repeatLabel(r) !== null;
+ const repeating = rollsOn(r);
if (repeating) {
// Not taken while it settles, nor until Apple has the tick before; once it shows open
// again with its next date, a tick counts.
@@ -608,7 +708,8 @@ export function RemindersView() {
// has made it (waiting for that, a tick on one showed nothing at all for a second or two).
setItems(patch(r.guid, { completedAt: wasOpen ? Math.floor(Date.now() / 1000) : null }));
// Only where completed reminders are hidden, and never for a repeating one, which rolls on.
- if (wasOpen && !showDone && repeatLabel(r) === null) depart(r.guid);
+ // Its last time before End Repeat is a completion too, as on the phone.
+ if (wasOpen && !showDone && !repeating) depart(r.guid);
else stay(r.guid);
const before = ticks.current.get(r.guid) ?? Promise.resolve();
const next = before.then(() => send(r, wasOpen));
@@ -626,7 +727,7 @@ export function RemindersView() {
patch(r.guid, { completedAt: wasOpen ? Math.floor(Date.now() / 1000) : null }),
);
if (!fresh) stay(r.guid);
- if (!fresh || !wasOpen || repeatLabel(r) === null) return;
+ if (!fresh || !wasOpen || !rollsOn(r)) return;
const after = fresh.find((x) => x.guid === r.guid);
if (after && after.dueAt !== null && after.dueAt !== r.dueAt) {
setMoved({ guid: r.guid, text: dueLabel(after.dueAt).text });
@@ -656,21 +757,43 @@ export function RemindersView() {
/** A date, and whether it has a time — the phone's Date and Time switches. */
const setDue = (r: Reminder, day: string, time: string | null) => {
const allDay = Boolean(day) && time === null;
- const dueAt = !day ? null : allDay ? dayToUtc(day) : Math.floor(new Date(`${day}T${time}`).getTime() / 1000);
+ // A time is read on the clock of the zone it is kept in, as the phone reads it: 11:00 in
+ // New York stays 11:00 in New York, whatever this computer's own clock says.
+ const dueAt = !day ? null : allDay ? dayToUtc(day) : timedInstant(day, time ?? "09:00", zoneOf(r));
return write(
r,
() => api.reminderEdit(r.guid, r.listGuid, { dueAt, allDay }),
patch(r.guid, { dueAt: allDay && dueAt !== null ? dayToLocal(dueAt) : dueAt, allDay }),
);
};
- const setNotes = (r: Reminder, notes: string) =>
- write(r, () =>
+ const setNotes = (r: Reminder, notes: string) => {
+ // Only a real change is sent: leaving the field as it was sent the notes as shown, which
+ // could be older than an edit made on the phone that had not arrived yet — and replace it.
+ if ((notes.trim() || null) === (r.notes?.trim() || null)) return;
+ return write(r, () =>
api.reminderEdit(r.guid, r.listGuid, { notes: notes.trim() || null }),
);
- const setRepeat = (r: Reminder, key: string) => {
- const chosen = REPEATS.find((option) => option.key === key);
- if (!chosen) return Promise.resolve(null);
- return write(r, () => api.reminderSetRepeat(r.guid, r.listGuid, chosen.repeat));
+ };
+ /** A repeat, or none, and when it ends — shown at once, then sent. Changing how often keeps
+ * the end date, as the phone does. */
+ const setRepeat = (r: Reminder, repeat: { frequency: number; interval: number } | null, endAt: number | null, days: number[] = []) => {
+ const daysOfWeek = repeat?.frequency === 1 ? days : [];
+ setMoreOf((m) =>
+ m && m.guid === r.guid
+ ? { ...m, repeat: repeat ? { frequency: repeat.frequency, interval: repeat.interval, endAt, occurrenceCount: 0, daysOfWeek, other: [] } : null }
+ : m,
+ );
+ setMarks((was) => {
+ const next = new Map(was);
+ const at = next.get(r.guid) ?? { guid: r.guid, daysOfWeek: [], urgent: false, location: null, messaging: null, url: null };
+ next.set(r.guid, { ...at, daysOfWeek });
+ return next;
+ });
+ return write(
+ r,
+ () => api.reminderSetRepeat(r.guid, r.listGuid, repeat, repeat ? endAt : null, daysOfWeek),
+ patch(r.guid, { recurFrequency: repeat?.frequency ?? null, recurInterval: repeat?.interval ?? null }),
+ );
};
const setPriority = (r: Reminder, priority: number) =>
write(r, () => api.reminderEdit(r.guid, r.listGuid, { priority }));
@@ -710,6 +833,47 @@ export function RemindersView() {
useEffect(() => {
void readDetail(openGuid);
}, [openGuid, readDetail, revision, outbox.tick]);
+ useEffect(() => {
+ let live = true;
+ remindersApi
+ .ending()
+ .then((guids) => live && setEnding(new Set(guids)))
+ .catch(() => {});
+ return () => {
+ live = false;
+ };
+ }, [revision, outbox.tick, items.length, moreOf?.repeat?.endAt]);
+ // The rows' marks, read again when the rows or Apple's copy change.
+ const markKey = items.map((r) => r.guid).join(",");
+ useEffect(() => {
+ const guids = items.filter((r) => !r.guid.startsWith(STAND_IN)).map((r) => r.guid);
+ if (!guids.length) return;
+ let live = true;
+ remindersApi
+ .marks(guids)
+ .then((found) => live && setMarks(new Map(found.map((m) => [m.guid, m]))))
+ .catch(() => {});
+ return () => {
+ live = false;
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [markKey, revision, outbox.tick]);
+ /** The rest of the open reminder's Details, read again with it. */
+ useEffect(() => {
+ const guid = openGuid;
+ if (!guid || guid.startsWith(STAND_IN)) {
+ setMoreOf(null);
+ return;
+ }
+ let live = true;
+ remindersApi
+ .more(guid)
+ .then((found) => live && setMoreOf(found))
+ .catch(() => live && setMoreOf((was) => (was?.guid === guid ? was : null)));
+ return () => {
+ live = false;
+ };
+ }, [openGuid, revision, outbox.tick]);
// Tags and smart lists hold what is still to do, so a change sent or ticked moves them.
useEffect(() => {
void readExtras().catch(() => {});
@@ -731,14 +895,16 @@ export function RemindersView() {
if (predict) {
setDetailOf((d) => (d && d.guid === r.guid ? predict(d) : d));
setTagsOf((m) => {
- const base = { guid: r.guid, tags: m.get(r.guid) ?? [], url: null, earlyAlerts: [], otherAttachments: 0 };
+ const base = { guid: r.guid, tags: m.get(r.guid) ?? [], url: null, earlyAlerts: [], otherAttachments: 0, images: [] };
const next = new Map(m);
next.set(r.guid, predict(base).tags);
return next;
});
}
await write(r, run);
- await Promise.all([readDetail(openGuid), readExtras().catch(() => {})]);
+ // The reminder open after the write, not the one open when it began: a write takes a few
+ // seconds, and re-reading the earlier one showed its details on whatever was opened since.
+ await Promise.all([readDetail(openRef.current), readExtras().catch(() => {})]);
};
const tagAdd = (r: Reminder, raw: string) => {
const name = raw.trim().replace(/^#+/, "").replace(/\s+/g, "");
@@ -836,8 +1002,9 @@ export function RemindersView() {
const keys = useRef<(e: KeyboardEvent) => void>(() => {});
keys.current = (e: KeyboardEvent) => {
if (!live.current || e.defaultPrevented) return;
- // A menu, a picker's list or a sheet over the screen has the keys to itself.
- if (document.querySelector('[role="menu"], [role="listbox"], [role="dialog"], [role="alertdialog"]')) return;
+ // A menu, a picker's list or a sheet over the screen has the keys to itself — not another
+ // screen's own list (Photos' grid stays mounted once visited), which overlayOpen skips.
+ if (overlayOpen()) return;
const target = e.target as HTMLElement | null;
const typing = !!target?.closest?.("input, textarea, select, [contenteditable]");
const command = (e.ctrlKey || e.metaKey) && !e.altKey;
@@ -1006,8 +1173,12 @@ export function RemindersView() {
async function add(e: React.FormEvent) {
e.preventDefault();
- const title = draft.trim();
- if (!title || !targetListGuid) return;
+ const typed = draft.trim();
+ if (!typed || !targetListGuid) return;
+ // What the line said beyond its title, as the preview showed it.
+ const said = quick;
+ const title = said ? said.title : typed;
+ setLiteral(false);
setSyncing(true);
setError(null);
// What the view implies, as on the phone: typed into Today or Scheduled it is due today,
@@ -1016,12 +1187,24 @@ export function RemindersView() {
const today = new Date();
const pad2 = (n: number) => String(n).padStart(2, "0");
const todayKey = `${today.getFullYear()}-${pad2(today.getMonth() + 1)}-${pad2(today.getDate())}`;
- const implied =
+ const keyOf = (d: Date) => `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
+ const viewImplied: { dueAt?: number; allDay?: boolean; flagged?: boolean } =
kind === "today" || kind === "scheduled"
? { dueAt: dayToUtc(todayKey), allDay: true }
: kind === "flagged"
? { flagged: true }
: {};
+ // A day or time typed wins over the one the view implies; a day is kept as Apple keeps
+ // one (that day's midnight in UTC), a time as the moment it is.
+ const implied: { dueAt?: number; allDay?: boolean; flagged?: boolean } =
+ said?.dueAt != null
+ ? {
+ ...viewImplied,
+ ...(said.allDay
+ ? { dueAt: dayToUtc(keyOf(new Date(said.dueAt * 1000))), allDay: true }
+ : { dueAt: said.dueAt, allDay: false }),
+ }
+ : viewImplied;
// The row is there the moment Return is pressed, and the field is ready for the next.
const standIn = `${STAND_IN}${Date.now()}`;
setDraft("");
@@ -1031,14 +1214,19 @@ export function RemindersView() {
...rows,
{
guid: standIn, listGuid: targetListGuid, title, notes: null,
- dueAt: implied.dueAt !== undefined ? dayToLocal(implied.dueAt) : null,
+ dueAt: implied.dueAt === undefined ? null : implied.allDay ? dayToLocal(implied.dueAt) : implied.dueAt,
allDay: implied.allDay ?? false,
- completedAt: null, priority: 0, flagged: implied.flagged ?? false, parentGuid: null,
- recurFrequency: null, recurInterval: null, etag: null,
+ completedAt: null, priority: said?.priority ?? 0, flagged: implied.flagged ?? false, parentGuid: null,
+ recurFrequency: said?.repeat?.frequency ?? null, recurInterval: said?.repeat?.interval ?? null, etag: null,
} as Reminder,
]);
try {
const made = await api.reminderCreate(targetListGuid, title, implied);
+ // The priority and repeat the line named, through the same edits the detail panel makes.
+ if (said && typeof made === "string" && made) {
+ if (said.priority) await api.reminderEdit(made, targetListGuid, { priority: said.priority }).catch((e) => setError(messageOf(e)));
+ if (said.repeat) await api.reminderSetRepeat(made, targetListGuid, said.repeat).catch((e) => setError(messageOf(e)));
+ }
// Typed into a tag, it carries the tag, as on the phone.
if (tagged && REMINDER_DETAIL_WRITES && typeof made === "string" && made) {
await remindersApi.tagAdd(made, tagged).catch((e) => setError(messageOf(e)));
@@ -1047,7 +1235,7 @@ export function RemindersView() {
await readItems();
} catch (err) {
setItems((rows) => rows.filter((r) => r.guid !== standIn));
- setDraft((d) => d || title);
+ setDraft((d) => d || typed);
setError(messageOf(err));
} finally {
setSyncing(false);
@@ -1408,7 +1596,10 @@ export function RemindersView() {
</span>
<input
value={draft}
- onChange={(e) => setDraft(e.target.value)}
+ onChange={(e) => {
+ setDraft(e.target.value);
+ setLiteral(false);
+ }}
placeholder="New Reminder"
aria-label={
inList ? `Add a reminder to ${heading}` : `Add a reminder to ${targetList?.title ?? "a list"}`
@@ -1425,6 +1616,22 @@ export function RemindersView() {
options={lists.map((l) => ({ value: l.guid, label: l.title }))}
/>
)}
+ {quick && (
+ <div className="rx-add-understood" role="status">
+ <span className="rx-add-reading">
+ {[
+ quick.dueAt !== null && dueLabel(quick.dueAt, false, quick.allDay).text,
+ quick.repeat && repeatWords(quick.repeat),
+ quick.priority === 1 ? "High priority" : quick.priority === 5 ? "Medium priority" : quick.priority === 9 ? "Low priority" : null,
+ ]
+ .filter(Boolean)
+ .join(" · ")}
+ </span>
+ <button type="button" className="rx-add-literal" onClick={() => setLiteral(true)}>
+ Add as Typed
+ </button>
+ </div>
+ )}
</form>
);
@@ -1657,6 +1864,13 @@ export function RemindersView() {
const justMoved = moved?.guid === reminder.guid ? moved.text : null;
const home = lists.find((l) => l.guid === reminder.listGuid);
const mark = priorityMark(reminder.priority);
+ const rowMarks = marks.get(reminder.guid);
+ // Kept in another zone, the phone adds that zone's clock: "8:30 PM (11:00 AM GMT-4)".
+ const elsewhere =
+ due && reminder.dueAt !== null && !reminder.allDay && reminder.timezone && reminder.timezone !== LOCAL_ZONE
+ ? zonedClock(reminder.timezone, reminder.dueAt)
+ : null;
+ const chips = rowMarks && (rowMarks.location || rowMarks.messaging || rowMarks.url) ? rowMarks : null;
const rowTags =
isOpen && detailOf?.guid === reminder.guid ? detailOf.tags : (tagsOf.get(reminder.guid) ?? []);
return (
@@ -1812,7 +2026,7 @@ export function RemindersView() {
<span className="rx-notes">{reminder.notes}</span>
)}
<Waiting shown={outbox.waiting.has(reminder.guid)} />
- {(due || repeat || justMoved || (showListName && home) || rowTags.length > 0) && (
+ {(due || repeat || justMoved || (showListName && home) || rowTags.length > 0 || rowMarks?.urgent) && (
<span className="rx-meta">
{justMoved ? (
<span className="rx-moved" role="status">
@@ -1825,15 +2039,20 @@ export function RemindersView() {
)}
{due && (
<span className={`rx-due${due.overdue ? " overdue" : ""}`}>
- {due.text}
+ {elsewhere ? `${due.text} (${elsewhere})` : due.text}
</span>
)}
{repeat && (
<span className="rx-repeat" title={repeat}>
- <span aria-hidden="true">↻</span> {repeatWord(reminder)}
+ <span aria-hidden="true">↻</span> {repeatWord(reminder, rowMarks?.daysOfWeek)}
<span className="visually-hidden">{repeat}</span>
</span>
)}
+ {rowMarks?.urgent && (
+ <span className="rx-urgent" role="img" aria-label="Urgent" title="Urgent">
+ <AlarmClock aria-hidden="true" size={13} strokeWidth={2} />
+ </span>
+ )}
{rowTags.map((name) => (
<button
key={name}
@@ -1850,6 +2069,30 @@ export function RemindersView() {
)}
</span>
)}
+ {chips && !justMoved && (
+ <span className="rx-chips">
+ {chips.location && (
+ <span className="rx-chip">
+ <MapPin aria-hidden="true" size={12} strokeWidth={2.2} className="rx-chip-place" />
+ {chips.location.proximity && <b>{chips.location.proximity === "arriving" ? "Arriving:" : "Leaving:"}</b>}
+ {chips.location.title ?? "A place"}
+ </span>
+ )}
+ {chips.messaging && (
+ <span className="rx-chip">
+ <MessageCircle aria-hidden="true" size={12} strokeWidth={2.2} />
+ <b>Messaging:</b>
+ {chips.messaging}
+ </span>
+ )}
+ {chips.url && (
+ <a className="rx-chip rx-chip-link" href={chips.url} target="_blank" rel="noreferrer" tabIndex={-1} title={chips.url}>
+ <Link2 aria-hidden="true" size={12} strokeWidth={2.2} />
+ {hostOf(chips.url)}
+ </a>
+ )}
+ </span>
+ )}
{isOpen && (
<div className="rx-detail" role="group" aria-label={`Info for ${reminder.title}`}>
@@ -1871,33 +2114,17 @@ export function RemindersView() {
/>
<div className="rx-detail-rule" aria-hidden="true" />
<DueField reminder={reminder} onChange={(day, time) => void setDue(reminder, day, time)} />
+ {moreOf?.guid === reminder.guid && <ZoneAndUrgent reminder={reminder} more={moreOf} />}
<EarlyField
reminder={reminder}
alerts={detailOf?.guid === reminder.guid ? detailOf.earlyAlerts : []}
onChange={(alert) => void setEarly(reminder, alert)}
/>
- <div className="rx-field">
- <span>Repeat</span>
- <Picker
- label={`Repeat for ${reminder.title}`}
- value={repeatKey(reminder)}
- disabled={reminder.dueAt === null}
- onChange={(key) => void setRepeat(reminder, key)}
- options={
- repeatKey(reminder) === "custom"
- ? [
- // A schedule this menu doesn't express must still be
- // shown, and choosing anything else would replace it.
- { value: "custom", label: repeat ?? "Custom" },
- ...REPEATS.map((o) => ({ value: o.key, label: o.label })),
- ]
- : REPEATS.map((o) => ({ value: o.key, label: o.label }))
- }
- />
- </div>
- {reminder.dueAt === null && (
- <p className="rx-hint">Add a date to repeat it.</p>
- )}
+ <RepeatField
+ reminder={reminder}
+ rule={moreOf?.guid === reminder.guid ? moreOf.repeat : null}
+ onChange={(repeat, endAt, days) => void setRepeat(reminder, repeat, endAt, days)}
+ />
<div className="rx-detail-rule" aria-hidden="true" />
<TagsField
reminder={reminder}
@@ -1906,6 +2133,23 @@ export function RemindersView() {
onAdd={(name) => void tagAdd(reminder, name)}
onRemove={(name) => void tagRemove(reminder, name)}
/>
+ <div className="rx-field">
+ <span>Subtasks</span>
+ <span className="rx-value">{items.filter((x) => x.parentGuid === reminder.guid).length}</span>
+ </div>
+ <div className="rx-field">
+ <span>Flag</span>
+ <label className="rx-switch">
+ <input
+ type="checkbox"
+ role="switch"
+ aria-label={`Flag for ${reminder.title}`}
+ checked={reminder.flagged}
+ onChange={() => void flag(reminder)}
+ />
+ <span className="switch" aria-hidden="true" />
+ </label>
+ </div>
<div className="rx-field">
<span>Priority</span>
<Picker
@@ -1918,6 +2162,34 @@ export function RemindersView() {
}))}
/>
</div>
+ {moreOf?.guid === reminder.guid && <PlacesAndPeople more={moreOf} />}
+ {detailOf?.guid === reminder.guid && detailOf.images.length > 0 && (
+ <div className="rx-images" role="list" aria-label="Pictures">
+ {detailOf.images.map((id) => (
+ <img
+ key={id}
+ role="listitem"
+ className="rx-image"
+ src={reminderImageSrc(id)}
+ alt="Attached picture"
+ loading="lazy"
+ decoding="async"
+ draggable={false}
+ />
+ ))}
+ </div>
+ )}
+ {(detailOf?.guid === reminder.guid ? detailOf.otherAttachments - detailOf.images.length : 0) > 0 && (
+ <div className="rx-field">
+ <span>Attachments</span>
+ <span className="rx-value">
+ {detailOf!.otherAttachments - detailOf!.images.length === 1
+ ? "1 file"
+ : `${detailOf!.otherAttachments - detailOf!.images.length} files`}
+ </span>
+ </div>
+ )}
+ <div className="rx-detail-rule" aria-hidden="true" />
<div className="rx-field">
<span>List</span>
<Picker
@@ -2212,10 +2484,11 @@ function ListInfo({ list, onClose, onDone }: {
* day — all day, no alert; on, at the time chosen. Each change is saved when it is made.
*/
function DueField({ reminder, onChange }: { reminder: Reminder; onChange: (day: string, time: string | null) => void }) {
- const at = reminder.dueAt === null ? null : new Date(reminder.dueAt * 1000);
+ // Read on the clock of the reminder's own zone, where it has one.
+ const w = reminder.dueAt === null ? null : reminder.allDay ? localWall(reminder.dueAt) : wallIn(zoneOf(reminder), reminder.dueAt);
const pad = (n: number) => String(n).padStart(2, "0");
- const day = at ? `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())}` : "";
- const time = at && !reminder.allDay ? `${pad(at.getHours())}:${pad(at.getMinutes())}` : null;
+ const day = w ? `${w.y}-${pad(w.m)}-${pad(w.d)}` : "";
+ const time = w && !reminder.allDay ? `${pad(w.h)}:${pad(w.min)}` : null;
return (
<div className="rx-field">
<span>Date</span>
@@ -2241,12 +2514,12 @@ function DueField({ reminder, onChange }: { reminder: Reminder; onChange: (day:
<span className="switch" aria-hidden="true" />
<span>Time</span>
</label>
- {time !== null && at && (
+ {time !== null && w && (
<TimeField
className="field"
label={`Time of day for ${reminder.title}`}
- hours={at.getHours()}
- minutes={at.getMinutes()}
+ hours={w.h}
+ minutes={w.min}
onChange={(h, m) => onChange(day, `${pad(h)}:${pad(m)}`)}
/>
)}
@@ -2272,7 +2545,7 @@ function UrlField({ reminder, url, onSave }: { reminder: Reminder; url: string |
);
}
return (
- <label className="rx-field">
+ <label className="rx-field rx-field-url">
<span>URL</span>
<input
className="field"
@@ -2293,6 +2566,11 @@ function UrlField({ reminder, url, onSave }: { reminder: Reminder; url: string |
}
}}
/>
+ {url && /^(https?:|mailto:)/i.test(url) && (
+ <a className="rx-url rx-url-open" href={url} target="_blank" rel="noreferrer" title={url}>
+ Open
+ </a>
+ )}
</label>
);
}
@@ -2308,7 +2586,7 @@ function EarlyField({ reminder, alerts, onChange }: {
if (!alerts.length) return null;
return (
<div className="rx-field">
- <span>Early alert</span>
+ <span>Early Reminder</span>
<span className="rx-value">{said}</span>
</div>
);
@@ -2318,9 +2596,9 @@ function EarlyField({ reminder, alerts, onChange }: {
const known = EARLY_CHOICES.some(([c, u]) => `${c}:${u}` === now);
return (
<div className="rx-field">
- <span>Early alert</span>
+ <span>Early Reminder</span>
<Picker
- label={`Early alert for ${reminder.title}`}
+ label={`Early reminder for ${reminder.title}`}
value={now}
onChange={(v) => {
if (v === now) return;
@@ -2389,3 +2667,274 @@ function TagsField({ reminder, tags, onOpen, onAdd, onRemove }: {
</div>
);
}
+
+/** The weekday, month-day or month a rule falls on by its due date, as the phone preselects. */
+const WEEKDAY_LETTERS = ["S", "M", "T", "W", "T", "F", "S"];
+const WEEKDAY_SHORT = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
+const WEEKDAY_NAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
+const MONTH_SHORT = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+
+/** "every day", "every 2 weeks", "every hour". */
+function everyText(frequency: number, interval: number): string {
+ const unit = REPEAT_UNITS[frequency] ?? "day";
+ return interval > 1 ? `every ${interval} ${unit}s` : `every ${unit}`;
+}
+
+/** The end of a day, on the clock of `zone`: an end date takes in every time on that day. */
+const endOfDayIn = (day: string, zone: string) => timedInstant(day, "23:59", zone);
+
+/**
+ * Repeat, as the iPhone lays it out: the preset menu; Custom's Frequency and Every, with the
+ * days the rule falls on; then End Repeat, Never or On Date. Each change is shown at once
+ * and saved as it is made.
+ */
+function RepeatField({ reminder, rule, onChange }: {
+ reminder: Reminder;
+ rule: RepeatRule | null;
+ onChange: (repeat: { frequency: number; interval: number } | null, endAt: number | null, days?: number[]) => void;
+}) {
+ const [customOpen, setCustomOpen] = useState(false);
+ const days = rule?.daysOfWeek ?? [];
+ useEffect(() => setCustomOpen(false), [reminder.guid]);
+ const repeating = reminder.recurFrequency !== null && reminder.recurFrequency !== undefined;
+ const frequency = reminder.recurFrequency ?? 0;
+ const interval = reminder.recurInterval ?? 1;
+ const endAt = rule?.endAt ?? null;
+ const key = repeatKey(reminder, rule, days);
+ const custom = repeating && (customOpen || key === "custom");
+ const dated = reminder.dueAt !== null;
+ const zone = zoneOf(reminder);
+ const pad = (n: number) => String(n).padStart(2, "0");
+ const endWall = endAt === null ? null : wallIn(zone, endAt);
+ const endDay = endWall ? `${endWall.y}-${pad(endWall.m)}-${pad(endWall.d)}` : "";
+ const [typed, setTyped] = useState(String(interval));
+ useEffect(() => setTyped(String(interval)), [interval, reminder.guid]);
+ const commitEvery = (raw: string) => {
+ const n = Math.max(1, Math.min(999, Math.round(Number(raw)) || 1));
+ setTyped(String(n));
+ if (n !== interval) onChange({ frequency, interval: n }, endAt, days);
+ };
+ // The day the rule falls on, read from the due date on its own zone's clock.
+ const due = reminder.dueAt === null ? null : reminder.allDay ? localWall(reminder.dueAt) : wallIn(zone, reminder.dueAt);
+ const dueWeekday = due ? new Date(Date.UTC(due.y, due.m - 1, due.d)).getUTCDay() : -1;
+ const fromPhone = (rule?.other.length ?? 0) > 0;
+ const on = (() => {
+ if (fromPhone) return "on the days chosen on your iPhone";
+ if (!due) return "";
+ if (frequency === 1) {
+ const on = days.length ? days : [dueWeekday + 1];
+ return `on ${on.map((d) => WEEKDAY_NAMES[d - 1]).join(", ").replace(/, ([^,]*)$/, " and $1")}`;
+ }
+ if (frequency === 2) return `on day ${due.d}`;
+ if (frequency === 3) return `in ${MONTH_SHORT[due.m - 1]}`;
+ return "";
+ })();
+ return (
+ <>
+ <div className="rx-field">
+ <span>Repeat</span>
+ <Picker
+ label={`Repeat for ${reminder.title}`}
+ value={custom ? "custom" : key}
+ disabled={!dated && !repeating}
+ onChange={(k) => {
+ if (k === "custom") {
+ setCustomOpen(true);
+ // The phone's Custom starts at Daily, every 1.
+ if (!repeating) onChange({ frequency: 0, interval: 1 }, null);
+ return;
+ }
+ const chosen = REPEATS.find((o) => o.key === k);
+ if (!chosen || chosen.disabled) return;
+ setCustomOpen(false);
+ onChange(chosen.repeat, chosen.repeat ? endAt : null, chosen.days ?? []);
+ }}
+ options={REPEATS.map((o) => ({ value: o.key, label: o.label, divider: o.divider, disabled: o.disabled }))}
+ />
+ </div>
+ {!dated && !repeating && <p className="rx-hint">Add a date to repeat it.</p>}
+ {custom && (
+ <div className="rx-custom" role="group" aria-label={`Custom repeat for ${reminder.title}`}>
+ <div className="rx-field">
+ <span>Frequency</span>
+ <Picker
+ label={`Frequency for ${reminder.title}`}
+ value={String(frequency)}
+ options={FREQUENCIES}
+ onChange={(f) => Number(f) !== frequency && onChange({ frequency: Number(f), interval }, endAt, Number(f) === 1 ? days : [])}
+ />
+ </div>
+ <div className="rx-field">
+ <span>Every</span>
+ <span className="rx-every">
+ <button
+ type="button"
+ className="rx-step"
+ aria-label="Fewer"
+ disabled={interval <= 1}
+ onClick={() => commitEvery(String(interval - 1))}
+ >
+ −
+ </button>
+ <input
+ className="field rx-every-count"
+ inputMode="numeric"
+ aria-label={`Every how many ${REPEAT_UNITS[frequency] ?? "day"}s`}
+ value={typed}
+ onChange={(e) => setTyped(e.target.value.replace(/\D/g, "").slice(0, 3))}
+ onBlur={(e) => commitEvery(e.target.value)}
+ onKeyDown={(e) => e.key === "Enter" && e.currentTarget.blur()}
+ />
+ <button type="button" className="rx-step" aria-label="More" disabled={interval >= 999} onClick={() => commitEvery(String(interval + 1))}>
+ +
+ </button>
+ <span className="rx-every-unit">{REPEAT_UNITS[frequency] ?? "day"}{interval === 1 ? "" : "s"}</span>
+ </span>
+ </div>
+ {frequency === 1 && (
+ <div className="rx-days" role="group" aria-label="Days of the week">
+ {WEEKDAY_LETTERS.map((letter, i) => {
+ // The days it falls on; none chosen is its due date's day, as the phone shows.
+ const on = days.length ? days.includes(i + 1) : i === dueWeekday;
+ return (
+ <button
+ key={i}
+ type="button"
+ className={`rx-day is-pick${on ? " is-on" : ""}`}
+ aria-label={WEEKDAY_NAMES[i]}
+ aria-pressed={on}
+ disabled={fromPhone}
+ onClick={() => {
+ const now = days.length ? days : dueWeekday >= 0 ? [dueWeekday + 1] : [];
+ const next = now.includes(i + 1) ? now.filter((d) => d !== i + 1) : [...now, i + 1].sort((a, b) => a - b);
+ // The last day off is its due date's day again, as the phone keeps one.
+ onChange({ frequency, interval }, endAt, next.length === 1 && next[0] === dueWeekday + 1 ? [] : next);
+ }}
+ >
+ {letter}
+ </button>
+ );
+ })}
+ </div>
+ )}
+ {frequency === 2 && (
+ <div className="rx-days is-month" role="group" aria-label="Days of the month">
+ {Array.from({ length: 31 }, (_, i) => i + 1).map((d) => (
+ <span key={d} className={`rx-day${!fromPhone && due?.d === d ? " is-on" : ""}`}
+ aria-current={!fromPhone && due?.d === d ? "true" : undefined}>
+ {d}
+ </span>
+ ))}
+ </div>
+ )}
+ {frequency === 3 && (
+ <div className="rx-days is-year" role="group" aria-label="Months of the year">
+ {MONTH_SHORT.map((m, i) => (
+ <span key={m} className={`rx-day${!fromPhone && due?.m === i + 1 ? " is-on" : ""}`}
+ aria-current={!fromPhone && due?.m === i + 1 ? "true" : undefined}>
+ {m}
+ </span>
+ ))}
+ </div>
+ )}
+ <p className="rx-hint rx-custom-hint">
+ {`Repeats ${everyText(frequency, interval)}${on ? ` ${on}` : ""}.`}
+ {frequency >= 2 && frequency <= 3 && !fromPhone && " Pick other days on your iPhone or iPad."}
+ </p>
+ </div>
+ )}
+ {repeating && (
+ <div className="rx-field">
+ <span>End Repeat</span>
+ <div className="rx-due">
+ <Picker
+ label={`End repeat for ${reminder.title}`}
+ value={endAt === null ? "never" : "date"}
+ options={[
+ { value: "never", label: "Never" },
+ { value: "date", label: "On Date" },
+ ]}
+ onChange={(v) => {
+ if (v === "never" && endAt !== null) onChange({ frequency, interval }, null, days);
+ if (v === "date" && endAt === null && due) {
+ // A month on from the day it is due, to start from.
+ const at = new Date(Date.UTC(due.y, due.m, due.d));
+ onChange({ frequency, interval }, endOfDayIn(`${at.getUTCFullYear()}-${pad(at.getUTCMonth() + 1)}-${pad(at.getUTCDate())}`, zone), days);
+ }
+ }}
+ />
+ {endAt !== null && (
+ <input
+ type="date"
+ className="field rx-due-day"
+ aria-label={`End repeat date for ${reminder.title}`}
+ defaultValue={endDay}
+ key={`e${endAt}`}
+ min={due ? `${due.y}-${pad(due.m)}-${pad(due.d)}` : undefined}
+ onBlur={(e) => e.target.value && e.target.value !== endDay && onChange({ frequency, interval }, endOfDayIn(e.target.value, zone), days)}
+ />
+ )}
+ </div>
+ </div>
+ )}
+ </>
+ );
+}
+
+/** The phone's Time Zone row, and Urgent where it is on. */
+function ZoneAndUrgent({ reminder, more }: { reminder: Reminder; more: ReminderMore }) {
+ const zone = more.timeZone;
+ const timed = reminder.dueAt !== null && !reminder.allDay;
+ const named = zone && timed ? zoneName(zone, reminder.dueAt!) : null;
+ if (!named && !more.urgent) return null;
+ return (
+ <>
+ {named && (
+ <div className="rx-field">
+ <span>Time Zone</span>
+ <span className="rx-value">
+ {named.city}
+ <span className="rx-quiet">{named.offset}</span>
+ </span>
+ </div>
+ )}
+ {more.urgent && (
+ <>
+ <div className="rx-field">
+ <span>Urgent</span>
+ <span className="rx-value">On</span>
+ </div>
+ <p className="rx-hint">Set on your iPhone. It rings as an alarm, even in a Focus or on silent.</p>
+ </>
+ )}
+ </>
+ );
+}
+
+/** Places & People: where it rings, and who it comes up for when messaging. */
+function PlacesAndPeople({ more }: { more: ReminderMore }) {
+ const { location, messaging } = more;
+ if (!location && !messaging) return null;
+ const side = location?.proximity === "arriving" ? "Arriving" : location?.proximity === "leaving" ? "Leaving" : null;
+ return (
+ <>
+ <div className="rx-detail-rule" aria-hidden="true" />
+ {location && (
+ <div className="rx-field">
+ <span>Location</span>
+ <span className="rx-value">
+ {location.title ?? "A place"}
+ {side && <span className="rx-quiet">{side}</span>}
+ </span>
+ </div>
+ )}
+ {messaging && (
+ <div className="rx-field">
+ <span>When Messaging</span>
+ <span className="rx-value">{messaging.name ?? messaging.handles[0]}</span>
+ </div>
+ )}
+ <p className="rx-hint">Set on your iPhone, and kept just as it is when you edit here.</p>
+ </>
+ );
+}
diff --git a/src/screens/SettingsView.tsx b/src/screens/SettingsView.tsx
index d9d0165..92e808b 100644
--- a/src/screens/SettingsView.tsx
+++ b/src/screens/SettingsView.tsx
@@ -1,7 +1,8 @@
+import { MOVE_CHECKED_KEY } from "./notes/model";
import { ConfirmSheet } from "../components/Confirm";
import { toast, toastSaved, useErrorToast } from "../components/Toast";
import { Progress } from "../components/Spinner";
-import { useEffect, useState, useSyncExternalStore } from "react";
+import { useEffect, useRef, useState, useSyncExternalStore } from "react";
import { getVersion } from "@tauri-apps/api/app";
import { listen } from "@tauri-apps/api/event";
import { pickOpen } from "../lib/pick";
@@ -17,12 +18,17 @@ import {
type LocalStorage,
type LoginItem,
messageOf,
+ PHOTO_CACHE,
+ photoCacheApi,
+ type PhotoCache,
settingsApi,
} from "../lib/ipc";
import { freshness, useSync } from "../lib/sync";
import { setTheme, storedTheme, type Theme } from "../lib/theme";
import { AppIcon } from "../components/AppIcon";
import { AccountAvatar } from "../components/Account";
+import { Picker } from "../components/Picker";
+import { localeFirstDay, setWeekStart, weekStartChoice, type WeekStartChoice } from "./calendar/model";
/** The app each service's freshness belongs to, for its icon. */
const ICON: Record<string, string> = {
@@ -322,6 +328,146 @@ function ExportRow({ onError }: { onError: (m: string) => void }) {
);
}
+/** A cap as Settings says it: "512 MB", "2 GB". */
+const capWords = (bytes: number) => (bytes < 1024 ** 3 ? `${Math.round(bytes / 1024 ** 2)} MB` : `${Math.round(bytes / 1024 ** 3)} GB`);
+
+/**
+ * Photos' originals and previews on this computer, as a Mac's Optimize Storage keeps them: what
+ * they take against the cap, the cap as a ruler of sizes, and Clear Cache. The cap moves at once
+ * and is sent when the hand stops; a lower one lets the longest unseen go in the background, and
+ * the figure follows when that is done (PHOTO_CACHE).
+ */
+function PhotoCacheGroup({ onError }: { onError: (m: string) => void }) {
+ const [cache, setCache] = useState<PhotoCache | null>(null);
+ /** The step the ruler shows while it is being moved, before the backend has it. */
+ const [moving, setMoving] = useState<number | null>(null);
+ const [clearing, setClearing] = useState(false);
+ const [freed, setFreed] = useState<number | null>(null);
+ const send = useRef<number | undefined>(undefined);
+ useEffect(() => {
+ photoCacheApi.status().then(setCache, () => {});
+ const stop = listen<PhotoCache>(PHOTO_CACHE, (e) => setCache(e.payload));
+ return () => {
+ window.clearTimeout(send.current);
+ void stop.then((un) => un()).catch(() => {});
+ };
+ }, []);
+ if (!cache) return null;
+ const steps = cache.steps;
+ const at = moving ?? Math.max(0, steps.indexOf(cache.cap));
+ const cap = steps[at] ?? cache.cap;
+ const choose = (i: number) => {
+ setMoving(i);
+ setFreed(null);
+ window.clearTimeout(send.current);
+ send.current = window.setTimeout(() => {
+ photoCacheApi.set(steps[i]).then(
+ (now) => {
+ setCache(now);
+ setMoving(null);
+ },
+ (e) => {
+ setMoving(null);
+ onError(messageOf(e));
+ },
+ );
+ }, 350);
+ };
+ const clear = () => {
+ const before = cache.used;
+ setClearing(true);
+ photoCacheApi
+ .clear()
+ .then(
+ (now) => {
+ setCache(now);
+ setFreed(Math.max(0, before - now.used));
+ },
+ (e) => onError(messageOf(e)),
+ )
+ .finally(() => setClearing(false));
+ };
+ const share = cap > 0 ? Math.min(1, cache.used / cap) : 0;
+ const limited = moving === null && cache.limit < cache.cap;
+ return (
+ <>
+ <h2 className="settings-heading settings-heading-line">
+ <span>Photos Cache</span>
+ <span className="settings-heading-value">
+ {size(cache.used)} of {capWords(cap)}
+ </span>
+ </h2>
+ <section className="settings-group" aria-label="Photos Cache">
+ <div className="settings-row is-stacked">
+ <div
+ className="storage-bar"
+ role="meter"
+ aria-label="Photos cache used"
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={Math.round(share * 100)}
+ aria-valuetext={`${size(cache.used)} of ${capWords(cap)}`}
+ >
+ <span style={{ width: `${share * 100}%` }} />
+ </div>
+ <span className="settings-hint settings-hint-wrap">
+ {limited
+ ? `Using up to ${size(cache.limit)} for now, to leave room on this disk. `
+ : "Recently viewed photos stay ready, even offline. "}
+ Thumbnails always stay.
+ </span>
+ </div>
+ <div className="settings-row is-stacked">
+ <div className="settings-row-line">
+ <label className="settings-label" htmlFor="photo-cache-cap">
+ Keep up to
+ </label>
+ <span className="settings-value">{capWords(cap)}</span>
+ </div>
+ <div className="cap-ruler" style={{ "--stops": steps.length } as React.CSSProperties}>
+ <input
+ id="photo-cache-cap"
+ type="range"
+ min={0}
+ max={steps.length - 1}
+ step={1}
+ value={at}
+ aria-valuetext={capWords(cap)}
+ onChange={(e) => choose(Number(e.currentTarget.value))}
+ />
+ <div className="cap-ruler-stops" aria-hidden="true">
+ {steps.map((s, i) => (
+ <button
+ key={s}
+ tabIndex={-1}
+ className={i === at ? "is-here" : undefined}
+ style={{ left: `${(i / (steps.length - 1)) * 100}%` }}
+ onClick={() => choose(i)}
+ >
+ {capWords(s)}
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+ <div className="settings-row">
+ <span className="settings-label settings-stack">
+ Clear Cache
+ <span className="settings-hint" aria-live="polite">
+ {freed !== null
+ ? `Cleared ${size(freed)}. Photos download again as you open them.`
+ : "Photos download again from iCloud as you open them."}
+ </span>
+ </span>
+ <button className="quiet" onClick={clear} disabled={clearing || cache.used < 1024 ** 2}>
+ {clearing ? "Clearing" : "Clear Cache"}
+ </button>
+ </div>
+ </section>
+ </>
+ );
+}
+
export function SettingsView({ onSignOut }: { onSignOut: (keep: boolean) => Promise<void> }) {
const [account, setAccount] = useState<AccountInfo | null>(null);
const [storage, setStorage] = useState<{ usedBytes: number; totalBytes: number } | null>(null);
@@ -563,6 +709,8 @@ export function SettingsView({ onSignOut }: { onSignOut: (keep: boolean) => Prom
<ExportRow onError={setError} />
</section>
+ <PhotoCacheGroup onError={setError} />
+
<h2 className="settings-heading">General</h2>
<section className="settings-group">
<div className="settings-row">
@@ -583,6 +731,8 @@ export function SettingsView({ onSignOut }: { onSignOut: (keep: boolean) => Prom
))}
</div>
</div>
+ <WeekStartRow />
+ <MoveCheckedRow />
<div className="settings-row">
<span className="settings-label settings-stack">
Open at Login
@@ -651,6 +801,8 @@ export function SettingsView({ onSignOut }: { onSignOut: (keep: boolean) => Prom
)}
</section>
+ <ReachGroup />
+
<h2 className="settings-heading">About</h2>
<section className="settings-group">
<div className="settings-row">
@@ -680,3 +832,113 @@ export function SettingsView({ onSignOut }: { onSignOut: (keep: boolean) => Prom
</div>
);
}
+
+/** Calendar's first day of the week: the locale's, or one chosen here, as Calendar on a Mac. */
+function WeekStartRow() {
+ const [choice, setChoice] = useState<WeekStartChoice>(weekStartChoice);
+ const day = (n: number) => new Intl.DateTimeFormat(undefined, { weekday: "long" }).format(new Date(2026, 0, 4 + n));
+ // The locale's own day, named in Automatic, so it is clear what Automatic gives.
+ const locale = localeFirstDay();
+ return (
+ <div className="settings-row">
+ <span className="settings-label">First Day of Week</span>
+ <Picker
+ label="First Day of Week"
+ value={choice}
+ onChange={(v) => {
+ const next = v as WeekStartChoice;
+ setChoice(next);
+ setWeekStart(next);
+ }}
+ options={[
+ { value: "auto", label: `Automatic (${day(locale)})` },
+ { value: "0", label: day(0) },
+ { value: "1", label: day(1) },
+ { value: "6", label: day(6) },
+ ]}
+ />
+ </div>
+ );
+}
+
+/**
+ * What Skykeep talks to, read from the network lock itself (`quince_auth::APPLE_DOMAINS`): a
+ * request to anywhere else fails before a connection exists. Subscribed calendars are listed
+ * by host, each reached by a client of its own.
+ */
+function ReachGroup() {
+ const [reach, setReach] = useState<{ apple: string[]; subscribed: string[] } | null>(null);
+ useEffect(() => {
+ api.networkReach().then(setReach, () => {});
+ }, []);
+ if (!reach) return null;
+ const apple = reach.apple.filter((d) => !d.endsWith(".cn"));
+ return (
+ <>
+ <h2 className="settings-heading">What Skykeep Talks To</h2>
+ <section className="settings-group settings-reach" aria-label="What Skykeep Talks To">
+ <div className="settings-row is-stacked">
+ <span className="settings-label">Apple</span>
+ <span className="settings-hint settings-hint-wrap">
+ {apple.map((d, i) => (
+ <span key={d}>
+ {i > 0 && ", "}
+ <code>{d}</code>
+ </span>
+ ))}{" "}
+ and their mainland China versions. Any other address is refused before a connection opens.
+ </span>
+ </div>
+ <div className="settings-row is-stacked">
+ <span className="settings-label">Calendar Subscriptions</span>
+ <span className="settings-hint settings-hint-wrap">
+ {reach.subscribed.length === 0
+ ? "None. A calendar you subscribe to adds its own address here."
+ : reach.subscribed.map((h, i) => (
+ <span key={h}>
+ {i > 0 && ", "}
+ <code>{h}</code>
+ </span>
+ ))}
+ </span>
+ </div>
+ </section>
+ </>
+ );
+}
+
+/** Notes' Move Checked Items to the Bottom: on this computer, as each iPhone keeps its own. */
+function MoveCheckedRow() {
+ const [on, setOn] = useState(() => {
+ try {
+ return localStorage.getItem(MOVE_CHECKED_KEY) === "1";
+ } catch {
+ return false;
+ }
+ });
+ return (
+ <div className="settings-row">
+ <span className="settings-label settings-stack">
+ Move Checked Items to the Bottom
+ <span className="settings-hint">In Notes checklists, ticked items sort below the rest</span>
+ </span>
+ <button
+ className="switch"
+ role="switch"
+ aria-checked={on}
+ aria-label="Move Checked Items to the Bottom"
+ onClick={() => {
+ const next = !on;
+ setOn(next);
+ try {
+ localStorage.setItem(MOVE_CHECKED_KEY, next ? "1" : "0");
+ } catch {
+ /* kept for this session only */
+ }
+ }}
+ >
+ <span className="switch-knob" />
+ </button>
+ </div>
+ );
+}
diff --git a/src/screens/SignIn.tsx b/src/screens/SignIn.tsx
index 0815ad7..f2f8866 100644
--- a/src/screens/SignIn.tsx
+++ b/src/screens/SignIn.tsx
@@ -160,6 +160,15 @@ export function SignIn({
Skykeep proves you know it without sending it, and keeps your session in your
system keyring. No Skykeep account, no Skykeep servers: it talks only to Apple, and to calendars you subscribe to.
</p>
+ <p>
+ <strong>Your full Apple Account password.</strong> An app-specific password opens
+ only mail, contacts and calendars to other apps. Notes, Reminders, Drive and Photos
+ open to a full sign-in with your two-factor code, the same one icloud.com uses.
+ </p>
+ <p>
+ <strong>Personal Apple Accounts.</strong> Accounts in mainland China and Managed
+ Apple Accounts from a school or workplace aren&rsquo;t supported yet.
+ </p>
<p>
<strong>Your iCloud, right here.</strong> Your calendar, reminders, notes, contacts
and Drive live on this computer in <code>{STORE}</code>, so everything opens
diff --git a/src/screens/calendar/CalendarView.tsx b/src/screens/calendar/CalendarView.tsx
index 799ffcb..813e327 100644
--- a/src/screens/calendar/CalendarView.tsx
+++ b/src/screens/calendar/CalendarView.tsx
@@ -7,10 +7,11 @@ import { usePending } from "../../lib/pending";
import { inMenu, Portal } from "../../components/Portal";
import { useReturnFocus } from "../../lib/focus";
import { TimeField } from "../../components/TimeField";
-import { ChevronDown, ChevronLeft, ChevronRight, Ellipsis, MapPin, Plus, Repeat } from "lucide-react";
+import { ChevronDown, ChevronLeft, ChevronRight, Ellipsis, MapPin, Plus, Repeat, Video } from "lucide-react";
import { createContext, Fragment, memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import {
type EventRepeat,
+ type Guest,
api,
defaultCalendar,
messageOf,
@@ -39,6 +40,7 @@ import {
midnight,
isWeekend,
monthDays,
+ onWeekChange,
placeDayWith,
sameClockIn,
sameDay,
@@ -50,6 +52,7 @@ import {
weekNumber,
weekSpans,
zoneName,
+ meetingOf,
} from "./model";
import { dateText, timeText } from "../../lib/when";
import { useReveal } from "../../lib/reveal";
@@ -165,6 +168,59 @@ const REFRESHES = [
/** A place, for the map app this computer opens `geo:` links with. */
const mapsHref = (place: string) => `geo:0,0?q=${encodeURIComponent(place.split("\n").join(", "))}`;
+/** An event's guests and their answers, as Calendar lists them: read from Apple when the event
+ * opens; nothing shown for an event with none, or before the answer comes. */
+function Guests({ guid }: { guid: string | null | undefined }) {
+ const [guests, setGuests] = useState<Guest[]>([]);
+ useEffect(() => {
+ setGuests([]);
+ if (!guid || guid.startsWith("quince:")) return;
+ let live = true;
+ api.eventGuests(guid).then((g) => live && setGuests(g), () => {});
+ return () => {
+ live = false;
+ };
+ }, [guid]);
+ if (guests.length === 0) return null;
+ const answer = { accepted: "Accepted", declined: "Declined", tentative: "Maybe", pending: "No reply" } as const;
+ const glyph = { accepted: "✓", declined: "✕", tentative: "?", pending: "" } as const;
+ return (
+ <section className="cx-guests" aria-label="Guests">
+ <h4 className="cx-guests-head">
+ {guests.length} {guests.length === 1 ? "Guest" : "Guests"}
+ </h4>
+ <ul className="cx-guest-list">
+ {guests.map((g, i) => {
+ const name = g.name ?? g.email ?? "Guest";
+ const role = g.isOrganizer ? "Organizer" : g.isMe ? "You" : null;
+ return (
+ <li key={`${g.email ?? g.name ?? ""}-${i}`} className="cx-guest" title={g.email ?? undefined}>
+ <span className={`cx-guest-mark is-${g.status}`} aria-hidden="true">{glyph[g.status]}</span>
+ <span className="cx-guest-name">
+ {name}
+ {role && <span className="cx-guest-role"> · {role}</span>}
+ </span>
+ <span className="cx-guest-answer">{answer[g.status]}</span>
+ </li>
+ );
+ })}
+ </ul>
+ </section>
+ );
+}
+
+/** Join, for an event with a video call: the call's own link, opened in its app or browser. */
+function JoinButton({ event }: { event: { url?: string | null; location?: string | null; notes?: string | null } }) {
+ const meeting = useMemo(() => meetingOf(event), [event.url, event.location, event.notes]);
+ if (!meeting) return null;
+ return (
+ <a className="cx-join" href={meeting.href} target="_blank" rel="noreferrer" title={meeting.href}>
+ <Video size={14} strokeWidth={2} aria-hidden="true" />
+ Join {meeting.service}
+ </a>
+ );
+}
+
const readSet = (key: string) => {
try {
return new Set<string>(JSON.parse(window.localStorage.getItem(key) ?? "[]"));
@@ -437,11 +493,15 @@ export function CalendarView() {
};
}, []);
+ // The first day of the week, changed in Settings or read late from the system's LC_TIME:
+ // every view is drawn again from it.
+ const [weekStart, setWeekStartTick] = useState(0);
+ useEffect(() => onWeekChange(() => setWeekStartTick((n) => n + 1)), []);
const week = useMemo(() => {
const start = startOfWeek(selected);
return Array.from({ length: 7 }, (_, i) => addDays(start, i));
- }, [selected]);
- const month = useMemo(() => monthDays(selected), [selected]);
+ }, [selected, weekStart]);
+ const month = useMemo(() => monthDays(selected), [selected, weekStart]);
// What each view reads from the library. Day and Week read the month around them and a
// month either side: asked for one day at a time, stepping to the next day showed the last
@@ -1885,6 +1945,7 @@ const MonthView = memo(function MonthView({
// A cell too narrow for any title shows its day's items as dots, as Calendar does on a
// small screen; a title cut to two letters and "3 more" squeezed below it said nothing.
const [dots, setDots] = useState(false);
+ const [tiny, setTiny] = useState(false);
useLayoutEffect(() => {
const el = grid.current;
if (!el) return undefined;
@@ -1897,7 +1958,13 @@ const MonthView = memo(function MonthView({
const width = (week?.firstElementChild as HTMLElement | null)?.getBoundingClientRect().width ?? 0;
// Lines 24px apart (calendar.css: each a 24px target, WCAG 2.2).
setRows(Math.max(1, Math.floor((height - 28) / LINE)));
- setDots(width > 0 && width < DOT_CELL);
+ // Dots too in a cell too short for one whole line under its date: one line was kept
+ // regardless, and its event drawn cut in half.
+ const short = height > 0 && height - 28 < LINE;
+ setDots((width > 0 && width < DOT_CELL) || short);
+ // Too short even for a row of 24px dots: small marks to see, the day itself the thing
+ // to press (it opens with its events), so no control is ever drawn half out of its cell.
+ setTiny(short);
};
measure();
const observer = new ResizeObserver(measure);
@@ -1965,7 +2032,7 @@ const MonthView = memo(function MonthView({
? dateText(day, { month: "short", day: "numeric" })
: day.getDate()}
</span>
- <ul className={`cx-items${dots ? " is-dots" : ""}`} style={{ marginTop: `${lanesHere * LANE}px` }}>
+ <ul className={`cx-items${dots ? " is-dots" : ""}${tiny ? " is-tiny" : ""}`} {...(tiny ? { inert: "" } : {})} style={{ marginTop: `${lanesHere * LANE}px` }}>
{visible.map((item) =>
item.kind === "event" ? (
<li key={item.event.guid}>
@@ -2875,6 +2942,7 @@ function EventPopover({
onSubmit={(e) => { e.preventDefault(); onClose(); }}
>
<h3 className="cx-info-title">{draft.title}</h3>
+ <JoinButton event={draft} />
{draft.location && (
<p className="cx-info-line cx-info-place">
{draft.location}
@@ -2886,6 +2954,7 @@ function EventPopover({
{draft.url && (
<a className="cx-info-url" href={draft.url} target="_blank" rel="noreferrer">{draft.url}</a>
)}
+ <Guests guid={draft.guid} />
{draft.notes && <p className="cx-info-notes">{draft.notes}</p>}
</form>
</Portal>
@@ -2914,6 +2983,7 @@ function EventPopover({
readOnly={!editable}
onChange={(e) => set({ title: e.target.value })}
/>
+ <JoinButton event={draft} />
<span className="cx-pop-place">
<input
className="cx-pop-line"
@@ -3061,6 +3131,7 @@ function EventPopover({
<a className="cx-pop-link is-text" href={draft.url.trim()} target="_blank" rel="noreferrer">Open</a>
)}
</span>
+ <Guests guid={draft.guid} />
<textarea
className="cx-pop-notes"
value={draft.notes}
diff --git a/src/screens/calendar/model.ts b/src/screens/calendar/model.ts
index 9b1a638..5464b7e 100644
--- a/src/screens/calendar/model.ts
+++ b/src/screens/calendar/model.ts
@@ -51,10 +51,72 @@ export function weekInfoOf(locale: string): WeekInfo {
}
}
-/** This computer's week, read once. */
-export const WEEK: WeekInfo = weekInfoOf(
- (typeof navigator !== "undefined" && navigator.language) || Intl.DateTimeFormat().resolvedOptions().locale
-);
+/** The first day chosen in Settings: "auto" for the locale's, else a day (`getDay`'s number). */
+export type WeekStartChoice = "auto" | "0" | "1" | "6";
+const WEEK_KEY = "quince.weekStart";
+export function weekStartChoice(): WeekStartChoice {
+ try {
+ const v = window.localStorage.getItem(WEEK_KEY);
+ return v === "0" || v === "1" || v === "6" ? v : "auto";
+ } catch {
+ return "auto";
+ }
+}
+
+/** The locale dates are written in: the engine's language until the system's LC_TIME is read. */
+let timeLocale =
+ (typeof navigator !== "undefined" && navigator.language) || Intl.DateTimeFormat().resolvedOptions().locale;
+
+/** The locale's own first day, whatever Settings chose. */
+export const localeFirstDay = () => weekInfoOf(timeLocale).firstDay;
+
+function weekNow(): WeekInfo {
+ const info = weekInfoOf(timeLocale);
+ const choice = typeof window === "undefined" ? "auto" : weekStartChoice();
+ return choice === "auto" ? info : { ...info, firstDay: Number(choice) };
+}
+
+/**
+ * This computer's week: its locale's (LC_TIME before LANG, read from the system), or the first
+ * day chosen in Settings. One object, kept current in place, so every default that reads it
+ * reads the latest; a change is told as `quince:week` for the views to draw again.
+ */
+export const WEEK: WeekInfo = weekNow();
+const WEEK_CHANGED = "quince:week";
+function refreshWeek() {
+ const next = weekNow();
+ if (next.firstDay === WEEK.firstDay && next.weekend.join() === WEEK.weekend.join()) return;
+ Object.assign(WEEK, next);
+ if (typeof window !== "undefined") window.dispatchEvent(new Event(WEEK_CHANGED));
+}
+export function setWeekStart(choice: WeekStartChoice) {
+ try {
+ if (choice === "auto") window.localStorage.removeItem(WEEK_KEY);
+ else window.localStorage.setItem(WEEK_KEY, choice);
+ } catch {
+ // Applies for now; the locale's on the next launch.
+ }
+ refreshWeek();
+}
+/** Calls `run` whenever the week changes; answers the way to stop. */
+export function onWeekChange(run: () => void): () => void {
+ window.addEventListener(WEEK_CHANGED, run);
+ return () => window.removeEventListener(WEEK_CHANGED, run);
+}
+if (typeof window !== "undefined" && "__TAURI_INTERNALS__" in window) {
+ void import("@tauri-apps/api/core")
+ .then(({ invoke }) => invoke<string | null>("system_time_locale"))
+ .then((tag) => {
+ if (!tag) return;
+ try {
+ new Intl.Locale(tag);
+ } catch {
+ return;
+ }
+ timeLocale = tag;
+ refreshWeek();
+ }, () => {});
+}
export const isWeekend = (d: Date) => WEEK.weekend.includes(d.getDay());
/** The day on or before `d` that a week starts on here — Sunday in the US, Monday in Europe. */
@@ -341,3 +403,41 @@ export function weekNumber(weekStart: Date, firstDay = WEEK.firstDay): number {
const firstWeek = startOfWeek(new Date(last.getFullYear(), 0, 1), firstDay);
return Math.round((start.getTime() - firstWeek.getTime()) / (7 * 864e5)) + 1;
}
+
+/** A video call an event holds a link to, and the service it is on. */
+export type Meeting = { href: string; service: string };
+
+// Each service by the shape of its join link, never by a word in the text: a link only counts
+// when its host and path are the service's own. Hosts are matched whole (a subdomain may lead,
+// as `company.zoom.us`), so `zoom.us.example.com` or `notzoom.us` are never taken for Zoom.
+const MEETINGS: { service: string; host: RegExp; path: RegExp }[] = [
+ { service: "Zoom", host: /^([a-z0-9-]+\.)*zoom\.(us|com)$/, path: /^\/(j|my|w|wc\/join)\/[\w.-]+/ },
+ { service: "Google Meet", host: /^meet\.google\.com$/, path: /^\/[a-z]{3}-[a-z]{4}-[a-z]{3}\b/ },
+ { service: "Microsoft Teams", host: /^teams\.(microsoft|live)\.com$/, path: /^\/(l\/meetup-join|meet)\// },
+ { service: "Webex", host: /^([a-z0-9-]+\.)*webex\.com$/, path: /^\/(meet|join|wbxmjs|[\w-]+\/j\.php)\b/ },
+ { service: "FaceTime", host: /^facetime\.apple\.com$/, path: /^\/join\b/ },
+];
+
+/**
+ * The video call to join from an event: the first service link in its URL field, then its
+ * location, then its notes — where calendars and invitations put them. Only `https:` links,
+ * trailing punctuation left off, nothing guessed: no link of a known service, no button.
+ */
+export function meetingOf(e: { url?: string | null; location?: string | null; notes?: string | null }): Meeting | null {
+ for (const text of [e.url, e.location, e.notes]) {
+ if (!text) continue;
+ for (const raw of text.match(/https:\/\/[^\s<>"'()]+/gi) ?? []) {
+ const link = raw.replace(/[.,;:!?)\]}>]+$/, "");
+ let url: URL;
+ try {
+ url = new URL(link);
+ } catch {
+ continue;
+ }
+ const host = url.hostname.toLowerCase();
+ const found = MEETINGS.find((m) => m.host.test(host) && m.path.test(url.pathname));
+ if (found) return { href: url.toString(), service: found.service };
+ }
+ }
+ return null;
+}
diff --git a/src/screens/contacts/DateField.tsx b/src/screens/contacts/DateField.tsx
new file mode 100644
index 0000000..5793aad
--- /dev/null
+++ b/src/screens/contacts/DateField.tsx
@@ -0,0 +1,112 @@
+import { useEffect, useMemo, useState } from "react";
+import { Picker } from "../../components/Picker";
+import { dateText } from "../../lib/when";
+
+/** The year Apple writes for a date given without one. */
+export const NO_YEAR = 1604;
+
+type Parts = { month: number | null; day: number | null; year: number | null };
+
+function parse(value: string | null): Parts {
+ const m = /^(\d{1,4})-(\d{2})-(\d{2})/.exec(value ?? "");
+ if (!m) return { month: null, day: null, year: null };
+ const year = Number(m[1]);
+ return { month: Number(m[2]), day: Number(m[3]), year: year === NO_YEAR ? null : year };
+}
+
+const pad = (n: number, w: number) => String(n).padStart(w, "0");
+
+/** As Apple writes it: `YYYY-MM-DD`, 1604 for no year, the day kept inside its month. */
+function written({ month, day, year }: Parts): string | null {
+ if (!month || !day) return null;
+ const last = new Date(Date.UTC(year ?? 2000, month, 0)).getUTCDate();
+ return `${pad(year ?? NO_YEAR, 4)}-${pad(month, 2)}-${pad(Math.min(day, last), 2)}`;
+}
+
+/** Month, day and year in the order this machine writes a date. */
+function order(): ("month" | "day" | "year")[] {
+ try {
+ const parts = new Intl.DateTimeFormat(undefined, { year: "numeric", month: "long", day: "numeric" })
+ .formatToParts(new Date(2000, 10, 22))
+ .map((p) => p.type)
+ .filter((t): t is "month" | "day" | "year" => t === "month" || t === "day" || t === "year");
+ return parts.length === 3 ? parts : ["month", "day", "year"];
+ } catch {
+ return ["month", "day", "year"];
+ }
+}
+
+/**
+ * A date as Contacts takes one — a birthday, an anniversary: a month, a day, and a year only
+ * if it is known. Three plain fields rather than the browser's date input, which WebKitGTK
+ * drew empty, and which cannot leave the year out.
+ */
+export function DateField({ value, onChange, label, autoFocus, compact }: {
+ value: string | null;
+ /** Months by their short names, for a date on one line of a card's details. */
+ compact?: boolean;
+ onChange: (value: string | null) => void;
+ /** What the date is, for each field's name: "Birthday" gives "Birthday, day". */
+ label: string;
+ autoFocus?: boolean;
+}) {
+ const [parts, setParts] = useState<Parts>(() => parse(value));
+ const [seen, setSeen] = useState(value);
+ // A value changed from outside (another date picked, the card re-read) is taken up.
+ useEffect(() => {
+ if (value !== seen) {
+ setSeen(value);
+ if (written(parts) !== value) setParts(parse(value));
+ }
+ }, [value, seen, parts]);
+ const months = useMemo(() => {
+ const f = new Intl.DateTimeFormat(undefined, { month: compact ? "short" : "long" });
+ return Array.from({ length: 12 }, (_, i) => ({ value: String(i + 1), label: f.format(new Date(2000, i, 1)) }));
+ }, [compact]);
+ const set = (next: Parts) => {
+ setParts(next);
+ const v = written(next);
+ setSeen(v);
+ onChange(v);
+ };
+ const number = (key: "day" | "year", max: number, width: number) => (
+ <input
+ key={key}
+ className={`date-field-${key}`}
+ inputMode="numeric"
+ autoComplete="off"
+ placeholder={key === "day" ? "Day" : "Year"}
+ aria-label={`${label}, ${key}`}
+ value={parts[key] ?? ""}
+ autoFocus={autoFocus && key === "day"}
+ onChange={(e) => {
+ const digits = e.target.value.replace(/\D/g, "").slice(0, width);
+ const n = digits ? Math.min(Number(digits), max) : null;
+ set({ ...parts, [key]: n && n > 0 ? n : null });
+ }}
+ />
+ );
+ const fields = {
+ month: (
+ <Picker
+ key="month"
+ className="date-field-month"
+ label={`${label}, month`}
+ value={parts.month ? String(parts.month) : ""}
+ onChange={(m) => set({ ...parts, month: m ? Number(m) : null })}
+ options={[{ value: "", label: "Month" }, ...months]}
+ />
+ ),
+ day: number("day", 31, 2),
+ year: number("year", 9999, 4),
+ };
+ return <span className="date-field">{order().map((k) => fields[k])}</span>;
+}
+
+/** "17 March", or "17 March 1998" when the year is known — as a card shows a date. */
+export function dateWords(raw: string): string {
+ const { month, day, year } = parse(raw);
+ if (!month || !day) return raw;
+ const date = new Date(year ?? 2000, month - 1, day);
+ return dateText(date, year ? { dateStyle: "long" } : { day: "numeric", month: "long" });
+}
diff --git a/src/screens/contacts/Duplicates.tsx b/src/screens/contacts/Duplicates.tsx
new file mode 100644
index 0000000..3cbd192
--- /dev/null
+++ b/src/screens/contacts/Duplicates.tsx
@@ -0,0 +1,116 @@
+import { ChevronRight, UsersRound } from "lucide-react";
+import { displayName, type Contact, type Duplicates } from "../../lib/ipc";
+
+/** What a group of cards shares, in a sentence. */
+function shared(reasons: string[]): string {
+ const words: Record<string, string> = { name: "name", phone: "phone number", email: "email address" };
+ const parts = reasons.map((r) => words[r]).filter(Boolean);
+ if (parts.length === 0) return "These cards look like one person.";
+ const list = parts.length === 1 ? parts[0] : `${parts.slice(0, -1).join(", ")} and ${parts[parts.length - 1]}`;
+ return `Same ${list}.`;
+}
+
+/** The person a group is, by the name most of its cards give. */
+function groupName(people: Contact[]): string {
+ const named = people.map(displayName);
+ return named.find((n) => /\p{L}/u.test(n)) ?? named[0] ?? "No Name";
+}
+
+/**
+ * At the top of the list when some cards look like one person, as the iPhone says it: a
+ * quiet line, never in the way, that opens the cards to look at.
+ */
+export function DuplicatesBanner({ count, onOpen }: { count: number; onOpen: () => void }) {
+ return (
+ <button type="button" className="dupes-banner" onClick={onOpen}>
+ <UsersRound size={18} strokeWidth={1.8} aria-hidden="true" />
+ <span className="dupes-banner-text">
+ <span className="dupes-banner-title">Duplicates Found</span>
+ <span className="dupes-banner-sub">
+ {count === 1 ? "1 person has more than one card" : `${count} people have more than one card`}
+ </span>
+ </span>
+ <ChevronRight size={16} strokeWidth={2} aria-hidden="true" className="dupes-banner-go" />
+ </button>
+ );
+}
+
+/**
+ * The cards that look like one person, group by group: who, what they share, and one press to
+ * make them one card. Nothing is lost in a merge — every number, address and date is kept —
+ * and it can be undone until iCloud has it.
+ */
+export function DuplicatesView({ groups, book, Face, onMerge, onMergeAll, onShow, busy }: {
+ groups: Duplicates[];
+ book: Map<string, Contact>;
+ Face: (props: { contact: Contact; large?: boolean }) => React.ReactNode;
+ onMerge: (group: Duplicates) => void;
+ onMergeAll: () => void;
+ onShow: (guid: string) => void;
+ busy: boolean;
+}) {
+ const shown = groups
+ .map((g) => ({ g, people: g.guids.map((id) => book.get(id)).filter((c): c is Contact => !!c) }))
+ .filter((x) => x.people.length > 1);
+ if (shown.length === 0) {
+ return (
+ <div className="dupes-done">
+ <UsersRound size={28} strokeWidth={1.5} aria-hidden="true" />
+ <p>Every person has one card.</p>
+ </div>
+ );
+ }
+ return (
+ <section className="dupes" aria-label="Duplicates">
+ <header className="dupes-head">
+ <h2>Duplicates</h2>
+ <p>
+ Merging keeps everything from every card in one: each number, email, address and date,
+ the notes, and the photo.
+ </p>
+ {shown.length > 1 && (
+ <button type="button" className="primary" disabled={busy} onClick={onMergeAll}>
+ Merge All
+ </button>
+ )}
+ </header>
+ <ul className="dupes-list">
+ {shown.map(({ g, people }) => (
+ <li key={g.guids.join("|")} className="dupes-group">
+ <div className="dupes-faces" aria-hidden="true">
+ {people.slice(0, 3).map((c) => <Face key={c.guid} contact={c} />)}
+ </div>
+ <div className="dupes-who">
+ <span className="dupes-name">{groupName(people)}</span>
+ <span className="dupes-why">
+ {people.length} cards. {shared(g.reasons)}
+ </span>
+ <span className="dupes-cards">
+ {people.map((c) => (
+ <button key={c.guid} type="button" className="link-button" onClick={() => onShow(c.guid)}>
+ {cardSummary(c)}
+ </button>
+ ))}
+ </span>
+ </div>
+ <button
+ type="button"
+ className="quiet dupes-merge"
+ disabled={busy}
+ aria-label={`Merge ${groupName(people)}`}
+ onClick={() => onMerge(g)}
+ >
+ Merge
+ </button>
+ </li>
+ ))}
+ </ul>
+ </section>
+ );
+}
+
+/** One card in a group, told apart from the others: its name and the first thing on it. */
+function cardSummary(c: Contact): string {
+ const first = c.methods.find((m) => m.kind === "phone" || m.kind === "email");
+ return first ? `${displayName(c)}, ${first.value}` : displayName(c);
+}
diff --git a/src/screens/contacts/PhotoSheet.tsx b/src/screens/contacts/PhotoSheet.tsx
new file mode 100644
index 0000000..b97526e
--- /dev/null
+++ b/src/screens/contacts/PhotoSheet.tsx
@@ -0,0 +1,233 @@
+import { useEffect, useRef, useState } from "react";
+import { ImagePlus } from "lucide-react";
+import { Portal } from "../../components/Portal";
+import { useModalFocus } from "../../lib/focus";
+
+/** The circle a face is chosen in, and the frame around it, in CSS pixels. */
+const FRAME = 240;
+const RADIUS = 108;
+/** The longest `data:` URL icloud.com sends for a picture: the image is made to fit under it. */
+const LIMIT = 229_376;
+
+export type ChosenPhoto = {
+ /** The whole picture, as a JPEG `data:` URL — what icloud.com sends. */
+ url: string;
+ /** The square, `x,y,width,height` in the sent picture's pixels, measured from its bottom left. */
+ crop: string;
+ /** The square alone, small, to show on the card until iCloud has the picture. */
+ preview: string;
+};
+
+type Loaded = { src: string; img: HTMLImageElement; w: number; h: number };
+/** Where the picture sits: its point under the circle's centre, and its scale. */
+type View = { cx: number; cy: number; scale: number };
+
+const minScale = (l: Loaded) => (2 * RADIUS) / Math.min(l.w, l.h);
+
+/** The view moved or zoomed, kept so the circle never shows past the picture's edge. */
+function within(l: Loaded, v: View): View {
+ const scale = Math.max(minScale(l), Math.min(v.scale, minScale(l) * 8));
+ const half = RADIUS / scale;
+ return {
+ scale,
+ cx: Math.min(Math.max(v.cx, half), l.w - half),
+ cy: Math.min(Math.max(v.cy, half), l.h - half),
+ };
+}
+
+/** The picture drawn to a canvas and made a JPEG under icloud.com's size: quality first, then size. */
+function encode(l: Loaded): { url: string; factor: number } | null {
+ const canvas = document.createElement("canvas");
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return null;
+ let factor = Math.min(1, 2048 / Math.max(l.w, l.h));
+ let quality = 0.9;
+ for (let i = 0; i < 24; i++) {
+ canvas.width = Math.max(1, Math.round(l.w * factor));
+ canvas.height = Math.max(1, Math.round(l.h * factor));
+ ctx.fillStyle = "#ffffff";
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+ ctx.drawImage(l.img, 0, 0, canvas.width, canvas.height);
+ const url = canvas.toDataURL("image/jpeg", quality);
+ if (url.length <= LIMIT) return { url, factor: canvas.width / l.w };
+ if (quality > 0.4) quality -= 0.15;
+ else factor *= 0.8;
+ }
+ return null;
+}
+
+/**
+ * Choosing a contact's picture, as Contacts does: a photo picked or dropped, then moved and
+ * zoomed until the face sits in the circle. Done sends the whole picture with the square
+ * chosen, as icloud.com does; Delete Photo takes the picture away.
+ */
+export function PhotoSheet({ hasPhoto, onDone, onRemove, onCancel }: {
+ hasPhoto: boolean;
+ onDone: (photo: ChosenPhoto) => void;
+ onRemove: () => void;
+ onCancel: () => void;
+}) {
+ const sheet = useRef<HTMLDivElement | null>(null);
+ useModalFocus(sheet);
+ const input = useRef<HTMLInputElement | null>(null);
+ const [loaded, setLoaded] = useState<Loaded | null>(null);
+ const [view, setView] = useState<View | null>(null);
+ const [problem, setProblem] = useState<string | null>(null);
+ const drag = useRef<{ x: number; y: number; from: View } | null>(null);
+
+ useEffect(() => () => {
+ if (loaded?.src.startsWith("blob:")) URL.revokeObjectURL(loaded.src);
+ }, [loaded]);
+
+ const open = (file: File | null | undefined) => {
+ if (!file) return;
+ if (!/^image\/(png|jpeg|gif|bmp|webp)$/.test(file.type)) {
+ setProblem("Choose a JPEG, PNG, GIF, BMP or WebP picture.");
+ return;
+ }
+ const src = URL.createObjectURL(file);
+ const img = new Image();
+ img.onload = () => {
+ const l = { src, img, w: img.naturalWidth, h: img.naturalHeight };
+ setProblem(null);
+ setLoaded(l);
+ setView(within(l, { cx: l.w / 2, cy: l.h / 2, scale: minScale(l) }));
+ };
+ img.onerror = () => setProblem("This picture can't be read. Choose another.");
+ img.src = src;
+ };
+
+ const zoomTo = (scale: number) => loaded && view && setView(within(loaded, { ...view, scale }));
+ const done = () => {
+ if (!loaded || !view) return;
+ const encoded = encode(loaded);
+ if (!encoded) {
+ setProblem("This picture is too large to use. Choose a smaller one.");
+ return;
+ }
+ const side = (2 * RADIUS) / view.scale;
+ const top = view.cy - side / 2;
+ const f = encoded.factor;
+ const x = Math.round((view.cx - side / 2) * f);
+ // Apple measures the square from the picture's bottom edge, as the Mac does.
+ const y = Math.round((loaded.h - top - side) * f);
+ const s = Math.max(1, Math.round(side * f));
+ const small = document.createElement("canvas");
+ small.width = small.height = 160;
+ small.getContext("2d")?.drawImage(loaded.img, view.cx - side / 2, top, side, side, 0, 0, 160, 160);
+ onDone({
+ url: encoded.url,
+ crop: `${Math.max(0, x)},${Math.max(0, y)},${s},${s}`,
+ preview: small.toDataURL("image/jpeg", 0.85),
+ });
+ };
+
+ const min = loaded ? minScale(loaded) : 1;
+ return (
+ <Portal>
+ <div className="modal-veil" onClick={onCancel}>
+ <div
+ ref={sheet}
+ className="modal-sheet photo-sheet"
+ role="dialog"
+ aria-modal="true"
+ aria-label="Contact photo"
+ onClick={(e) => e.stopPropagation()}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ e.stopPropagation();
+ onCancel();
+ }
+ }}
+ onDragOver={(e) => e.preventDefault()}
+ onDrop={(e) => {
+ e.preventDefault();
+ open(e.dataTransfer.files?.[0]);
+ }}
+ >
+ <h2>Contact Photo</h2>
+ <div
+ className={`photo-frame${loaded ? " has-photo" : ""}`}
+ style={{ width: FRAME, height: FRAME }}
+ onPointerDown={(e) => {
+ if (!view) return;
+ e.currentTarget.setPointerCapture(e.pointerId);
+ drag.current = { x: e.clientX, y: e.clientY, from: view };
+ }}
+ onPointerMove={(e) => {
+ const d = drag.current;
+ if (!d || !loaded) return;
+ setView(within(loaded, {
+ ...d.from,
+ cx: d.from.cx - (e.clientX - d.x) / d.from.scale,
+ cy: d.from.cy - (e.clientY - d.y) / d.from.scale,
+ }));
+ }}
+ onPointerUp={() => (drag.current = null)}
+ onPointerCancel={() => (drag.current = null)}
+ onWheel={(e) => view && zoomTo(view.scale * (e.deltaY < 0 ? 1.08 : 1 / 1.08))}
+ >
+ {loaded && view ? (
+ <>
+ <img
+ className="photo-frame-image"
+ src={loaded.src}
+ alt=""
+ draggable={false}
+ style={{
+ width: loaded.w * view.scale,
+ height: loaded.h * view.scale,
+ transform: `translate(${FRAME / 2 - view.cx * view.scale}px, ${FRAME / 2 - view.cy * view.scale}px)`,
+ }}
+ />
+ <span className="photo-frame-ring" style={{ width: RADIUS * 2, height: RADIUS * 2 }} aria-hidden="true" />
+ </>
+ ) : (
+ <button type="button" className="photo-frame-pick" onClick={() => input.current?.click()}>
+ <ImagePlus size={30} strokeWidth={1.5} aria-hidden="true" />
+ <span>Choose a photo, or drop one here</span>
+ </button>
+ )}
+ </div>
+ {loaded && view && (
+ <label className="photo-zoom">
+ <span>Zoom</span>
+ <input
+ type="range"
+ min={0}
+ max={100}
+ step={1}
+ aria-label="Zoom"
+ value={Math.round((Math.log(view.scale / min) / Math.log(8)) * 100)}
+ onChange={(e) => zoomTo(min * 8 ** (Number(e.target.value) / 100))}
+ />
+ </label>
+ )}
+ {problem && <p className="photo-problem" role="alert">{problem}</p>}
+ <input
+ ref={input}
+ type="file"
+ accept="image/png,image/jpeg,image/gif,image/bmp,image/webp"
+ hidden
+ aria-label="Photo file"
+ onChange={(e) => {
+ open(e.target.files?.[0]);
+ e.target.value = "";
+ }}
+ />
+ <div className="photo-sheet-actions">
+ {hasPhoto && !loaded && (
+ <button type="button" className="quiet danger" onClick={onRemove}>Delete Photo</button>
+ )}
+ {loaded && (
+ <button type="button" className="quiet" onClick={() => input.current?.click()}>Choose Another</button>
+ )}
+ <span className="photo-sheet-gap" />
+ <button type="button" className="quiet" onClick={onCancel}>Cancel</button>
+ <button type="button" className="primary" disabled={!loaded} onClick={done}>Done</button>
+ </div>
+ </div>
+ </div>
+ </Portal>
+ );
+}
diff --git a/src/screens/notes/NoteEditor.tsx b/src/screens/notes/NoteEditor.tsx
index ac5afd8..de2e7b0 100644
--- a/src/screens/notes/NoteEditor.tsx
+++ b/src/screens/notes/NoteEditor.tsx
@@ -7,7 +7,16 @@ import { keymap } from "prosemirror-keymap";
import { baseKeymap, splitBlockAs, toggleMark, chainCommands } from "prosemirror-commands";
import { Fragment, Slice, type Node as PMNode } from "prosemirror-model";
import type { Run } from "./Formatted";
-import { fromDoc, LIST_STYLES, schema, STYLE, tableCells, toDoc } from "./rich";
+import { checklistMove, fromDoc, LIST_STYLES, schema, STYLE, tableCells, toDoc } from "./rich";
+import { MOVE_CHECKED_KEY } from "./model";
+
+function moveCheckedOn(): boolean {
+ try {
+ return localStorage.getItem(MOVE_CHECKED_KEY) === "1";
+ } catch {
+ return false;
+ }
+}
import { api, messageOf, noteMediaSrc, type NoteAttachment } from "../../lib/ipc";
import { RowMenu, type MenuEntry } from "../../components/RowMenu";
import { autolink, openLinkAt } from "./links";
@@ -26,6 +35,16 @@ function withoutAttachments(content: Fragment): Fragment {
return Fragment.fromArray(kept);
}
+/** Whether a piece of the note holds an attachment — a picture, a file, a table. */
+function sliceHasAttachment(slice: Slice): boolean {
+ let found = false;
+ slice.content.descendants((node) => {
+ if (node.type === schema.nodes.attachment) found = true;
+ return !found;
+ });
+ return found;
+}
+
/** Every table on screen, by its element: how to read it again. */
const liveTables = new Map<HTMLElement, () => void>();
@@ -34,9 +53,10 @@ export function refreshTables() {
liveTables.forEach((read) => read());
}
-/** Whether tables can be edited here. Off: edits made here showed on an iPhone, but Notes there
- * kept conflict copies of the note with the edited text doubled — they did not merge cleanly. */
-const TABLE_CELL_WRITES = false;
+/** Whether tables can be edited here. Mirrors `TABLE_CELL_WRITES` / `TABLE_LINE_WRITES` in
+ * src-tauri/src/main.rs. Cells are on: a cell written here showed once on his iPhone with no
+ * conflict copy (2026-10-22). Rows and columns stay off until one is watched on a phone. */
+const TABLE_CELL_WRITES = true;
const TABLE_LINE_WRITES = false;
/** A table's right-click menu: drawn by the editor that holds the table, opened by a cell. */
@@ -90,12 +110,38 @@ export function drawMedia(dom: HTMLElement, info: NoteAttachment) {
// Opened in the app this computer uses for it; one that cannot be says why, on the chip
// itself, rather than a click that seems to do nothing.
let said: HTMLElement | null = null;
- const open = () =>
- void api.noteAttachmentOpen(info.id).catch((e) => {
- if (!said) return;
- said.textContent = `Couldn’t open: ${messageOf(e)}`;
- said.classList.add("is-trouble");
- });
+ // Answered on the click itself: the attachment dims and its line says it is opening, until
+ // the app this computer uses for it has it — a file not yet on this computer is fetched
+ // first, and a click that showed nothing meanwhile read as one that did nothing.
+ let opening = false;
+ const open = () => {
+ if (opening) return;
+ opening = true;
+ dom.classList.add("is-opening");
+ dom.setAttribute("aria-busy", "true");
+ const before = said?.textContent ?? null;
+ if (said) {
+ said.textContent = "Opening";
+ said.classList.remove("is-trouble");
+ }
+ void api
+ .noteAttachmentOpen(info.id)
+ .then(
+ () => {
+ if (said) said.textContent = before;
+ },
+ (e) => {
+ if (!said) return;
+ said.textContent = `Couldn’t open: ${messageOf(e)}`;
+ said.classList.add("is-trouble");
+ },
+ )
+ .finally(() => {
+ opening = false;
+ dom.classList.remove("is-opening");
+ dom.removeAttribute("aria-busy");
+ });
+ };
const chip = () => {
const c = document.createElement("button");
c.type = "button";
@@ -123,7 +169,14 @@ export function drawMedia(dom: HTMLElement, info: NoteAttachment) {
img.alt = name;
img.decoding = "async";
img.draggable = false;
- if (info.width && info.height) img.style.aspectRatio = `${info.width} / ${info.height}`;
+ // Its own size known before a byte of it arrives, so it holds its place at its proportions
+ // (drawn no wider than the note) instead of a gap that jumps when it lands.
+ if (info.width && info.height) {
+ img.width = Math.round(info.width);
+ img.height = Math.round(info.height);
+ img.style.aspectRatio = `${info.width} / ${info.height}`;
+ }
+ img.loading = "lazy";
img.src = noteMediaSrc(info.id, part);
// The backend says whether the picture can be shown: a 404 (a HEIC with no decoder on
// this computer, a fetch that failed) and it is the file's chip, drawn as one.
@@ -193,6 +246,8 @@ function attachmentView(node: PMNode) {
dom.classList.add("is-pending");
dom.title = "Open it on an Apple device to change it";
const id = node.attrs.id as string | null;
+ // With no id (the note's formatting not read yet) there is nothing to look up: no frame.
+ if (!id) dom.classList.replace("is-pending", "is-anon");
const draw = (cells: string[][]) => {
if (id) tableCells.set(id, cells.map((row) => [...row]));
@@ -287,17 +342,56 @@ function attachmentView(node: PMNode) {
dom.replaceChildren(table);
};
+ /**
+ * What the attachment is, drawn once known. A lookup that fails (offline, the session being
+ * renewed, Apple slow) is asked again a little later, and again after every sync — never left
+ * a blank gap. Until then a quiet frame holds its place; after the last try it is a card
+ * that still opens it.
+ */
+ let tries = 0;
+ let retry: number | null = null;
+ let gone = false;
+ const showMedia = (mediaId: string) => {
+ if (retry !== null) window.clearTimeout(retry);
+ retry = null;
+ void describe(mediaId).then((info) => {
+ if (gone) return;
+ if (info) {
+ dom.classList.remove("is-pending", "is-unknown");
+ drawMedia(dom, info);
+ return;
+ }
+ tries += 1;
+ if (tries < 4) retry = window.setTimeout(() => showMedia(mediaId), 1500 * 2 ** tries);
+ else if (dom.classList.contains("is-pending")) {
+ drawMedia(dom, { id: mediaId, uti: "", kind: "file", filename: null, title: null, width: null, height: null, size: null, hasPreview: false });
+ dom.classList.add("is-unknown");
+ }
+ });
+ };
+
if (id) {
- api.noteTable(id).then(
- (cells) => {
- if (cells && cells.length) draw(cells);
- else describe(id).then((info) => info && drawMedia(dom, info), () => {});
- },
- () => {},
- );
+ // What it is, first — kept on disk once known — so a picture or a file is drawn at once.
+ // Asking for table cells first went to Apple for every picture on every open (a picture
+ // has no cells to keep, so the answer was never kept), and each one waited for it.
+ void describe(id).then((info) => {
+ if (info && info.kind !== "table") return showMedia(id);
+ api.noteTable(id).then(
+ (cells) => {
+ if (cells && cells.length) draw(cells);
+ else showMedia(id);
+ },
+ () => showMedia(id),
+ );
+ });
// Read again after every sync, so a table typed in on a phone shows its new cells here
// without leaving the note; drawn again only when they changed.
liveTables.set(dom, () => {
+ // An attachment not yet known is asked about again now that Apple has been reached.
+ if (dom.classList.contains("is-pending") || dom.classList.contains("is-unknown")) {
+ tries = Math.min(tries, 3);
+ return showMedia(id);
+ }
if (!dom.classList.contains("is-table") && !dom.classList.contains("is-table-unread")) return;
api.noteTable(id).then(
(cells) => {
@@ -309,7 +403,11 @@ function attachmentView(node: PMNode) {
}
return {
dom,
- destroy: () => void liveTables.delete(dom),
+ destroy: () => {
+ gone = true;
+ liveTables.delete(dom);
+ if (retry !== null) window.clearTimeout(retry);
+ },
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")),
@@ -647,9 +745,13 @@ export const NoteEditor = forwardRef<EditorHandle, Props>(function NoteEditor(
...(placeholder ? { "data-placeholder": placeholder } : {}),
},
dispatchTransaction(tr: Transaction) {
- const next = v.state.apply(tr);
+ const before = v.state;
+ const next = before.apply(tr);
v.updateState(next);
- if (tr.docChanged) reportSoon();
+ // Only a change to what the note holds is an edit. A step that leaves the document as
+ // it was — text dragged and dropped where it lay, a mark set where it already is —
+ // is not, and must never become a save.
+ if (tr.docChanged && !next.doc.eq(before.doc)) reportSoon();
callbacks.current.onStatus?.(statusOf(next));
},
// A paste never brings an attachment's reference: Apple keeps each table or picture in
@@ -700,7 +802,23 @@ export const NoteEditor = forwardRef<EditorHandle, Props>(function NoteEditor(
view.dispatch(tr.scrollIntoView());
return true;
},
+ // Dragging within the note moves text, as Notes does. Never an attachment: a picture or
+ // table dragged was dropped as its cells' text, the table itself gone from the note (and a
+ // drag let go where it began still wrote the note back). A drop where the dragged text
+ // already lies changes nothing and is not made.
+ handleDrop(view, event, slice, moved) {
+ if (sliceHasAttachment(slice)) return true;
+ if (!moved) return false;
+ const at = view.posAtCoords({ left: event.clientX, top: event.clientY })?.pos;
+ const { from, to } = view.state.selection;
+ return at === undefined || (at >= from && at <= to);
+ },
handleDOMEvents: {
+ dragstart: (vw, event) => {
+ if (!sliceHasAttachment(vw.state.selection.content())) return false;
+ event.preventDefault();
+ return true;
+ },
click: (_vw, event) => openLinkAt(event),
blur: () => {
if (later.current !== null) report();
@@ -720,7 +838,28 @@ export const NoteEditor = forwardRef<EditorHandle, Props>(function NoteEditor(
const node = vw.state.doc.nodeAt(pos);
if (!node) return false;
event.preventDefault();
- vw.dispatch(vw.state.tr.setNodeMarkup(pos, undefined, { ...node.attrs, checked: !node.attrs.checked }));
+ const checked = !node.attrs.checked;
+ const tr = vw.state.tr.setNodeMarkup(pos, undefined, { ...node.attrs, checked });
+ // With "Move Checked Items to the Bottom" on, the item goes where Notes sorts it, in
+ // the same edit, so one undo puts both back.
+ if (moveCheckedOn()) {
+ const starts: number[] = [];
+ vw.state.doc.forEach((_, offset) => starts.push(offset));
+ const move = checklistMove(vw.state.doc, starts.indexOf(pos), checked);
+ if (move) {
+ const at = (i: number) => (i < starts.length ? starts[i] : vw.state.doc.content.size);
+ const slice = tr.doc.slice(at(move.from), at(move.to));
+ const target = tr.mapping.map(at(move.before));
+ if (move.before > move.from) {
+ tr.insert(target, slice.content);
+ tr.delete(at(move.from), at(move.to));
+ } else {
+ tr.delete(at(move.from), at(move.to));
+ tr.insert(target, slice.content);
+ }
+ }
+ }
+ vw.dispatch(tr);
return true;
},
},
@@ -790,6 +929,13 @@ export const NoteEditor = forwardRef<EditorHandle, Props>(function NoteEditor(
replace: (nextText, nextRuns) => {
const v = view.current;
if (!v) return;
+ // A key typed this very moment is not yet reported: send it first, and keep what is on
+ // screen — the parent sees it pending and does not lay Apple's copy over it. Replacing
+ // now lost that key, and the report that followed sent the replaced note.
+ if (later.current !== null) {
+ report();
+ return;
+ }
const doc = toDoc(nextText, nextRuns);
if (doc.eq(v.state.doc)) return;
const { from, to } = v.state.selection;
diff --git a/src/screens/notes/NotePicture.tsx b/src/screens/notes/NotePicture.tsx
index 821d22a..2a5ebd0 100644
--- a/src/screens/notes/NotePicture.tsx
+++ b/src/screens/notes/NotePicture.tsx
@@ -14,9 +14,12 @@ import { PICTURE_EVENT, type PictureShown } from "./NoteEditor";
export function NotePicture() {
const [shown, setShown] = useState<PictureShown | null>(null);
const [problem, setProblem] = useState<string | null>(null);
+ // Said on the button at once, until the other app has it.
+ const [opening, setOpening] = useState(false);
useEffect(() => {
const show = (e: Event) => {
setProblem(null);
+ setOpening(false);
setShown((e as CustomEvent<PictureShown>).detail);
};
window.addEventListener(PICTURE_EVENT, show);
@@ -60,9 +63,17 @@ export function NotePicture() {
{!shown.drawing && (
<button
className="quiet"
- onClick={() => void api.noteAttachmentOpen(shown.id).catch((e) => setProblem(messageOf(e)))}
+ disabled={opening}
+ aria-busy={opening}
+ onClick={() => {
+ setOpening(true);
+ void api
+ .noteAttachmentOpen(shown.id)
+ .catch((e) => setProblem(messageOf(e)))
+ .finally(() => setOpening(false));
+ }}
>
- Open in Default App
+ {opening ? "Opening" : "Open in Default App"}
</button>
)}
<button className="icon-button round nf-picture-close" aria-label="Close" autoFocus onClick={() => setShown(null)}>
diff --git a/src/screens/notes/model.ts b/src/screens/notes/model.ts
index 0efe2a7..d6175a0 100644
--- a/src/screens/notes/model.ts
+++ b/src/screens/notes/model.ts
@@ -11,29 +11,54 @@ const daysBetween = (from: Date, to: Date) =>
/** One run of the note list under a heading. */
export type Section = { key: string; heading: string; notes: Note[] };
+/** Settings ▸ Move Checked Items to the Bottom: off unless turned on, kept on this computer. */
+export const MOVE_CHECKED_KEY = "notes.moveChecked";
+
+/** How the list is ordered, as Notes' View menu offers it. */
+export type NoteSort = "edited" | "created" | "title";
+export type NoteOrder = { by: NoteSort; groupByDate: boolean };
+export const DEFAULT_ORDER: NoteOrder = { by: "edited", groupByDate: true };
+
+/** A note's title for sorting: its first line, as the list shows it. */
+const titleOf = (n: Note) => (n.title || "").trim();
+const byTitle = new Intl.Collator(undefined, { sensitivity: "base", numeric: true });
+
/**
- * The list the way Notes groups it: Pinned first, then Today, Yesterday, Previous 7 Days,
- * Previous 30 Days, then each earlier month of this year by name, then each earlier year.
- * Within a group, most recently changed first. A group with nothing in it is not shown.
+ * The list the way Notes groups it: Pinned first, then — sorted by a date and grouped — Today,
+ * Yesterday, Previous 7 Days, Previous 30 Days, each earlier month of this year by name, then
+ * each earlier year, by that date. Within a group, newest first; by title, A to Z with no date
+ * groups (as Notes does). A group with nothing in it is not shown. Notes with no date at all
+ * come last, under Earlier, whatever the order.
*/
-export function groupNotes(notes: Note[], now = new Date()): Section[] {
+export function groupNotes(notes: Note[], now = new Date(), order: NoteOrder = DEFAULT_ORDER): Section[] {
+ const dateOf = (n: Note) => (order.by === "created" ? n.createdAt : n.modifiedAt) ?? null;
+ const sorted = [...notes].sort((a, b) =>
+ order.by === "title"
+ ? byTitle.compare(titleOf(a), titleOf(b)) || (b.modifiedAt ?? 0) - (a.modifiedAt ?? 0)
+ : (dateOf(b) ?? -Infinity) - (dateOf(a) ?? -Infinity) || byTitle.compare(titleOf(a), titleOf(b)),
+ );
const out = new Map<string, Section>();
const add = (key: string, heading: string, note: Note) => {
const s = out.get(key) ?? { key, heading, notes: [] };
s.notes.push(note);
out.set(key, s);
};
- const sorted = [...notes].sort((a, b) => (b.modifiedAt ?? 0) - (a.modifiedAt ?? 0));
+ const dated = order.by !== "title" && order.groupByDate;
for (const note of sorted) {
if (note.pinned) {
add("pinned", "Pinned", note);
continue;
}
- if (note.modifiedAt === null) {
+ if (!dated) {
+ add("notes", "Notes", note);
+ continue;
+ }
+ const at = dateOf(note);
+ if (at === null) {
add("undated", "Earlier", note);
continue;
}
- const when = new Date(note.modifiedAt * 1000);
+ const when = new Date(at * 1000);
const ago = daysBetween(when, now);
if (ago <= 0) add("today", "Today", note);
else if (ago === 1) add("yesterday", "Yesterday", note);
@@ -43,11 +68,15 @@ export function groupNotes(notes: Note[], now = new Date()): Section[] {
add(`m${when.getMonth()}`, dateText(when, { month: "long" }), note);
else add(`y${when.getFullYear()}`, String(when.getFullYear()), note);
}
- // Map keeps insertion order, and notes went in newest first, so groups already run
- // newest first — Pinned aside, which always leads.
+ // Map keeps insertion order, and notes went in sorted, so groups already run in order —
+ // Pinned aside, which always leads, and Earlier (no date), which always ends.
const sections = [...out.values()];
const pinned = sections.filter((s) => s.key === "pinned");
- return [...pinned, ...sections.filter((s) => s.key !== "pinned")];
+ const undated = sections.filter((s) => s.key === "undated");
+ const rest = sections.filter((s) => s.key !== "pinned" && s.key !== "undated");
+ // With nothing pinned and no date groups, one untitled run: no "Notes" heading over it.
+ if (!dated && pinned.length === 0) rest.forEach((s) => (s.heading = ""));
+ return [...pinned, ...rest, ...undated];
}
/** The date a row shows: the time today, "Yesterday", the weekday this week, else the date. */
diff --git a/src/screens/notes/rich.ts b/src/screens/notes/rich.ts
index ca8a16d..ac8612c 100644
--- a/src/screens/notes/rich.ts
+++ b/src/screens/notes/rich.ts
@@ -288,3 +288,91 @@ export function carryRuns(from: string, runs: Run[], to: string): Run[] {
}
return out;
}
+
+/**
+ * `runs` over `text` in one shape, so two descriptions of the same formatting compare equal
+ * however they are cut — Apple's runs come in pieces (a word split in two), the editor's
+ * merged. Each unit takes its own character attributes and the setting of the unit that ends
+ * its line; neighbours differing only in length are one run; an attachment's run is never
+ * joined to anything. The backend has the same rule (notes.rs `canonical_runs`). Null when
+ * the runs do not describe the text.
+ */
+export function canonicalRuns(text: string, runs: Run[] | null): Run[] | null {
+ if (!runsFit(text, runs)) return null;
+ const units = perUnit(text, runs);
+ const out: Run[] = [];
+ let end = text.length - 1;
+ const ends: number[] = new Array(text.length);
+ for (let i = text.length - 1; i >= 0; i--) {
+ if (text[i] === "\n") end = i;
+ ends[i] = end;
+ }
+ for (let i = 0; i < text.length; i++) {
+ const own = units[i];
+ const line = units[ends[i]];
+ const style = line.style ?? null;
+ const unit: Run = {
+ length: 1,
+ style,
+ indent: line.indent ?? 0,
+ checked: style === STYLE.checklist ? Boolean(line.checked) : null,
+ bold: Boolean(own.bold),
+ italic: Boolean(own.italic),
+ underline: Boolean(own.underline),
+ strike: Boolean(own.strike),
+ link: own.link || null,
+ ...(style === STYLE.numbered && line.start && line.start !== 1 ? { start: line.start } : {}),
+ ...(line.quote ? { quote: true } : {}),
+ ...(own.emphasis ? { emphasis: own.emphasis } : {}),
+ ...(own.attachment ? { attachment: own.attachment } : {}),
+ };
+ const last = out[out.length - 1];
+ if (last && !last.attachment && !unit.attachment && same(last, unit)) last.length += 1;
+ else out.push(unit);
+ }
+ return out;
+}
+
+/** Whether `a` and `b` set `text` the same way, however each is cut. */
+export function sameFormatting(text: string, a: Run[] | null, b: Run[] | null): boolean {
+ const x = canonicalRuns(text, a);
+ const y = canonicalRuns(text, b);
+ return x !== null && y !== null && JSON.stringify(x) === JSON.stringify(y);
+}
+
+/**
+ * Where a checklist item goes when it is ticked or unticked with "Move Checked Items to the
+ * Bottom" on, as Notes sorts them: ticked, the item — with the items nested under it — goes
+ * to the end of its own checklist; unticked, back up to just above the ticked items. Only
+ * within the run of checklist lines it sits in, and only for a top-level item (a nested one
+ * moves with its parent). `index` is the item's place among the document's lines; `checked`
+ * its state after the change. The answer is which lines move (`from` up to `to`, not
+ * including it) and the line they go before (`before`, measured in the document as it was);
+ * `null` when nothing needs to move.
+ */
+export function checklistMove(doc: PMNode, index: number, checked: boolean): { from: number; to: number; before: number } | null {
+ const lines: PMNode[] = [];
+ doc.forEach((n) => lines.push(n));
+ const isItem = (i: number) => lines[i]?.type.name === "paragraph" && lines[i].attrs.style === STYLE.checklist;
+ const indent = (i: number) => Number(lines[i]?.attrs.indent ?? 0);
+ if (!isItem(index) || indent(index) !== 0) return null;
+ let start = index;
+ while (start > 0 && isItem(start - 1)) start--;
+ let end = index + 1;
+ while (end < lines.length && isItem(end)) end++;
+ // The item and its nested items.
+ let to = index + 1;
+ while (to < end && indent(to) > 0) to++;
+ // Top-level items of the run other than this one, by their first line.
+ const tops: number[] = [];
+ for (let i = start; i < end; i++) if (indent(i) === 0 && (i < index || i >= to)) tops.push(i);
+ if (checked) {
+ // To the end of the run, unless it is already below every other top-level item.
+ if (tops.every((i) => i < index)) return null;
+ return { from: index, to, before: end };
+ }
+ // Just above the first ticked item; where none is above it, it stays.
+ const firstTicked = tops.find((i) => lines[i].attrs.checked === true);
+ if (firstTicked === undefined || firstTicked > index) return null;
+ return { from: index, to, before: firstTicked };
+}
diff --git a/src/screens/photos/JumpTo.tsx b/src/screens/photos/JumpTo.tsx
index c1537fe..4bd6492 100644
--- a/src/screens/photos/JumpTo.tsx
+++ b/src/screens/photos/JumpTo.tsx
@@ -5,11 +5,11 @@
*/
import { useActiveRef } from "../../lib/screen";
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
-import { fitSrc, type Photo } from "../../lib/ipc";
+import { fitSrc } from "../../lib/ipc";
import { Portal } from "../../components/Portal";
import { fadeIn } from "../../lib/fade";
-export type MonthCover = { label: string; year: number; month: number; cover: Photo };
+export type MonthCover = { label: string; year: number; month: number; cover: { id: string } };
const SHORT = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
diff --git a/src/screens/photos/Slideshow.tsx b/src/screens/photos/Slideshow.tsx
index a09319f..7580dc1 100644
--- a/src/screens/photos/Slideshow.tsx
+++ b/src/screens/photos/Slideshow.tsx
@@ -1,97 +1,314 @@
/**
- * A slideshow, as Photos plays one: the photos one after another on black, each easing slowly
- * larger while it shows and dissolving into the next. Space pauses, the arrows step, Escape ends.
- * The controls sit in a glass capsule that fades away while the pointer is still.
+ * A slideshow, as Photos plays one: each photo whole on black, dissolving into the next. A video
+ * shows its own picture, then plays from where that picture is, and the show moves on when it
+ * ends. Space pauses, the arrows step, Escape ends; the controls sit in a glass capsule that
+ * fades away while the pointer is still.
*
- * Each photo is the picture made the size of the screen (fitSrc), so it is sharp from its first
- * frame — never a soft copy with a sharper one popping in over it. The next is fetched and
- * decoded before its turn, and the change waits for it: a photo is never shown half there. The
- * one leaving fades out as the next fades in — before, it stood whole behind the next for the
- * length of the fade, its edges showing round a narrower photo, and then vanished at once.
+ * Two layers, made once and never replaced, take turns: the next photo goes into the one behind,
+ * made the size of the screen (fitSrc) and decoded there — on that very element — before it is
+ * shown, so it is sharp from its first frame and never a blank or soft one. Only then does it
+ * dissolve in over the other, its opacity set by the page frame by frame (as lib/fade does:
+ * every animation WebKitGTK handed its compositor glitched on his Hyprland). The photo leaving
+ * holds whole beneath it and lets go only at the end, so the screen never dims to black between
+ * two photos. A layer is never torn down and built again: a new element painted nothing for a
+ * frame before its picture came in, which was the flash on every step. With reduced motion the
+ * change is a cut.
+ *
+ * A picture that cannot be had is passed over, never shown as a black frame.
*/
import { useActiveRef } from "../../lib/screen";
-import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { ChevronLeft, ChevronRight, Pause, Play, X } from "lucide-react";
-import { fitSrc, type Photo } from "../../lib/ipc";
-import { fadeIn } from "../../lib/fade";
+import { api, fitSrc, turnStyle, type Photo, type Turn } from "../../lib/ipc";
+/** How long a photo stays. */
const HOLD = 4000;
-const FADE = 900;
+/** How long one photo takes to dissolve into the next. */
+const FADE = 800;
+/** The longest a video plays before the show moves on. */
+const FILM_CAP = 60_000;
+
+const still = () => typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
-/** The picture a photo is shown at, whole on this screen. */
-const screenSrc = (p: Photo) => {
+/** The box a photo fills on this screen, whole, in CSS pixels. */
+function boxOf(p: Photo) {
+ const W = window.innerWidth;
+ const H = window.innerHeight;
const r = p.width && p.height ? p.width / p.height : 4 / 3;
- const w = Math.min(window.innerWidth, window.innerHeight * r);
- return fitSrc(p.id, Math.max(w, w / r) * (window.devicePixelRatio || 1));
+ const w = Math.min(W, H * r);
+ return { w, h: w / r, W, H };
+}
+
+/** The picture a photo is shown at: whole on this screen, in device pixels — never smaller. */
+export const screenSrc = (p: Photo) => {
+ const { w, h } = boxOf(p);
+ return fitSrc(p.id, Math.max(w, h) * (window.devicePixelRatio || 1));
};
-/** Fetched and decoded, by address. */
-const ready = new Map<string, Promise<void>>();
-const decode = (url: string) => {
- let p = ready.get(url);
+/** Fetched and decoded ahead, by address: the next is ready before its turn. */
+const warmed = new Map<string, Promise<boolean>>();
+function warm(url: string) {
+ let p = warmed.get(url);
if (!p) {
const img = new Image();
img.decoding = "async";
img.src = url;
- p = img.decode().catch(() => {});
- ready.set(url, p);
+ p = img.decode().then(
+ () => true,
+ () => false,
+ );
+ warmed.set(url, p);
+ if (warmed.size > 24) warmed.delete(warmed.keys().next().value as string);
}
return p;
-};
+}
+
+/** One of the two layers: its picture, and its film when it holds a video. */
+type Layer = { root: HTMLDivElement; img: HTMLImageElement; box: HTMLDivElement; film: HTMLVideoElement };
+
+/**
+ * `ids` are the photos in order — a whole library's worth is only its ids; each photo is fetched
+ * (`load`) a few ahead of its turn and held only while the show is near it. `videoBase` is the
+ * app's loopback server (video.rs); without it a video shows as its picture.
+ */
+export function Slideshow({
+ ids,
+ start,
+ load,
+ videoBase,
+ onClose,
+}: {
+ ids: string[];
+ start: number;
+ load: (ids: string[]) => Promise<Photo[]>;
+ videoBase?: string | null;
+ onClose: () => void;
+}) {
+ const first = Math.max(0, Math.min(start, ids.length - 1));
+ const have = useRef(new Map<string, Photo>());
+ /** The photo at `i`, fetched with the few after it when it is not here. */
+ const fetchAt = useCallback(
+ async (i: number): Promise<Photo | undefined> => {
+ const id = ids[i];
+ const here = have.current.get(id);
+ if (here) return here;
+ const want = ids.slice(i, i + 4).filter((x) => !have.current.has(x));
+ const got = await load(want).catch(() => [] as Photo[]);
+ // Only those near where the show is are kept.
+ for (const [x] of have.current) if (Math.abs(ids.indexOf(x) - i) > 12) have.current.delete(x);
+ for (const p of got) have.current.set(p.id, p);
+ return have.current.get(id);
+ },
+ [ids, load],
+ );
-export function Slideshow({ photos, start, onClose }: { photos: Photo[]; start: number; onClose: () => void }) {
- // Every photo, a video shown by its still, as Photos includes them.
- const list = photos;
- const first = Math.max(0, Math.min(start, photos.length - 1));
- // What shows, and the one fading out under it.
const [at, setAt] = useState(first);
- const [leaving, setLeaving] = useState<number | null>(null);
const [playing, setPlaying] = useState(true);
const [awake, setAwake] = useState(true);
- const shown = useRef(first);
+ const [ready, setReady] = useState(false);
+ /** Playing, as the timers that outlive a render read it. */
+ const playingNow = useRef(true);
- // To another photo, once its picture is decoded.
+ const a = useRef<Layer | null>(null);
+ const b = useRef<Layer | null>(null);
+ /** The layer in front, showing `shownAt`. */
+ const front = useRef<"a" | "b">("a");
+ const shownAt = useRef(-1);
const asked = useRef(0);
+ const fading = useRef(0);
+ const hold = useRef<number | undefined>(undefined);
+ const layer = (k: "a" | "b") => (k === "a" ? a.current : b.current);
+ const stopFilm = (l: Layer | null) => {
+ if (!l) return;
+ const v = l.film;
+ v.onended = v.onerror = null;
+ v.pause();
+ if (v.getAttribute("src")) {
+ v.removeAttribute("src");
+ v.load();
+ }
+ v.style.opacity = "0";
+ l.box.hidden = true;
+ };
+
+ /** The film of a video in the front layer: over its picture once a frame of it is here. */
+ const playFilm = useCallback(
+ async (l: Layer, p: Photo, mine: number, next: () => void) => {
+ const v = l.film;
+ const box = l.box;
+ const { w, h, W, H } = boxOf(p);
+ box.style.width = `${w}px`;
+ box.style.height = `${h}px`;
+ box.style.left = `${(W - w) / 2}px`;
+ box.style.top = `${(H - h) / 2}px`;
+ let turn: Turn = [1, 0, 0, 1];
+ let which: "video" | "original" = "video";
+ try {
+ turn = await api.photoVideoTurn(p.id, which);
+ } catch {
+ which = "original";
+ turn = await api.photoVideoTurn(p.id, which).catch(() => [1, 0, 0, 1] as Turn);
+ }
+ if (mine !== asked.current) return;
+ Object.assign(v.style, { position: "", left: "", top: "", width: "100%", height: "100%", translate: "", transform: "", maxWidth: "", maxHeight: "" }, turnStyle(turn, p.width, p.height));
+ v.style.opacity = "0";
+ box.hidden = false;
+ const shown = () => {
+ if (mine === asked.current) requestAnimationFrame(() => (v.style.opacity = "1"));
+ };
+ type Rvfc = HTMLVideoElement & { requestVideoFrameCallback?: (cb: () => void) => number };
+ v.ontimeupdate = () => {
+ if (v.currentTime > 0.04 && v.readyState >= 2) {
+ v.ontimeupdate = null;
+ shown();
+ }
+ };
+ const cap = window.setTimeout(next, FILM_CAP);
+ v.onended = () => {
+ window.clearTimeout(cap);
+ // The last frame stays: the next photo dissolves in over it.
+ if (mine === asked.current) next();
+ };
+ v.onerror = () => {
+ if (mine !== asked.current) return;
+ if (which === "video") {
+ which = "original";
+ v.src = `${videoBase}/${p.id}/original`;
+ void v.play().catch(() => undefined);
+ return;
+ }
+ // Not playable here: its picture stays its time, as a photo's would.
+ window.clearTimeout(cap);
+ stopFilm(l);
+ hold.current = window.setTimeout(next, HOLD);
+ };
+ v.src = `${videoBase}/${p.id}/${which}`;
+ (v as Rvfc).requestVideoFrameCallback?.(shown);
+ if (!playingNow.current) return;
+ // With its sound, as Photos plays one; muted only where the engine will not start it so.
+ await v.play().catch(async () => {
+ v.muted = true;
+ await v.play().catch(() => undefined);
+ });
+ },
+ [videoBase],
+ );
+
+ /** To the photo `by` along, once its picture is decoded in the layer behind. */
const go = useCallback(
- (by: number) => {
- const to = (shown.current + by + list.length) % list.length;
+ async (by: number, from?: number) => {
+ const n = ids.length;
+ if (!n) return;
const mine = ++asked.current;
- void decode(screenSrc(list[to])).then(() => {
- if (mine !== asked.current || to === shown.current) return;
- setLeaving(shown.current);
- shown.current = to;
- setAt(to);
- });
+ window.clearTimeout(hold.current);
+ let to = (((from ?? shownAt.current) + by) % n + n) % n;
+ // A picture that cannot be had is passed over (a few at most), never shown black.
+ for (let tries = 0; tries < Math.min(n, 6); tries++) {
+ const p = await fetchAt(to);
+ if (mine !== asked.current) return;
+ const url = p ? screenSrc(p) : null;
+ if (p && url && (await warm(url))) {
+ const back = layer(front.current === "a" ? "b" : "a");
+ const top = layer(front.current);
+ if (!back || !top) return;
+ stopFilm(back);
+ back.img.src = url;
+ back.img.alt = p.filename ?? "Photo";
+ // Decoded on the element that will show it, so its first painted frame is whole.
+ await back.img.decode().catch(() => undefined);
+ if (mine !== asked.current) return;
+ await dissolve(back, top, shownAt.current < 0 || still());
+ if (mine !== asked.current) return;
+ front.current = front.current === "a" ? "b" : "a";
+ shownAt.current = to;
+ setAt(to);
+ setReady(true);
+ stopFilm(top);
+ // Ready before its turn: the next one's picture.
+ void fetchAt((to + 1) % n).then((q) => q && warm(screenSrc(q)));
+ const next = () => {
+ if (playingNow.current && mine === asked.current) void go(1);
+ };
+ if (p.kind === "video" && videoBase) void playFilm(back, p, mine, next);
+ else if (playingNow.current && n > 1) hold.current = window.setTimeout(next, HOLD);
+ return;
+ }
+ to = (to + Math.sign(by || 1) + n) % n;
+ }
},
- [list],
+ [ids, fetchAt, playFilm, videoBase],
);
- useEffect(() => {
- if (leaving === null) return undefined;
- const t = window.setTimeout(() => setLeaving(null), FADE);
- return () => window.clearTimeout(t);
- }, [leaving, at]);
- // On, one after another; round again at the end, as Photos loops a slideshow.
- useEffect(() => {
- if (!playing || list.length < 2) return undefined;
- const t = window.setTimeout(() => go(1), HOLD);
- return () => window.clearTimeout(t);
- }, [at, playing, go, list.length]);
+ /** The layer behind dissolves in over the one in front, which holds whole until the end. */
+ const dissolve = (inc: Layer, out: Layer, cut: boolean) =>
+ new Promise<void>((done) => {
+ cancelAnimationFrame(fading.current);
+ inc.root.style.zIndex = "2";
+ out.root.style.zIndex = "1";
+ if (cut) {
+ inc.root.style.opacity = "1";
+ out.root.style.opacity = "0";
+ done();
+ return;
+ }
+ inc.root.style.opacity = "0";
+ out.root.style.opacity = "1";
+ const t0 = performance.now();
+ const step = (now: number) => {
+ const t = Math.max(0, Math.min(1, (now - t0) / FADE));
+ // Eased both ways, as a dissolve on a Mac: no jump at either end.
+ const k = t < 0.5 ? 2 * t * t : 1 - (2 - 2 * t) ** 2 / 2;
+ inc.root.style.opacity = String(k);
+ // Whole beneath the arriving photo for nearly all of it — no dip to black where the two
+ // overlap — and gone by the end where it is wider than the arriving one.
+ out.root.style.opacity = String(1 - k ** 4);
+ if (t < 1) fading.current = requestAnimationFrame(step);
+ else {
+ out.root.style.opacity = "0";
+ done();
+ }
+ };
+ fading.current = requestAnimationFrame(step);
+ });
- // The next is on its way while this one shows.
+ // The first photo, then on round the show; everything let go at the end.
useEffect(() => {
- const next = list[(at + 1) % list.length];
- if (next) void decode(screenSrc(next));
- }, [at, list]);
+ void go(0, first);
+ return () => {
+ asked.current++;
+ window.clearTimeout(hold.current);
+ cancelAnimationFrame(fading.current);
+ stopFilm(a.current);
+ stopFilm(b.current);
+ };
+ }, []); // eslint-disable-line react-hooks/exhaustive-deps
+
+ const toggle = useCallback(() => {
+ setPlaying((was) => {
+ const now = !was;
+ playingNow.current = now;
+ const l = layer(front.current);
+ const filming = !!l?.film.getAttribute("src") && !l.box.hidden;
+ if (!now) {
+ window.clearTimeout(hold.current);
+ l?.film.pause();
+ } else if (filming) void l?.film.play().catch(() => undefined);
+ else if (ids.length > 1) {
+ const mine = asked.current;
+ hold.current = window.setTimeout(() => mine === asked.current && void go(1), HOLD);
+ }
+ return now;
+ });
+ }, [go, ids.length]); // eslint-disable-line react-hooks/exhaustive-deps
const live = useActiveRef();
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (!live.current) return;
if (e.key === "Escape") onClose();
- else if (e.key === " ") setPlaying((p) => !p);
- else if (e.key === "ArrowRight") go(1);
- else if (e.key === "ArrowLeft") go(-1);
+ else if (e.key === " ") toggle();
+ else if (e.key === "ArrowRight") void go(1);
+ else if (e.key === "ArrowLeft") void go(-1);
else return;
e.preventDefault();
e.stopPropagation();
@@ -99,60 +316,58 @@ export function Slideshow({ photos, start, onClose }: { photos: Photo[]; start:
// Before the screen's own keys, which would otherwise step the photo behind or close it.
window.addEventListener("keydown", onKey, true);
return () => window.removeEventListener("keydown", onKey, true);
- }, [go, onClose]);
+ }, [go, toggle, onClose]); // eslint-disable-line react-hooks/exhaustive-deps
// The controls show when the pointer moves and go once it rests.
- const idle = useRef<number | null>(null);
+ const idle = useRef<number | undefined>(undefined);
const wake = () => {
setAwake(true);
- if (idle.current !== null) window.clearTimeout(idle.current);
+ window.clearTimeout(idle.current);
idle.current = window.setTimeout(() => setAwake(false), 2200);
};
useEffect(() => {
wake();
- return () => {
- if (idle.current !== null) window.clearTimeout(idle.current);
- };
+ return () => window.clearTimeout(idle.current);
}, []); // eslint-disable-line react-hooks/exhaustive-deps
- // The arriving photo dissolves in over the one leaving, frame by frame from the page, set before
- // its first frame is painted.
- const arriving = useRef<HTMLImageElement | null>(null);
- useLayoutEffect(() => {
- if (leaving !== null) fadeIn(arriving.current, { duration: FADE });
- }, [at]); // eslint-disable-line react-hooks/exhaustive-deps
+ const mount = (k: "a" | "b") => (root: HTMLDivElement | null) => {
+ const ref = k === "a" ? a : b;
+ if (!root) {
+ ref.current = null;
+ return;
+ }
+ ref.current = {
+ root,
+ img: root.querySelector("img") as HTMLImageElement,
+ box: root.querySelector(".px-slide-film") as HTMLDivElement,
+ film: root.querySelector("video") as HTMLVideoElement,
+ };
+ };
+ const slide = (k: "a" | "b") => (
+ <div ref={mount(k)} className="px-slide" style={{ opacity: 0 }} aria-hidden={k !== front.current || undefined}>
+ <img alt="" decoding="sync" draggable={false} />
+ <div className="px-slide-film" hidden>
+ <video playsInline preload="auto" aria-label="Video" />
+ </div>
+ </div>
+ );
- const photo = list[at];
- if (!photo) return null;
- const old = leaving !== null ? list[leaving] : null;
return (
- <div
- className={`px-show${awake ? " is-awake" : ""}`}
- role="dialog"
- aria-label="Slideshow"
- onMouseMove={wake}
- onClick={wake}
- >
- {old && <img key={`l${old.id}-${leaving}`} className="px-slide is-leaving" src={screenSrc(old)} alt="" aria-hidden="true" />}
- <img
- key={`a${photo.id}-${at}`}
- ref={arriving}
- className="px-slide"
- src={screenSrc(photo)}
- alt={photo.filename ?? "Photo"}
- />
+ <div className={`px-show${awake ? " is-awake" : ""}`} role="dialog" aria-label="Slideshow" aria-busy={!ready} onMouseMove={wake} onClick={wake}>
+ {slide("a")}
+ {slide("b")}
<div className="px-show-bar toolbar-group" role="toolbar" aria-label="Slideshow controls">
- <button className="tool px-cap" aria-label="Previous" onClick={() => go(-1)}>
+ <button className="tool px-cap" aria-label="Previous" onClick={() => void go(-1)}>
<ChevronLeft size={18} />
</button>
- <button className="tool px-cap" aria-label={playing ? "Pause" : "Play"} onClick={() => setPlaying((p) => !p)}>
+ <button className="tool px-cap" aria-label={playing ? "Pause" : "Play"} onClick={toggle}>
{playing ? <Pause size={17} fill="currentColor" strokeWidth={0} /> : <Play size={17} fill="currentColor" strokeWidth={0} />}
</button>
- <button className="tool px-cap" aria-label="Next" onClick={() => go(1)}>
+ <button className="tool px-cap" aria-label="Next" onClick={() => void go(1)}>
<ChevronRight size={18} />
</button>
<span className="px-show-count" aria-live="polite">
- {at + 1} of {list.length}
+ {at + 1} of {ids.length}
</span>
<button className="tool px-cap" aria-label="End Slideshow" title="End Slideshow (Esc)" onClick={onClose}>
<X size={17} />
diff --git a/src/screens/photos/VideoPlayer.tsx b/src/screens/photos/VideoPlayer.tsx
index 77d4596..8437ab9 100644
--- a/src/screens/photos/VideoPlayer.tsx
+++ b/src/screens/photos/VideoPlayer.tsx
@@ -4,6 +4,12 @@
* where it is, a scrubber, what is left, and sound. A click on the film plays or pauses it;
* Space does too (the viewer's own keys still step through the photos).
*
+ * Until the film's first frame is on screen its poster stands in its place — the video's own
+ * picture, sharp, made the size it is shown at — and the film is drawn over it only once a frame
+ * of it has been presented: WebKitGTK paints a video black from the moment it starts loading
+ * until its first frame arrives, and that black flashed on every open. While it waits on the
+ * network a small spinner says so.
+ *
* The scrubber follows the film every frame (the engine's own timeupdate comes four times a
* second, and a progress bar that jumps reads as a stutter), and dragging it seeks as it goes.
*/
@@ -26,6 +32,7 @@ export function VideoPlayer({
label,
style,
turn,
+ zoom = 1,
shape,
onError,
}: {
@@ -35,6 +42,8 @@ export function VideoPlayer({
style?: React.CSSProperties;
/** How the film is turned, as its file records it; not shown until it is known. */
turn?: Turn;
+ /** How much larger than its box the film is drawn (its clean aperture; see turnStyle). */
+ zoom?: number;
/** The photo's own width and height, upright: the box the film is turned into. */
shape: { w: number; h: number };
onError: () => void;
@@ -48,6 +57,39 @@ export function VideoPlayer({
const [muted, setMuted] = useState(false);
const [awake, setAwake] = useState(true);
const [hover, setHover] = useState<{ x: number; t: number } | null>(null);
+ /** A frame of the film has been presented: drawn over its poster from then on. */
+ const [shown, setShown] = useState(false);
+ /** Waiting on its bytes for longer than a moment. */
+ const [stalled, setStalled] = useState(false);
+ const stallTimer = useRef<number | undefined>(undefined);
+ const waitOn = useCallback((on: boolean) => {
+ window.clearTimeout(stallTimer.current);
+ if (on) stallTimer.current = window.setTimeout(() => setStalled(true), 450);
+ else setStalled(false);
+ }, []);
+ useEffect(() => {
+ waitOn(true);
+ return () => window.clearTimeout(stallTimer.current);
+ }, [waitOn]);
+ // The first frame presented, as the engine says it (requestVideoFrameCallback), or failing
+ // that the clock moving: only then is the film drawn over its poster.
+ useEffect(() => {
+ const v = film.current;
+ if (!v || shown) return undefined;
+ type Rvfc = HTMLVideoElement & { requestVideoFrameCallback?: (cb: () => void) => number; cancelVideoFrameCallback?: (id: number) => void };
+ const rv = v as Rvfc;
+ let id = 0;
+ const done = () => requestAnimationFrame(() => setShown(true));
+ if (rv.requestVideoFrameCallback) id = rv.requestVideoFrameCallback(done);
+ const moved = () => {
+ if (v.currentTime > 0.04 && v.readyState >= 2) done();
+ };
+ v.addEventListener("timeupdate", moved);
+ return () => {
+ v.removeEventListener("timeupdate", moved);
+ if (id && rv.cancelVideoFrameCallback) rv.cancelVideoFrameCallback(id);
+ };
+ }, [shown]);
const dragging = useRef(false);
// Another screen brought to the front pauses it, as leaving a film does on a Mac.
const active = useScreenActive();
@@ -118,14 +160,15 @@ export function VideoPlayer({
return (
<div className={`px-player${awake || !playing ? " is-awake" : ""}`} style={style} onPointerMove={wake}>
+ {/* The video's own picture, sharp, until a frame of the film is on screen. */}
+ {!(shown && turn) && <img className="px-player-poster" src={poster} alt="" aria-hidden="true" decoding="sync" draggable={false} />}
<video
ref={film}
className="px-shown"
- // Turned as it was recorded, in the photo's own box (lib/ipc turnStyle); hidden until
- // the turn is known, so a film never shows sideways first.
- style={turn ? turnStyle(turn, shape.w, shape.h) : { visibility: "hidden" }}
+ // Turned as it was recorded, in the photo's own box (lib/ipc turnStyle); not drawn
+ // until the turn is known and a frame is here, so a film never shows sideways or black.
+ style={{ ...(turn ? turnStyle(turn, shape.w, shape.h, zoom) : {}), opacity: shown && turn ? 1 : 0 }}
src={src}
- poster={poster}
aria-label={label}
autoPlay
playsInline
@@ -138,15 +181,26 @@ export function VideoPlayer({
setPlaying(true);
wake();
}}
+ onWaiting={() => waitOn(true)}
+ onPlaying={() => waitOn(false)}
+ onCanPlay={() => waitOn(false)}
+ onSeeking={() => waitOn(true)}
onPause={() => {
setPlaying(false);
draw();
}}
onLoadedMetadata={draw}
- onSeeked={draw}
+ onSeeked={() => {
+ waitOn(false);
+ draw();
+ }}
onVolumeChange={(e) => setMuted(e.currentTarget.muted)}
- onError={onError}
+ onError={() => {
+ waitOn(false);
+ onError();
+ }}
/>
+ {stalled && <span className="px-player-wait" role="status" aria-label="Loading video" />}
<div className="px-player-bar toolbar-group" role="toolbar" aria-label="Video controls" onClick={(e) => e.stopPropagation()}>
<button className="tool px-cap" aria-label={playing ? "Pause" : "Play"} onClick={toggle}>
{playing ? <Pause size={17} strokeWidth={0} fill="currentColor" /> : <Play size={17} strokeWidth={0} fill="currentColor" />}
diff --git a/src/screens/photos/list.ts b/src/screens/photos/list.ts
new file mode 100644
index 0000000..62d88cd
--- /dev/null
+++ b/src/screens/photos/list.ts
@@ -0,0 +1,255 @@
+/**
+ * A grid's photos without holding the library: the index whole (every photo's id, grouping date
+ * and marks — a few bytes each), and the photos themselves fetched a page at a time as the grid
+ * or the viewer comes near them, at most KEEP held at once, the farthest let go. A library of
+ * fifty thousand opens on its first screen and stays the same size in memory however far it is
+ * scrolled.
+ */
+import { api, type Photo, type PhotoIndex } from "../../lib/ipc";
+
+/** Photos asked for at once. */
+export const PAGE = 240;
+/** The most photos held at once; past it the farthest from where the grid is go. */
+export const KEEP = 2400;
+
+const KINDS = ["image", "video", "live"] as const;
+
+/** Whether two reads of one photo are the same in every field. */
+export function samePhoto(a: Photo, b: Photo): boolean {
+ for (const k in b) {
+ const x = (a as Record<string, unknown>)[k];
+ const y = (b as Record<string, unknown>)[k];
+ if (x === y) continue;
+ if (Array.isArray(x) && Array.isArray(y) && x.length === y.length && x.every((v, i) => v === y[i])) continue;
+ return false;
+ }
+ return true;
+}
+
+/**
+ * The photos fetched, by id, for every list drawn from them. A photo read again unchanged keeps
+ * the object it had, so nothing draws again for a read that changed nothing.
+ */
+export class PhotoStore {
+ private photos = new Map<string, Photo>();
+ /** Read before the latest refresh: shown, and fetched again when next wanted. */
+ private stale = new Set<string>();
+ private asked = new Set<string>();
+ /** How many times each photo held has changed: what a month watches to draw a tile again. */
+ private revs = new Map<string, number>();
+ private listeners = new Set<() => void>();
+ private center = 0;
+ private list: PhotoList | null = null;
+ private told = 0;
+ /** Bumped by every change; what a view subscribes to. */
+ version = 0;
+
+ get(id: string): Photo | undefined {
+ return this.photos.get(id);
+ }
+ turns(id: string): number {
+ return this.revs.get(id) ?? 0;
+ }
+ private turned(id: string) {
+ this.revs.set(id, (this.revs.get(id) ?? 0) + 1);
+ }
+ get size(): number {
+ return this.photos.size;
+ }
+ /** Where the grid (or the viewer) last asked from. */
+ get near(): number {
+ return this.center;
+ }
+ subscribe = (listener: () => void) => {
+ this.listeners.add(listener);
+ return () => void this.listeners.delete(listener);
+ };
+ private changed() {
+ this.version++;
+ // Once a frame however many pages land in it.
+ if (this.told) return;
+ this.told = requestAnimationFrame(() => {
+ this.told = 0;
+ this.listeners.forEach((l) => l());
+ });
+ }
+
+ /** Photos read, kept by id; one unchanged keeps the object it had. */
+ put(read: Photo[]) {
+ let any = false;
+ for (const p of read) {
+ this.asked.delete(p.id);
+ this.stale.delete(p.id);
+ const had = this.photos.get(p.id);
+ if (had && samePhoto(had, p)) continue;
+ this.photos.set(p.id, p);
+ if (had) this.turned(p.id);
+ any = true;
+ }
+ this.trim();
+ if (any) this.changed();
+ }
+
+ /** A change made here, shown at once (Favorite, a title, a date). */
+ patch(ids: Iterable<string>, change: (p: Photo) => Photo) {
+ let any = false;
+ for (const id of ids) {
+ const p = this.photos.get(id);
+ if (!p) continue;
+ this.photos.set(id, change(p));
+ this.turned(id);
+ any = true;
+ }
+ if (any) this.changed();
+ }
+
+ /** The list now drawn: where the farthest are measured from. */
+ use(list: PhotoList) {
+ this.list = list;
+ }
+
+ /**
+ * Everything held is from before this moment (a sync landed): still shown, and fetched again
+ * as it is wanted; anything far off is let go now rather than fetched again.
+ */
+ refresh() {
+ for (const id of this.photos.keys()) this.stale.add(id);
+ this.asked.clear();
+ }
+
+ /** The photos `from`–`to` of `list` on their way, a page at a time, unless here (and fresh). */
+ need(list: PhotoList, from: number, to: number): Promise<void> {
+ from = Math.max(0, from);
+ to = Math.min(list.length - 1, to);
+ if (to < from) return Promise.resolve();
+ this.center = Math.round((from + to) / 2);
+ this.list = list;
+ const wanted: string[] = [];
+ for (let i = from; i <= to; i++) {
+ const id = list.ids[i];
+ if ((!this.photos.has(id) || this.stale.has(id)) && !this.asked.has(id)) wanted.push(id);
+ }
+ if (wanted.length === 0) return Promise.resolve();
+ wanted.forEach((id) => this.asked.add(id));
+ const pages: Promise<void>[] = [];
+ for (let i = 0; i < wanted.length; i += PAGE) {
+ const ids = wanted.slice(i, i + PAGE);
+ pages.push(
+ api.photosGet(ids).then(
+ (read) => {
+ this.put(read);
+ // Gone from the library meanwhile: asked for no longer.
+ ids.forEach((id) => this.asked.delete(id));
+ },
+ () => ids.forEach((id) => this.asked.delete(id)),
+ ),
+ );
+ }
+ return Promise.all(pages).then(() => {});
+ }
+
+ /** Photos by id, fetched where they are not here: for an action on a selection. */
+ async load(ids: string[]): Promise<Photo[]> {
+ const missing = ids.filter((id) => !this.photos.has(id));
+ if (missing.length) {
+ const read = await api.photosGet(missing);
+ // Held only for this answer: never pushes out what the grid is showing.
+ const got = new Map(read.map((p) => [p.id, p]));
+ return ids.map((id) => this.photos.get(id) ?? got.get(id)).filter((p): p is Photo => Boolean(p));
+ }
+ return ids.map((id) => this.photos.get(id)!);
+ }
+
+ /** Held to KEEP: the farthest from where the grid is go first. */
+ private trim() {
+ if (this.photos.size <= KEEP) return;
+ const list = this.list;
+ const far = [...this.photos.keys()]
+ .map((id) => {
+ const at = list ? list.indexOf(id) : -1;
+ return [id, at < 0 ? Infinity : Math.abs(at - this.center)] as const;
+ })
+ .sort((a, b) => b[1] - a[1]);
+ const goal = Math.floor(KEEP * 0.8);
+ for (const [id] of far) {
+ if (this.photos.size <= goal) break;
+ this.photos.delete(id);
+ this.stale.delete(id);
+ this.revs.delete(id);
+ }
+ }
+}
+
+/** One read of a source: its index, and its photos as they are here. */
+export class PhotoList {
+ readonly ids: string[];
+ readonly keys: number[];
+ readonly marks: number[];
+ readonly first: number | null;
+ readonly last: number | null;
+ private places: Map<string, number> | null = null;
+
+ constructor(index: PhotoIndex, readonly store: PhotoStore) {
+ this.ids = index.ids;
+ this.keys = index.keys;
+ this.marks = index.marks;
+ this.first = index.first;
+ this.last = index.last;
+ }
+
+ /** A list from photos alone: the first screen, before the index comes. */
+ static of(photos: Photo[], store: PhotoStore, keyOf: (p: Photo) => number): PhotoList {
+ store.put(photos);
+ const taken = photos.map((p) => p.takenAt);
+ return new PhotoList(
+ {
+ ids: photos.map((p) => p.id),
+ keys: photos.map(keyOf),
+ marks: photos.map((p) => (p.kind === "video" ? 1 : p.kind === "live" ? 2 : 0) | (p.favorite ? 4 : 0) | ((p.rating ?? 0) << 3)),
+ first: taken.length ? Math.min(...taken) : null,
+ last: taken.length ? Math.max(...taken) : null,
+ },
+ store,
+ );
+ }
+
+ get length(): number {
+ return this.ids.length;
+ }
+ /** The photo at `i`, when it is here. */
+ at(i: number): Photo | undefined {
+ const id = this.ids[i];
+ return id === undefined ? undefined : this.store.get(id);
+ }
+ indexOf(id: string): number {
+ if (!this.places) this.places = new Map(this.ids.map((x, i) => [x, i]));
+ return this.places.get(id) ?? -1;
+ }
+ kind(i: number): Photo["kind"] {
+ return this.at(i)?.kind ?? KINDS[this.marks[i] & 3] ?? "image";
+ }
+ favorite(i: number): boolean {
+ return this.at(i)?.favorite ?? (this.marks[i] & 4) !== 0;
+ }
+ stars(i: number): number {
+ return this.at(i)?.rating ?? (this.marks[i] >> 3);
+ }
+ /** The photos `from`–`to` on their way. */
+ need(from: number, to: number): Promise<void> {
+ return this.store.need(this, from, to);
+ }
+ /** The same list without `gone` (taken out here, at once). */
+ without(gone: Set<string>): PhotoList {
+ const keep = this.ids.map((id) => !gone.has(id));
+ const pick = <T,>(xs: T[]) => xs.filter((_, i) => keep[i]);
+ return new PhotoList({ ids: pick(this.ids), keys: pick(this.keys), marks: pick(this.marks), first: this.first, last: this.last }, this.store);
+ }
+ /** The same as `other` throughout: a read that changed nothing. */
+ same(other: PhotoList | null): boolean {
+ if (!other || other.length !== this.length || other.first !== this.first || other.last !== this.last) return false;
+ for (let i = 0; i < this.length; i++) {
+ if (other.ids[i] !== this.ids[i] || other.keys[i] !== this.keys[i] || other.marks[i] !== this.marks[i]) return false;
+ }
+ return true;
+ }
+}
diff --git a/src/screens/reminderQuick.ts b/src/screens/reminderQuick.ts
new file mode 100644
index 0000000..eac63fd
--- /dev/null
+++ b/src/screens/reminderQuick.ts
@@ -0,0 +1,56 @@
+/**
+ * A reminder typed in one line, read the way Reminders reads one: "Call mom tomorrow 6pm",
+ * "Water plants daily", "!! Pay rent every month". The day, time and repeat come from Quick
+ * Event's reader (calendar/quick.ts); a leading or trailing `!`, `!!` or `!!!` is the
+ * priority, as the phone's list shows it. Anything else stays in the title — a place is not
+ * taken out, since a reminder's place is set on the phone. Nothing here is saved: the add
+ * field shows what was understood first, and can add the line as typed instead.
+ */
+import { parseQuick } from "./calendar/quick.ts";
+
+export type QuickReminder = {
+ title: string;
+ /** Local unix seconds of the moment due, or, all day, of that day's local midnight. */
+ dueAt: number | null;
+ allDay: boolean;
+ /** Apple's repeat: 0 daily, 1 weekly, 2 monthly, 3 yearly; with how many between. */
+ repeat: { frequency: number; interval: number } | null;
+ /** Apple's scale: 0 none, 1 high, 5 medium, 9 low. */
+ priority: number;
+};
+
+const FREQUENCY = { daily: 0, weekly: 1, monthly: 2, yearly: 3 } as const;
+const PRIORITY: Record<number, number> = { 1: 9, 2: 5, 3: 1 };
+
+export function parseReminder(text: string, now: Date = new Date(), dayFirst?: boolean): QuickReminder {
+ let line = text.trim();
+ let priority = 0;
+ const bang = /^(!{1,3})\s+|\s+(!{1,3})$/.exec(line);
+ if (bang) {
+ priority = PRIORITY[(bang[1] ?? bang[2]).length];
+ line = (line.slice(0, bang.index) + " " + line.slice(bang.index + bang[0].length)).trim();
+ }
+ const q = parseQuick(line, now, dayFirst);
+ // Where Quick Event took out a place, it goes back: a reminder keeps "at the office" as
+ // words, as the phone does when typed.
+ let title = q.location ? `${q.title} at ${q.location}`.trim() : q.title;
+ if (!title) title = line;
+ const repeat = q.repeat ? { frequency: FREQUENCY[q.repeat.freq], interval: q.repeat.interval } : null;
+ const midnight = (d: Date) => Math.floor(new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime() / 1000);
+ let dueAt: number | null = null;
+ let allDay = false;
+ if (q.timed) {
+ dueAt = q.startsAt;
+ } else if (q.dated) {
+ dueAt = q.startsAt;
+ allDay = true;
+ } else if (repeat) {
+ // A repeat needs a first day, as on the phone: today.
+ dueAt = midnight(now);
+ allDay = true;
+ }
+ return { title, dueAt, allDay, repeat, priority };
+}
+
+/** Whether a line says more than a title — the field then shows what it understood. */
+export const understood = (q: QuickReminder) => q.dueAt !== null || q.repeat !== null || q.priority !== 0;
diff --git a/src/styles/a11y.css b/src/styles/a11y.css
index 6be5019..f693fd2 100644
--- a/src/styles/a11y.css
+++ b/src/styles/a11y.css
@@ -10,10 +10,10 @@
* floating surface gets a real border here, selection takes Highlight, focus a Highlight
* outline, and the glyphs drawn in an app's colour take the text colour.
*
- * On Linux neither query fires today: WebKitGTK does not map GTK's high-contrast theme or the
- * Settings portal's org.freedesktop.appearance contrast key to prefers-contrast, and it has no
- * forced-colours mode (docs/accessibility.md). The rules are written so the moment either is
- * mapped — by WebKitGTK, or by the app reading the portal — they apply as they are.
+ * On Linux WebKitGTK maps neither: it has no forced-colours mode, and it does not turn the
+ * Settings portal's org.freedesktop.appearance contrast key into prefers-contrast. The app
+ * reads that key itself (appearance.rs) and marks the root data-contrast="more"; the rules
+ * under that mark below are the Increase Contrast ones, so GNOME's and KDE's switch applies.
*/
/* ---- Increase Contrast ---------------------------------------------------------------- */
@@ -75,9 +75,65 @@
:is(.quiet, .segment, .picker-button) { box-shadow: inset 0 0 0 1px var(--field-edge); }
}
+/* ---- Increase Contrast, read from the desktop ---------------------------------------- */
+/* The same rules, where the engine does not map the setting and the app reads it instead
+ (Linux: the Settings portal, appearance.rs, marks the root data-contrast="more"). Kept in
+ step with the blocks above and with tokens.css's glass rule. */
+:root:root:root[data-contrast="more"] {
+ --glass: var(--bg);
+ --glass-thick: var(--sheet);
+ --glass-blur: none;
+ --text-2: #3a3a3e;
+ --text-3: #4a4a4f;
+ --separator: rgba(0, 0, 0, 0.42);
+ --field-edge: rgba(0, 0, 0, 0.6);
+ --field-edge-hover: rgba(0, 0, 0, 0.75);
+ --glass-edge: rgba(0, 0, 0, 0.5);
+ --fill: color-mix(in srgb, var(--text) 12%, transparent);
+ --fill-selected: color-mix(in srgb, var(--text) 20%, transparent);
+ --accent-ring: var(--accent-strong);
+ --ring: 0 0 0 2px var(--accent-strong);
+ --focus-ring: 2px solid var(--text);
+}
+@media (prefers-color-scheme: dark) {
+ :root:root:root[data-contrast="more"]:not([data-theme="light"]) {
+ --text-2: #d1d1d6;
+ --text-3: #c2c2c7;
+ --separator: rgba(255, 255, 255, 0.45);
+ --field-edge: rgba(255, 255, 255, 0.6);
+ --field-edge-hover: rgba(255, 255, 255, 0.75);
+ --glass-edge: rgba(255, 255, 255, 0.45);
+ --accent-strong: #40a9ff;
+ --danger: #ff9999;
+ }
+ :root:root:root[data-contrast="more"]:not([data-theme="light"])[data-app="calendar"] { --accent-strong: #ff7a7a; }
+ :root:root:root[data-contrast="more"]:not([data-theme="light"])[data-app="notes"] { --accent-strong: #ffd600; }
+}
+:root:root:root[data-contrast="more"][data-theme="dark"] {
+ --text-2: #d1d1d6;
+ --text-3: #c2c2c7;
+ --separator: rgba(255, 255, 255, 0.45);
+ --field-edge: rgba(255, 255, 255, 0.6);
+ --field-edge-hover: rgba(255, 255, 255, 0.75);
+ --glass-edge: rgba(255, 255, 255, 0.45);
+ --accent-strong: #40a9ff;
+ --danger: #ff9999;
+}
+:root:root:root[data-contrast="more"][data-theme="dark"][data-app="calendar"] { --accent-strong: #ff7a7a; }
+:root:root:root[data-contrast="more"][data-theme="dark"][data-app="notes"] { --accent-strong: #ffd600; }
+:root[data-contrast="more"] :is(.modal-sheet, .popover, .toast, .row-menu, .picker-menu, .cx-popover, .cx-zones,
+ .gsearch-panel, .gsearch-out, .format-panel, .upload-menu, .upload-tray, .px-info, .px-jump,
+ .toolbar-group, .sidebar) {
+ outline: 1px solid var(--glass-edge);
+ outline-offset: -1px;
+}
+:root[data-contrast="more"] :is(.quiet, .segment, .picker-button) { box-shadow: inset 0 0 0 1px var(--field-edge); }
+
/* ---- Forced colours (Windows High Contrast) -------------------------------------------- */
@media (forced-colors: active) {
+ /* A note's table is framed by a shadow, which forced colours drop: a real border instead. */
+ .nf-table { border: 1px solid CanvasText; }
/* Every control with an edge of its own: the fill that marked it is gone. */
:is(.primary, .quiet, .icon-button, .tool, .segment, .picker-button, .toast-action,
.sidebar-toggle, .compact-back, .search-clear, .confirm-answer) {
diff --git a/src/styles/app.css b/src/styles/app.css
index 5b51c54..4667e15 100644
--- a/src/styles/app.css
+++ b/src/styles/app.css
@@ -700,9 +700,9 @@
.contact-row:hover { background: color-mix(in srgb, var(--text) 5%, transparent); }
/* As macOS selects: the accent with white text while the list has focus, grey after. */
-.contact-row[aria-current="true"] { background: color-mix(in srgb, var(--text) 11%, transparent); }
-.contact-rows.is-focused .contact-row[aria-current="true"] { background: var(--accent-fill); color: var(--on-accent); }
-.contact-rows.is-focused .contact-row[aria-current="true"] .avatar:not(:has(img)) { background: rgba(255, 255, 255, 0.28); color: #fff; }
+.contact-row[aria-selected="true"] { background: color-mix(in srgb, var(--text) 11%, transparent); }
+.contact-rows.is-focused .contact-row[aria-selected="true"] { background: var(--accent-fill); color: var(--on-accent); }
+.contact-rows.is-focused .contact-row[aria-selected="true"] .avatar:not(:has(img)) { background: rgba(255, 255, 255, 0.28); color: #fff; }
.contact-row:focus-visible { outline: var(--focus-ring); outline-offset: -1px; }
.contact-row-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* Several picked: their faces fanned, the count, and what can be done to all of them. */
@@ -712,7 +712,7 @@
.contact-many h2 { margin: 0; font-size: var(--t-17); }
/* "me" beside this person's own card, as Contacts marks it. */
.contact-me { margin-left: auto; color: var(--text-3); font-size: var(--t-11); }
-.contact-rows.is-focused .contact-row[aria-current="true"] .contact-me { color: var(--on-accent-2); }
+.contact-rows.is-focused .contact-row[aria-selected="true"] .contact-me { color: var(--on-accent-2); }
.avatar {
width: 26px;
@@ -1141,6 +1141,19 @@
/* A menu's highlight is the system's, whichever app it is in — as every Mac menu's is. */
.picker-menu li.is-active { background: var(--sys-blue-deep); color: #fff; }
.picker-menu li.is-active .picker-check { color: #fff; }
+/* A rule between groups of choices, as Reminders' Repeat menu sets Never and Custom apart. */
+.picker-menu li.has-divider { position: relative; margin-top: 11px; }
+.picker-menu li.is-disabled { color: var(--text-3); cursor: default; }
+.picker-menu li.has-divider::before {
+ content: "";
+ position: absolute;
+ top: -6px;
+ left: 8px;
+ right: 8px;
+ height: var(--hairline);
+ background: var(--separator);
+ pointer-events: none;
+}
.picker-check {
flex: none;
@@ -1214,7 +1227,7 @@
/* Kind, label, value, remove — the shape of one line of a card. */
.contact-method-rows li {
display: grid;
- grid-template-columns: 96px 112px minmax(0, 1fr) auto;
+ grid-template-columns: 112px 112px minmax(0, 1fr) auto;
gap: 6px;
align-items: center;
}
@@ -1228,7 +1241,7 @@
as it takes, then town, region and postcode side by side, then the country. */
.contact-address-rows { padding-top: 6px; border-top: var(--hairline) solid var(--separator); }
.contact-method-rows li.contact-address-edit {
- grid-template-columns: 96px 112px minmax(0, 1fr) auto;
+ grid-template-columns: 112px 112px minmax(0, 1fr) auto;
row-gap: 6px;
align-items: center;
}
@@ -1465,10 +1478,14 @@
.screen-failed { max-width: 46ch; margin: 64px auto 0; text-align: center; color: var(--text-2); }
.screen-failed p { margin: 0 0 12px; font-size: var(--t-13); }
-.contact-birthday-field { display: flex; align-items: flex-end; flex-wrap: wrap; gap: 6px 14px; margin: 10px 0; }
-.contact-birthday-field label:first-child { display: flex; flex-direction: column; gap: 4px; font-size: var(--t-11); color: var(--text-2); }
-.contact-birthday-field input[type="date"] { padding: 4px 8px; border: 1px solid var(--field-edge); border-radius: 6px; background: var(--field); color: var(--text); font: inherit; font-size: var(--t-13); color-scheme: light dark; }
-.contact-birthday-noyear { display: flex; align-items: center; gap: 6px; padding-bottom: 6px; font-size: var(--t-13); color: var(--text-2); }
+/* The birthday sits on a line of its own shape: its name where a kind goes, the date across
+ the label and value columns. */
+.contact-birthday-field {
+ display: grid;
+ grid-template-columns: 112px minmax(0, 1fr) auto;
+ gap: 6px;
+ align-items: center;
+}
/* File Info: a calm sheet, the mark large, the facts in two aligned columns. */
.info-sheet { width: min(400px, calc(100vw - 32px)); padding: 0 0 8px; }
@@ -1813,3 +1830,118 @@
.is-rail .sidebar-foot-stack .sidebar-account-name { display: none; }
.sidebar .status-line { padding: 4px 8px; font-size: var(--t-11); }
.drive-bar .drive-title { flex: 1 1 14ch; }
+
+/* Photos Cache: the cap as a ruler of the sizes offered — the native slider for the hand and the
+ keys, its stops named under it, each placed under the slider's own position for it. */
+.cap-ruler { --thumb: 18px; display: flex; flex-direction: column; gap: 2px; }
+.cap-ruler input[type="range"] { width: 100%; margin: 0; accent-color: var(--accent); cursor: pointer; }
+.cap-ruler-stops { position: relative; height: 16px; margin: 0 calc(var(--thumb) / 2); }
+.cap-ruler-stops button {
+ position: absolute; top: 0; transform: translateX(-50%);
+ padding: 0 2px; border: 0; background: none; cursor: pointer;
+ color: var(--text-2); font: inherit; font-size: var(--t-11); font-variant-numeric: tabular-nums; white-space: nowrap;
+}
+.cap-ruler-stops button.is-here { color: var(--text); font-weight: 600; }
+
+/* ── Contacts: every field, the photo, duplicates ─────────────────────────────────────────
+ The editor grows by what a card holds — a nickname or a job title appears only once it is
+ there or asked for — so the common card stays as short as it was. */
+.contact-form-head { display: flex; align-items: center; gap: 14px; }
+.contact-photo-edit {
+ position: relative; padding: 0; border: 0; background: none; border-radius: var(--r-pill);
+ cursor: pointer; flex: none;
+}
+.contact-photo-edit:focus-visible { outline: var(--focus-ring); outline-offset: 3px; }
+.contact-photo-badge {
+ position: absolute; right: -2px; bottom: -2px; width: 24px; height: 24px; display: grid;
+ place-items: center; border-radius: var(--r-pill); background: var(--bg); color: var(--text-2);
+ box-shadow: 0 0 0 var(--hairline) var(--separator), 0 1px 2px rgba(0, 0, 0, 0.12);
+}
+.contact-photo-edit:hover .contact-photo-badge { color: var(--text); }
+.contact-kind-fixed { font-size: var(--t-13); color: var(--text-2); padding-left: 8px; }
+
+.date-field { display: flex; gap: 6px; min-width: 0; }
+.date-field .date-field-month { flex: 1 1 auto; min-width: 0; }
+.contact-form .date-field-day { flex: none; width: 2.9em; }
+.contact-form .date-field-year { flex: none; width: 3.9em; }
+.contact-method-rows li .date-field { grid-column: 3; }
+/* In a narrow pane the value column is what gives way first, so the kind and label columns
+ narrow, and a date — three fields — takes the line under its label, as an address does. */
+.contact-form { container-type: inline-size; }
+@container (max-width: 440px) {
+ .contact-method-rows li,
+ .contact-method-rows li.contact-address-edit { grid-template-columns: 84px 104px minmax(0, 1fr) auto; }
+ .contact-birthday-field { grid-template-columns: 84px minmax(0, 1fr) auto; }
+ .contact-method-rows li .date-field { grid-column: 2 / 4; grid-row: 2; }
+ .contact-method-rows li > .quiet.danger { grid-column: 4; }
+ .contact-kind-fixed, .contact-address-kind { line-height: 1.2; }
+}
+
+.contact-phonetic { margin: 0; color: var(--text-3); font-size: var(--t-11); }
+.contact-nickname { margin: 0; color: var(--text-2); font-size: var(--t-13); }
+
+/* At the top of the list: a quiet line, not an alert. */
+.dupes-banner {
+ display: flex; align-items: center; gap: 10px; width: 100%; margin: 0 0 8px; padding: 8px 10px;
+ border: 0; border-radius: var(--r-field); background: var(--fill); color: var(--text);
+ font: inherit; text-align: left; cursor: pointer;
+}
+.dupes-banner:hover { background: color-mix(in srgb, var(--text) 9%, transparent); }
+.dupes-banner:focus-visible { outline: var(--focus-ring); outline-offset: 1px; }
+.dupes-banner > svg:first-child { flex: none; color: var(--text-2); }
+.dupes-banner-text { display: flex; flex-direction: column; min-width: 0; flex: 1; }
+.dupes-banner-title { font-size: var(--t-13); font-weight: 600; }
+.dupes-banner-sub { font-size: var(--t-11); color: var(--text-2); }
+.dupes-banner-go { flex: none; color: var(--text-3); }
+
+.dupes-head { display: flex; flex-direction: column; align-items: flex-start; gap: 6px; margin-bottom: 14px; }
+.dupes-head p { margin: 0 0 4px; color: var(--text-2); font-size: var(--t-13); max-width: 52ch; }
+.dupes-list { list-style: none; margin: 0; padding: 0; }
+.dupes-group {
+ display: grid; grid-template-columns: auto minmax(0, 1fr) auto; gap: 12px; align-items: center;
+ padding: 12px 0; border-top: var(--hairline) solid var(--separator);
+}
+.dupes-faces { display: flex; padding-left: 4px; }
+.dupes-faces .avatar { width: 32px; height: 32px; font-size: var(--t-11); }
+.dupes-faces .avatar + .avatar { margin-left: -8px; box-shadow: 0 0 0 2px var(--bg); }
+.dupes-who { display: flex; flex-direction: column; min-width: 0; gap: 1px; }
+.dupes-name { font-size: var(--t-15); font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.dupes-why { font-size: var(--t-12); color: var(--text-2); }
+.dupes-cards { display: flex; flex-wrap: wrap; gap: 2px 12px; margin-top: 2px; }
+.dupes-cards button {
+ padding: 0; border: 0; background: none; font: inherit; font-size: var(--t-12);
+ color: var(--accent-strong); cursor: pointer; text-align: left;
+}
+.dupes-cards button:hover { text-decoration: underline; }
+.dupes-done { display: flex; flex-direction: column; align-items: center; gap: 8px; padding-top: 64px; color: var(--text-2); }
+
+/* Choosing a photo: the picture moves under a fixed circle, nothing animates. */
+.photo-sheet { width: min(320px, 92vw); align-items: center; }
+.photo-sheet h2 { align-self: flex-start; }
+.photo-frame {
+ position: relative; overflow: hidden; border-radius: 12px; flex: none;
+ background: color-mix(in srgb, var(--text) 8%, transparent); touch-action: none; user-select: none;
+}
+.photo-frame.has-photo { cursor: grab; background: #000; }
+.photo-frame.has-photo:active { cursor: grabbing; }
+.photo-frame-image { position: absolute; left: 0; top: 0; max-width: none; transform-origin: 0 0; pointer-events: none; }
+.photo-frame-ring {
+ position: absolute; left: 50%; top: 50%; translate: -50% -50%; border-radius: 50%;
+ box-shadow: 0 0 0 999px rgba(0, 0, 0, 0.5); outline: 2px solid rgba(255, 255, 255, 0.9);
+ pointer-events: none;
+}
+.photo-frame-pick {
+ position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center;
+ justify-content: center; gap: 10px; padding: 24px; border: 0; background: none;
+ color: var(--text-2); font: inherit; font-size: var(--t-13); cursor: pointer;
+}
+.photo-frame-pick:hover { color: var(--text); }
+.photo-zoom { display: flex; align-items: center; gap: 10px; width: 100%; font-size: var(--t-12); color: var(--text-2); }
+.photo-zoom input { flex: 1; }
+.photo-problem { margin: 0; font-size: var(--t-12); color: var(--danger, #d70015); }
+.photo-sheet-actions { display: flex; align-items: center; gap: 8px; width: 100%; }
+.photo-sheet-gap { flex: 1; }
+
+/* What Skykeep talks to (Settings): each source a label over its hosts, the hosts as written. */
+.settings-reach .settings-row.is-stacked { gap: 2px; }
+.settings-reach code { font: inherit; color: var(--text); }
diff --git a/src/styles/calendar.css b/src/styles/calendar.css
index fd1db5c..9c706b8 100644
--- a/src/styles/calendar.css
+++ b/src/styles/calendar.css
@@ -284,6 +284,11 @@
.cx-items.is-dots .cx-item-title,
.cx-items.is-dots .cx-item-time,
.cx-items.is-dots .cx-more { display: none; }
+/* A cell too short for a row of dots: small marks only — seen, not pressed — and the day is
+ the target. Hidden from the keyboard and screen readers there (the day names its events). */
+.cx-items.is-tiny { pointer-events: none; gap: 2px; padding: 2px 3px; }
+.cx-items.is-tiny .cx-item { width: 6px; height: 6px; min-height: 0; }
+.cx-items.is-tiny .cx-item .cx-dot, .cx-items.is-tiny .cx-ring { width: 6px; height: 6px; margin: 0; }
.cx-item.is-reminder.is-done .cx-item-title { color: var(--text-3); text-decoration: line-through; }
.cx-more {
height: 24px;
@@ -473,7 +478,9 @@
gap: 5px;
height: 18px;
font-size: var(--t-11);
- overflow: hidden;
+ /* Not clipped: the ring's 24px target reaches past the 18px line, and clipping it cut the
+ edges off what a click lands on. The title ends itself in an ellipsis instead. */
+ overflow: visible;
white-space: nowrap;
pointer-events: none;
}
@@ -859,4 +866,43 @@
.cx-pop-link:focus-visible { outline: var(--focus-ring); }
.cx-info-place { display: flex; flex-wrap: wrap; align-items: baseline; gap: 2px 8px; }
.cx-maps { color: var(--sys-blue); font-size: var(--t-11); text-decoration: none; }
+/* Join: the one action an event with a call asks for, as Calendar puts it — a filled pill
+ under the title, the call's service named, the link itself in the tooltip. */
+.cx-join {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ align-self: flex-start;
+ margin: 2px 0 6px;
+ padding: 4px 12px;
+ border-radius: 999px;
+ /* A deep green: white reads on it at 5:1, where Apple's bright green gives 2.2:1. */
+ background: #1f8034;
+ color: #fff;
+ font-size: var(--t-12);
+ font-weight: 600;
+ text-decoration: none;
+}
+.cx-join:hover { filter: brightness(1.06); }
+.cx-join:focus-visible { outline: none; box-shadow: var(--focus-ring); }
+@media (forced-colors: active) { .cx-join { border: 1px solid ButtonText; } }
+/* Guests, as Calendar lists them under an event: a count, then one quiet line each — the
+ answer as a small mark and a word, the organizer and you named as such. */
+.cx-guests { margin: 6px 0 4px; }
+.cx-guests-head { margin: 0 0 4px; font-size: var(--t-11); font-weight: 600; color: var(--text-2); }
+.cx-guest-list { margin: 0; padding: 0; list-style: none; display: grid; gap: 3px; max-height: 168px; overflow-y: auto; }
+.cx-guest { display: grid; grid-template-columns: 16px minmax(0, 1fr) auto; align-items: center; gap: 8px; font-size: var(--t-12); }
+.cx-guest-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text); }
+.cx-guest-role { color: var(--text-2); }
+.cx-guest-answer { color: var(--text-2); font-size: var(--t-11); }
+.cx-guest-mark {
+ width: 16px; height: 16px; border-radius: 50%;
+ display: grid; place-items: center;
+ font-size: 10px; font-weight: 700; line-height: 1; color: #fff;
+ box-shadow: inset 0 0 0 var(--hairline) color-mix(in srgb, var(--text) 25%, transparent);
+}
+.cx-guest-mark.is-accepted { background: #1f8034; box-shadow: none; }
+.cx-guest-mark.is-declined { background: #c62828; box-shadow: none; }
+.cx-guest-mark.is-tentative { background: #a35b00; box-shadow: none; }
+@media (forced-colors: active) { .cx-guest-mark { border: 1px solid CanvasText; } }
.cx-maps:hover { text-decoration: underline; }
diff --git a/src/styles/kit.css b/src/styles/kit.css
index e23a61c..a6b687e 100644
--- a/src/styles/kit.css
+++ b/src/styles/kit.css
@@ -481,6 +481,31 @@ textarea.field { padding-block: 5px; resize: vertical; }
.confirm-actions.is-stacked { grid-template-columns: 1fr; }
.confirm-actions > button { width: 100%; }
+/* Keyboard Shortcuts (Ctrl+/): the apps in two columns where there is room, each a quiet
+ heading over its rows — the action, then its keys as small caps of the system's keycaps. */
+.shortcuts-sheet { width: min(760px, 94vw); max-height: min(640px, 88vh); }
+.shortcuts-groups {
+ min-height: 0; overflow-y: auto; margin: 0 -22px; padding: 2px 22px 4px;
+ columns: 2 300px; column-gap: 32px;
+}
+.shortcuts-groups:focus-visible { outline: var(--focus-ring); outline-offset: -2px; }
+.shortcuts-groups section { break-inside: avoid; padding-bottom: 14px; }
+.shortcuts-groups h3 { margin: 0 0 4px; font-size: var(--t-13); font-weight: 700; color: var(--text); }
+.shortcuts-groups dl { margin: 0; }
+.shortcuts-row {
+ display: flex; align-items: baseline; justify-content: space-between; gap: 12px;
+ padding: 4px 0; border-top: var(--hairline) solid var(--separator); font-size: var(--t-13);
+}
+.shortcuts-row:first-child { border-top: 0; }
+.shortcuts-row dt { color: var(--text-2); min-width: 0; }
+.shortcuts-row dd { margin: 0; display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 6px; flex: none; }
+.shortcuts-combo { display: inline-flex; gap: 2px; }
+.shortcuts-combo kbd {
+ min-width: 20px; padding: 1px 5px; border-radius: 5px; text-align: center;
+ font: inherit; font-size: var(--t-11); font-weight: 600; color: var(--text);
+ background: var(--fill); box-shadow: inset 0 calc(-1 * var(--hairline)) 0 var(--separator);
+}
+
/* ---- small controls ---------------------------------------------------------------------- */
/* A segmented control: one recessed track, a raised cap over the chosen segment. */
diff --git a/src/styles/notes.css b/src/styles/notes.css
index 74eff7b..b2b89fb 100644
--- a/src/styles/notes.css
+++ b/src/styles/notes.css
@@ -73,17 +73,17 @@
cursor: default;
}
/* Rows are separated by a hairline that stops short of the selected row, as in Notes. */
-[role="listitem"] + [role="listitem"] > .note-row:not([aria-current="true"]) {
+.note-item + .note-item > .note-row:not([aria-selected="true"]) {
box-shadow: inset 0 1px 0 var(--separator);
border-radius: 0 0 8px 8px;
}
.note-row:hover { background: color-mix(in srgb, var(--text) 5%, transparent); }
/* The selection as macOS draws it: the accent, text in white, while the list has focus;
a quiet grey once focus is elsewhere — in the note being written, say. */
-.note-row[aria-current="true"] { background: color-mix(in srgb, var(--text) 11%, transparent); box-shadow: none; }
-.note-rows:focus-within .note-row[aria-current="true"] { background: var(--accent); color: var(--on-accent); }
-.note-rows:focus-within .note-row[aria-current="true"] .note-row-when,
-.note-rows:focus-within .note-row[aria-current="true"] .note-row-snippet { color: var(--on-accent-2); }
+.note-row[aria-selected="true"] { background: color-mix(in srgb, var(--text) 11%, transparent); box-shadow: none; }
+.note-rows:focus-within .note-row[aria-selected="true"] { background: var(--accent); color: var(--on-accent); }
+.note-rows:focus-within .note-row[aria-selected="true"] .note-row-when,
+.note-rows:focus-within .note-row[aria-selected="true"] .note-row-snippet { color: var(--on-accent-2); }
.note-row:focus-visible { outline: var(--focus-ring); outline-offset: -1px; }
.note-row-title {
display: flex;
@@ -96,7 +96,7 @@
.note-row-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* A locked note keeps its title in the list, as Notes shows it, with a small lock before it. */
.note-row-lock { flex: none; color: var(--text-2); }
-.note-rows:focus-within .note-row[aria-current="true"] .note-row-lock { color: var(--on-accent); }
+.note-rows:focus-within .note-row[aria-selected="true"] .note-row-lock { color: var(--on-accent); }
.note-row-meta { display: flex; gap: 8px; min-width: 0; font-size: var(--t-11); }
.note-row-when { flex: none; color: var(--text); font-variant-numeric: tabular-nums; }
.note-row-snippet { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-3); }
@@ -366,9 +366,13 @@ textarea.note-title::placeholder { color: var(--text-3); }
display: block; padding: 3px; margin: 8px -3px; border-radius: 0; background: none;
color: inherit; font-size: inherit; overflow-x: auto; overflow-y: hidden;
}
+/* The frame is an inset shadow, not a border. At a fractional scale (1.25×) the note's column
+ starts between two device pixels, and WebKit drew a bordered table's left edge not at all and
+ its right edge two pixels wide, soft. The shadow is drawn the same weight on both sides at
+ every scale, as each line between the cells is. */
.nf-table {
width: 100%; table-layout: fixed; border-collapse: separate; border-spacing: 0;
- border: var(--hairline) solid var(--table-line); border-radius: 8px; overflow: hidden;
+ border: 0; box-shadow: inset 0 0 0 var(--hairline) var(--table-line); border-radius: 8px; overflow: hidden;
}
.nf-table td {
min-width: 96px; padding: 8px 10px; height: 2.6em; line-height: 1.4;
@@ -457,9 +461,12 @@ textarea.note-title::placeholder { color: var(--text-3); }
/* A table chosen whole: its own frame takes the accent, as the phone rings a chosen table —
drawn on the frame itself, so the scroll box round it can never cut it to one edge. */
.note-rich .nf-attachment.is-table.ProseMirror-selectednode > .nf-table {
- border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent);
+ box-shadow: inset 0 0 0 var(--hairline) var(--accent), 0 0 0 1px var(--accent);
}
.nf-file-meta.is-trouble { color: var(--danger); white-space: normal; }
+/* Opening: answered at once, dimmed in place (no motion), until the other app has it. */
+.nf-attachment.is-opening .nf-file,
+.nf-attachment.is-opening .nf-doc { opacity: 0.6; cursor: progress; }
/* A table not readable here yet: a quiet dashed frame where the grid will be. */
.nf-table-unread {
@@ -468,8 +475,15 @@ textarea.note-title::placeholder { color: var(--text-3); }
}
.notes-folder-rename { width: 100%; }
-/* An attachment not yet known takes no room and says nothing until it is drawn. */
-.note-rich .nf-attachment.is-pending { padding: 0; margin: 0; background: none; }
+/* An attachment not yet known: a quiet frame holding its place, no words, no motion — never
+ a blank gap that later jumps open. */
+.note-rich .nf-attachment.is-pending {
+ display: inline-block; vertical-align: top; width: min(100%, 220px); height: 46px; padding: 0; margin: 2px 0;
+ border-radius: 12px; background: color-mix(in srgb, var(--text) 5%, transparent);
+}
+.note-rich .nf-attachment.is-anon { padding: 0; margin: 0; background: none; }
+/* One that could not be looked up even after asking again: a card that still opens it. */
+.note-rich .nf-attachment.is-unknown .nf-file-glyph { background: color-mix(in srgb, var(--text) 30%, transparent); }
/* ---- a locked note ------------------------------------------------------------------
Calm, as Notes shows one: a lock, one line, the password and Unlock, centred a little above
@@ -517,3 +531,38 @@ textarea.note-title::placeholder { color: var(--text-3); }
to "Septe…"; the list beside it says when, too. "Saving…" and "Waiting to sync" always show. */
.note-body { container-type: inline-size; }
@container (max-width: 460px) { .note-bar:has(.note-bar-actions) .note-when.is-date { visibility: hidden; } }
+
+/* A file on its way into the note: a card over the note while it uploads, the picture already
+ there, so adding never looks stuck. The note — text and toolbar — waits under a clear cover
+ pinned to the note's panel (the text scrolls; the panel does not), so nothing typed or done
+ in those seconds is lost when it comes back from Apple. No motion: it appears and goes. */
+.note-body { position: relative; }
+.note-adding {
+ position: absolute;
+ inset: 0;
+ z-index: 5;
+ display: flex;
+ align-items: flex-end;
+ justify-content: center;
+ padding: 24px;
+ cursor: progress;
+}
+.note-adding-card {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ max-width: min(420px, 100%);
+ padding: 12px 14px;
+ border-radius: 12px;
+ background: var(--bg);
+ box-shadow: 0 0 0 var(--hairline) color-mix(in srgb, var(--text) 14%, transparent), 0 8px 24px rgba(0, 0, 0, 0.18);
+}
+.note-adding-file { display: grid; grid-template-columns: 48px minmax(0, 1fr); align-items: center; gap: 10px; }
+.note-adding-thumb {
+ width: 48px; height: 48px; border-radius: 8px; object-fit: cover;
+ background: color-mix(in srgb, var(--text) 6%, transparent);
+ box-shadow: 0 0 0 var(--hairline) color-mix(in srgb, var(--text) 12%, transparent);
+}
+.note-adding-thumb.is-file { display: grid; place-items: center; color: var(--text-2); }
+.note-adding-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--t-13); color: var(--text); }
+.note-adding-state { display: flex; align-items: center; gap: 8px; font-size: var(--t-11); color: var(--text-2); }
diff --git a/src/styles/photos.css b/src/styles/photos.css
index 870e9d6..61ab561 100644
--- a/src/styles/photos.css
+++ b/src/styles/photos.css
@@ -102,7 +102,15 @@
selection's "3 Photos Selected") no longer has the engine lay out every built month again
to find out. A click that selects went from ~80 ms of work to ~20 in WebKit. */
contain: strict;
-}
+ /* Never moved by the engine to follow a box: every month is as tall unbuilt as built, so
+ nothing above the view changes height. With anchoring on, WebKit followed the block below a
+ month's built rows as rows were built over it, and the view slid down a few rows a frame —
+ a jump landed months away, and the top of the grid slid up under the header. */
+ overflow-anchor: none;
+}
+/* Its scrollbar starts under the header: drawn under it, the bar's thumb was hidden exactly
+ when the grid was at the top. */
+.px-scroll::-webkit-scrollbar-track { margin-top: calc(var(--bar, 68px) + 4px); }
/* The rectangle swept out to select (see sweepStart): drawn by paint where it lies, never moved
as a layer. */
.px-sweep {
@@ -344,7 +352,7 @@
box-shadow: none;
}
.px-video img { max-width: 100%; max-height: calc(100vh - 120px); object-fit: contain; }
-.px-video video { display: block; background-color: #000; background-size: 100% 100%; outline: none; }
+.px-video video { display: block; background-size: 100% 100%; outline: none; }
.px-play {
position: absolute;
display: grid;
@@ -356,6 +364,23 @@
color: #fff;
}
.px-video:hover .px-play { background: rgba(0, 0, 0, 0.65); }
+.px-video-hold { position: relative; display: grid; place-items: center; max-width: 100%; max-height: 100%; }
+.px-video-note {
+ position: absolute;
+ left: 50%;
+ bottom: 16px;
+ translate: -50% 0;
+ max-width: min(440px, calc(100% - 32px));
+ margin: 0;
+ padding: 8px 14px;
+ border-radius: 12px;
+ background: rgba(28, 28, 30, 0.78);
+ color: rgba(255, 255, 255, 0.92);
+ font-size: var(--t-12, 12px);
+ line-height: 1.4;
+ text-align: center;
+ pointer-events: none;
+}
/* What is dragged: the photo, with how many when it is more than one. */
.px-ghost { position: fixed; top: -200px; left: -200px; width: 72px; height: 72px; }
@@ -380,15 +405,18 @@
.px-slide {
position: absolute;
inset: 0;
- width: 100%;
- height: 100%;
- object-fit: contain;
- /* No CSS animation: the arriving photo fades in over the leaving one frame by frame from the
- page (fadeIn), the leaving one still beneath it. The slow zoom across each photo was a
- long compositor animation on a full-screen picture — the kind that glitched on his screen. */
+ /* No CSS animation: the arriving layer's opacity is set by the page frame by frame
+ (Slideshow.tsx), the leaving one whole beneath it. The two layers are made once and take
+ turns; never torn down, so neither paints an empty frame. */
z-index: 1;
+ pointer-events: none;
}
-.px-slide.is-leaving { z-index: 0; pointer-events: none; }
+.px-slide > img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; }
+.px-slide > img:not([src]) { visibility: hidden; }
+/* A video's film, in its picture's own box, drawn over its picture once a frame is here. */
+.px-slide-film { position: absolute; overflow: hidden; }
+.px-slide-film[hidden] { display: none; }
+.px-slide-film > video { display: block; width: 100%; height: 100%; object-fit: contain; background: transparent; }
.px-show-bar {
position: absolute;
z-index: 2;
@@ -593,6 +621,8 @@
opacity: 0.82;
}
.px-slip:hover { opacity: 1; }
+/* A slip whose photo is still on its way: its place, nothing to press. */
+.px-slip.is-waiting { pointer-events: none; }
.px-slip img { width: 100%; height: 100%; object-fit: cover; display: block; }
.px-slip.is-shown { width: 54px; top: 0; height: 44px; opacity: 1; }
/* The shown one's frame drawn inside it, over the picture: drawn outside, the strip's own edge
@@ -689,10 +719,31 @@
/* ---- a video, as Photos plays one: the film alone, its controls in a capsule floating over
its foot that fades while the pointer rests (always there while paused) ----------------- */
-.px-player { position: relative; display: block; overflow: hidden; max-width: none; max-height: none; background: #000 center / 100% 100% no-repeat; }
-.px-player > video { display: block; width: 100%; height: 100%; object-fit: contain; outline: none; }
+.px-player { position: relative; display: block; overflow: hidden; max-width: none; max-height: none; background: transparent center / 100% 100% no-repeat; }
+.px-player > video { position: relative; z-index: 1; display: block; width: 100%; height: 100%; object-fit: contain; outline: none; background: transparent; }
+/* The video's own picture under the film until a frame of it is on screen. */
+.px-player-poster { position: absolute; inset: 0; z-index: 0; width: 100%; height: 100%; object-fit: contain; pointer-events: none; }
+/* Waiting on the network: a small ring, never a black box. */
+.px-player-wait {
+ position: absolute;
+ z-index: 2;
+ left: 50%;
+ top: 50%;
+ width: 28px;
+ height: 28px;
+ margin: -14px 0 0 -14px;
+ border-radius: 50%;
+ border: 2.5px solid rgba(255, 255, 255, 0.28);
+ border-top-color: #fff;
+ box-shadow: 0 0 12px rgba(0, 0, 0, 0.35);
+ animation: px-spin 0.9s linear infinite;
+ pointer-events: none;
+}
+@keyframes px-spin { to { rotate: 360deg; } }
+@media (prefers-reduced-motion: reduce) { .px-player-wait { animation: none; } }
.px-player-bar {
position: absolute;
+ z-index: 3;
left: 50%;
bottom: 14px;
width: min(560px, calc(100% - 28px));
@@ -801,7 +852,8 @@
background: var(--accent);
}
/* A Live Photo's moving part, exactly over its still. */
-.px-live { position: absolute; inset: 0; width: 100%; height: 100%; max-width: none; max-height: none; object-fit: contain; pointer-events: none; }
+.px-live-frame { position: absolute; inset: 0; overflow: hidden; pointer-events: none; }
+.px-live { position: absolute; inset: 0; width: 100%; height: 100%; max-width: none; max-height: none; object-fit: contain; pointer-events: none; background: transparent; }
/* ---- going to a month: the years down the side, a year's months as tiles with a photo -- */
.px-jump {
diff --git a/src/styles/reminders.css b/src/styles/reminders.css
index d2f34f4..5b65aa7 100644
--- a/src/styles/reminders.css
+++ b/src/styles/reminders.css
@@ -367,15 +367,34 @@ button.rx-tag:hover { background: color-mix(in srgb, var(--text) 12%, transparen
}
.rx-field {
display: grid;
- grid-template-columns: 76px minmax(0, 1fr);
+ grid-template-columns: 96px minmax(0, 1fr);
gap: 10px;
align-items: center;
min-height: 28px;
}
.rx-field > span:first-child { color: var(--text-2); font-size: var(--t-11); }
.rx-field-notes { align-items: start; }
+/* The link: typed in the field, opened with Open beside it — as the phone's link is tapped. */
+.rx-field-url { grid-template-columns: 96px minmax(0, 1fr) auto; }
+.rx-url-open { font-size: var(--t-12); color: var(--accent, var(--sys-blue)); text-decoration: none; }
+.rx-url-open:hover { text-decoration: underline; }
.rx-field-notes > span:first-child { padding-top: 6px; }
.rx-field textarea.field { resize: vertical; min-height: 44px; }
+/* A reminder's pictures, as the phone lists them: a row of even squares, each cropped to fill
+ its tile with a hairline edge so a white picture still reads as one. */
+.rx-images {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(72px, 1fr));
+ gap: 8px;
+}
+.rx-image {
+ width: 100%;
+ aspect-ratio: 1;
+ object-fit: cover;
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--text) 6%, transparent);
+ box-shadow: 0 0 0 var(--hairline) color-mix(in srgb, var(--text) 12%, transparent);
+}
/* A value read from Apple, not a control: the panel's type, quietly. */
.rx-value { color: var(--text); font-size: var(--t-13); }
.rx-url {
@@ -391,7 +410,46 @@ button.rx-tag:hover { background: color-mix(in srgb, var(--text) 12%, transparen
/* Between the panel's groups — what it says, when it is due, how it is filed — as Apple
separates them in its info popover. */
.rx-detail-rule { height: var(--hairline); margin: 2px 0; background: var(--separator); }
-.rx-hint { margin: -4px 0 0 86px; color: var(--text-3); font-size: var(--t-11); }
+.rx-hint { margin: -4px 0 0 106px; color: var(--text-3); font-size: var(--t-11); line-height: 1.35; }
+/* A second, quieter part of a value: the offset beside a zone, Arriving beside a place. */
+.rx-quiet { margin-left: 8px; color: var(--text-3); }
+
+/* Custom repeat: set in from the Repeat row, as the phone opens it as a page of its own. */
+.rx-custom { display: flex; flex-direction: column; gap: 8px; padding-left: 12px; border-left: 2px solid var(--separator); }
+.rx-custom .rx-hint { margin-left: 106px; }
+.rx-every { display: inline-flex; align-items: center; gap: 6px; }
+.rx-field .rx-every .rx-every-count { width: 4.5ch; text-align: center; padding-left: 4px; padding-right: 4px; }
+.rx-every-unit { color: var(--text-2); font-size: var(--t-13); }
+.rx-step {
+ display: grid;
+ place-items: center;
+ width: 24px;
+ height: 24px;
+ padding: 0;
+ border: 0;
+ border-radius: 7px;
+ background: color-mix(in srgb, var(--text) 8%, transparent);
+ color: var(--text);
+ font: inherit;
+ font-size: var(--t-13);
+ line-height: 1;
+}
+.rx-step:disabled { color: var(--text-3); }
+.rx-step:focus-visible { outline: var(--focus-ring); }
+/* The days a rule falls on, shown as the phone's grid shows them; the one it falls on filled. */
+.rx-days { display: grid; grid-template-columns: repeat(7, 28px); gap: 4px; margin-left: 106px; }
+.rx-custom .rx-days { margin-left: 106px; }
+.rx-days.is-year { grid-template-columns: repeat(6, 40px); }
+.rx-day {
+ display: grid;
+ place-items: center;
+ height: 24px;
+ border-radius: 6px;
+ color: var(--text-3);
+ font-size: var(--t-11);
+ font-variant-numeric: tabular-nums;
+}
+.rx-day.is-on { background: var(--sys-blue); color: #fff; font-weight: 600; }
.rx-tag-field { display: flex; flex-wrap: wrap; align-items: center; gap: 5px; min-width: 0; }
.rx-tag.is-chip { padding: 0; height: 22px; background: color-mix(in srgb, var(--sys-blue) 12%, transparent); }
.rx-tag-name,
@@ -434,6 +492,28 @@ button.rx-tag:hover { background: color-mix(in srgb, var(--text) 12%, transparen
}
.rx-add input::placeholder { color: var(--text-3); }
.rx-add-target { max-width: 160px; }
+/* What the line says beyond its title, under it before Return: quiet, on the text's column. */
+.rx-add-understood {
+ grid-column: 2 / -1;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ margin-top: 4px;
+ font-size: var(--t-11);
+ color: var(--accent, var(--sys-blue));
+}
+.rx-add-reading { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.rx-add-literal {
+ flex: none;
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--text-2);
+ font: inherit;
+ cursor: pointer;
+}
+.rx-add-literal:hover { color: var(--text); }
+.rx-add-literal:focus-visible { outline: none; box-shadow: var(--focus-ring); border-radius: 4px; }
.rx-add-target .picker-button { font-size: var(--t-11); padding: 3px 8px; }
/* One column at a time, as on iPhone: the lists, or the list picked from them. Searching
@@ -473,3 +553,34 @@ button.rx-tag:hover { background: color-mix(in srgb, var(--text) 12%, transparen
.rx-row[draggable="true"] { cursor: grab; }
.rx-row.is-dragging { opacity: 0.45; }
.rx-row.is-drop-before { box-shadow: inset 0 2px 0 var(--sys-blue, #0a84ff); }
+
+/* A row's marks, as the phone's list shows them: another zone's clock beside the time, the
+ Urgent alarm, and chips for a place, a person and a link. */
+.rx-urgent { display: inline-flex; align-items: center; color: var(--text-2); }
+.rx-chips { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; }
+.rx-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ min-width: 0;
+ max-width: 100%;
+ height: 24px;
+ padding: 0 10px 0 8px;
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--text) 7%, transparent);
+ color: var(--text);
+ font-size: var(--t-11);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ text-decoration: none;
+}
+.rx-chip b { font-weight: 600; }
+.rx-chip svg { flex: none; color: var(--text-2); }
+.rx-chip .rx-chip-place { color: var(--sys-red); }
+.rx-chip-link:hover { background: color-mix(in srgb, var(--text) 11%, transparent); }
+/* Custom's weekday picks: the same grid, each a toggle. */
+.rx-day.is-pick { padding: 0; border: 0; background: color-mix(in srgb, var(--text) 6%, transparent); font: inherit; font-size: var(--t-11); cursor: default; }
+.rx-day.is-pick.is-on { background: var(--sys-blue); color: #fff; }
+.rx-day.is-pick:focus-visible { outline: var(--focus-ring); }
+.rx-day.is-pick:disabled { opacity: 0.6; }