Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
Photos: deletes that land at once, 60 fps drawing, videos in the window
Yashwanth Kamireddi60485ca54df9
diff --git a/.uiverify/clip.webm b/.uiverify/clip.webmnew file mode 100644index 0000000..38958ebBinary files /dev/null and b/.uiverify/clip.webm differdiff --git a/.uiverify/photos-albums.mjs b/.uiverify/photos-albums.mjsindex 7e0c17b..909f854 100644--- a/.uiverify/photos-albums.mjs+++ b/.uiverify/photos-albums.mjs@@ -9,7 +9,9 @@ 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; });-page.on("dialog", (d) => void d.accept());+// Every question agreed to, as soon as it is asked.+await page.addInitScript(() => addEventListener("DOMContentLoaded", () =>+ new MutationObserver(() => document.querySelector(".px-ask .is-act")?.click()).observe(document.body, { childList: true, subtree: true })));await page.goto("http://localhost:4173", { waitUntil: "networkidle" });await openScreen(page, "Photos");await page.waitForTimeout(400);@@ -25,7 +27,8 @@ ok((await page.locator(".px-albums-head h1").innerText()) === "Albums" && (await"Albums opens the Albums page");ok((await page.locator(".px-card").count()) === 1 && /Trips[\s\S]*2 items/.test(await page.locator(".px-card").innerText()),`each album a card with its name and count ${JSON.stringify(await page.locator(".px-card").innerText())}`);-ok((await page.locator(".px-tile").count()) === 0, "and the photos give way to it");+// The grid stays built underneath (back is instant) but none of it shows.+ok((await page.locator(".px-tile").evaluateAll((els) => els.filter((e) => e.getClientRects().length > 0).length)) === 0, "and the photos give way to it");await page.getByRole("button", { name: "Hide Albums" }).click();ok((await page.locator(".px-albums .px-source").count()) === 0 && (await page.locator(".px-card").count()) === 1, "the chevron only folds the list away");await page.getByRole("button", { name: "Show Albums" }).click();diff --git a/.uiverify/photos-keys.mjs b/.uiverify/photos-keys.mjsindex c33f261..aec9cf4 100644--- a/.uiverify/photos-keys.mjs+++ b/.uiverify/photos-keys.mjs@@ -7,7 +7,9 @@ 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; });-page.on("dialog", (d) => void d.accept());+// Every question agreed to, as soon as it is asked.+await page.addInitScript(() => addEventListener("DOMContentLoaded", () =>+ new MutationObserver(() => document.querySelector(".px-ask .is-act")?.click()).observe(document.body, { childList: true, subtree: true })));await page.goto("http://localhost:4173", { waitUntil: "networkidle" });await openScreen(page, "Photos");await page.waitForTimeout(400);@@ -32,11 +34,11 @@ await page.keyboard.press("i");await page.waitForTimeout(600);ok((await page.locator(".px-viewer").count()) === 1 && (await page.locator(".px-info").count()) === 1, "I opens the photo with its details");await page.keyboard.press("z");-await page.waitForTimeout(150);+await page.waitForTimeout(400); // the zoom glidesconst k = await page.locator(".px-pan").evaluate((el) => new DOMMatrix(getComputedStyle(el).transform).a);ok(k > 2, `Z zooms in ×${k.toFixed(2)}`);await page.keyboard.press("z");-await page.waitForTimeout(150);+await page.waitForTimeout(400); // the zoom glidesok((await page.locator(".px-pan").evaluate((el) => new DOMMatrix(getComputedStyle(el).transform).a)) === 1, "and Z again fits it");await page.keyboard.press("Control+.");await page.waitForTimeout(650);diff --git a/.uiverify/photos-resize.mjs b/.uiverify/photos-resize.mjsnew file mode 100644index 0000000..46d844e--- /dev/null+++ b/.uiverify/photos-resize.mjs@@ -0,0 +1,40 @@+// A photo keeps its exact shape and fills the stage at every window size: as large as fits+// (never past 1.5× its pixels), centred, laid out by the engine as the window is resized —+// small, large, tall, wide — with no stretched or cut picture.+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";+const b = await engine.launch();+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });+const page = await ctx.newPage();+page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });+await openScreen(page, "Photos");+await page.waitForTimeout(400);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };++await page.locator(".px-tile").nth(0).dblclick(); // 4032 × 3024+await page.waitForTimeout(700);+const measure = () => page.evaluate(() => {+ const st = document.querySelector(".px-stage");+ const img = document.querySelector(".px-stage .px-shown");+ const cs = getComputedStyle(st);+ const s = st.getBoundingClientRect();+ const box = { l: s.left + parseFloat(cs.paddingLeft), t: s.top + parseFloat(cs.paddingTop), r: s.right - parseFloat(cs.paddingRight), b: s.bottom - parseFloat(cs.paddingBottom) };+ const r = img.getBoundingClientRect();+ return { box, r: { l: r.left, t: r.top, r: r.right, b: r.bottom, w: r.width, h: r.height } };+});+for (const [w, h] of [[1280, 800], [640, 520], [1920, 1040], [700, 1000], [1500, 600]]) {+ await page.setViewportSize({ width: w, height: h });+ await page.waitForTimeout(150);+ const { box, r } = await measure();+ const bw = box.r - box.l, bh = box.b - box.t;+ const shape = Math.abs(r.w / r.h - 4032 / 3024) < 0.01;+ const inside = r.l >= box.l - 1 && r.t >= box.t - 1 && r.r <= box.r + 1 && r.b <= box.b + 1;+ const fills = Math.abs(r.w - bw) < 1.5 || Math.abs(r.h - bh) < 1.5;+ const centred = Math.abs((r.l + r.r) / 2 - (box.l + box.r) / 2) < 1.5 && Math.abs((r.t + r.b) / 2 - (box.t + box.b) / 2) < 1.5;+ ok(shape && inside && fills && centred, `${w}×${h}: its own shape, inside the stage, filling it, centred (${r.w.toFixed(0)}×${r.h.toFixed(0)} in ${bw.toFixed(0)}×${bh.toFixed(0)})`);+}+await b.close();+process.exitCode = failures ? 1 : (process.exitCode ?? 0);diff --git a/.uiverify/photos-underlay.mjs b/.uiverify/photos-underlay.mjsnew file mode 100644index 0000000..658f38f--- /dev/null+++ b/.uiverify/photos-underlay.mjs@@ -0,0 +1,32 @@+// Never a black stage: the viewer paints the grid's thumbnail under every picture (photo or+// video still) until the sharper one is decoded; and a month once built stays built.+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";+const b = await engine.launch();+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });+const page = await ctx.newPage();+page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });+await openScreen(page, "Photos");+await page.waitForTimeout(400);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };++const lazy = await page.locator(".px-tile img[loading=lazy]").count();+ok(lazy === 0, `tile thumbnails are fetched with their month, not on the engine's lazy margin (${lazy} lazy)`);+await page.locator(".px-tile").nth(0).dblclick();+await page.waitForTimeout(500);+const bg = await page.locator(".px-stage .px-shown").evaluate((el) => getComputedStyle(el).backgroundImage);+ok(/thumb/.test(decodeURIComponent(bg)), `the shown picture has its thumbnail under it ${bg.slice(0, 80)}`);+const tiles = await page.locator(".px-tile").count();+await page.keyboard.press("Escape");+await page.waitForTimeout(500);+await page.locator(".px-scroll").evaluate((el) => (el.scrollTop = el.scrollHeight));+await page.waitForTimeout(300);+await page.locator(".px-scroll").evaluate((el) => (el.scrollTop = 0));+await page.waitForTimeout(300);+const after = await page.locator(".px-tile").count();+ok(after >= tiles, `months built stay built after scrolling away and back (${tiles} → ${after})`);+await b.close();+process.exitCode = failures ? 1 : (process.exitCode ?? 0);diff --git a/.uiverify/photos-video.mjs b/.uiverify/photos-video.mjsnew file mode 100644index 0000000..ac612ad--- /dev/null+++ b/.uiverify/photos-video.mjs@@ -0,0 +1,73 @@+// A video plays in the viewer itself, as Photos plays one: fetched from the app's loopback+// server in ranges, its controls the player's own, seeking anywhere. One this engine cannot+// play gives way to a still whose Play opens the system's player.+import http from "node:http";+import fs from "node:fs";+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";+const clip = new URL("./clip.webm", import.meta.url);+const len = fs.statSync(clip).size;+const asked = [];+const server = http.createServer((req, res) => {+ asked.push(req.url);+ if (!req.url.startsWith("/s3cret/p3/")) return void res.writeHead(404).end();+ const m = /bytes=(\d*)-(\d*)/.exec(req.headers.range ?? "");+ const first = m && m[1] ? +m[1] : 0;+ const last = 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": last - first + 1, "Content-Range": `bytes ${first}-${last}/${len}` });+ fs.createReadStream(clip, { start: first, end: last }).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 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) => { window.__videoBase = v; }, base);+const page = await ctx.newPage();+page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });+await openScreen(page, "Photos");+await page.waitForTimeout(400);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };++await page.locator('.px-tile[data-id="p3"]').dblclick();+await page.waitForTimeout(600);+const video = page.locator(".px-stage video");+ok((await video.count()) === 1 && (await video.getAttribute("src")) === `${base}/p3/original`, `the video is in the viewer, from the loopback server ${await video.getAttribute("src").catch(() => "")}`);+ok(await video.evaluate((v) => v.controls && v.autoplay), "with the player's own controls, playing at once");+const played = await video.evaluate((v) => new Promise((r) => {+ v.muted = true;+ void v.play().catch(() => undefined);+ const t0 = performance.now();+ const tick = () => (v.currentTime > 0.5 || v.error || performance.now() - t0 > 5000 ? r({ t: v.currentTime, err: v.error?.code ?? null }) : setTimeout(tick, 100));+ tick();+}));+if (played.err) {+ // This engine has no decoder for it: the still and the system's player take its place.+ await page.waitForTimeout(200);+ ok((await page.locator(".px-stage button.px-video").count()) === 1, `an engine that cannot play it falls back to the system's player (error ${played.err})`);+} else {+ ok(played.t > 0.5, `it plays (at ${played.t.toFixed(2)}s)`);+ const sought = await video.evaluate((v) => new Promise((r) => { v.onseeked = () => r(v.currentTime); v.currentTime = 4; }));+ ok(Math.abs(sought - 4) < 0.5, `and seeks (to ${sought.toFixed(2)}s)`);+ ok(asked.some((u) => u.startsWith("/s3cret/p3/original")), "fetched from the app's server");+}+// Stepping to a photo leaves no video behind.+await page.keyboard.press("ArrowLeft");+await page.waitForTimeout(300);+ok((await page.locator(".px-stage video").count()) === 0, "a step to a photo leaves no video playing");++// No server (it could not start): the system's player, as before.+const p2 = await ctx.newPage();+await p2.addInitScript(() => { window.__videoBase = null; });+await p2.goto("http://localhost:4173", { waitUntil: "networkidle" });+await openScreen(p2, "Photos");+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");+await b.close();+server.close();+process.exitCode = failures ? 1 : (process.exitCode ?? 0);diff --git a/.uiverify/photos.mjs b/.uiverify/photos.mjsindex c0c1bcf..5aaf5e2 100644--- a/.uiverify/photos.mjs+++ b/.uiverify/photos.mjs@@ -53,8 +53,8 @@ await page.waitForTimeout(200);ok((await page.getByRole("button", { name: "Favorite", exact: true }).count()) === 1, '"." takes it back');const flags = await page.evaluate(() => window.__flags.map((f) => `${f.id}:${f.flag}:${f.on}`));ok(JSON.stringify(flags) === JSON.stringify(["p2:favorite:true", "p2:favorite:false"]), `and each goes to iCloud ${JSON.stringify(flags)}`);-page.once("dialog", (d) => void d.accept());await page.getByRole("button", { name: "Delete", exact: true }).click();+await page.locator(".px-ask .is-act").click();await page.waitForTimeout(300);const next = await page.locator(".px-stage .px-shown").first().getAttribute("src");ok(/p3|p4/.test(next ?? "") && (await page.locator(".px-tile").count()) === 4, "Delete, once agreed, takes it out and shows the next");@@ -88,9 +88,20 @@ await page.waitForTimeout(650);ok((await page.locator(".px-viewer").count()) === 0, "Escape closes the viewer");// Opening grows the photo out of its tile: a moment in, it is still near the tile's size.+// The width in the very frame the photo first appears, caught in the page, not after a round trip.+await page.evaluate(() => {+ window.__firstWidth = null;+ const watch = new MutationObserver(() => {+ const i = document.querySelector(".px-stage .px-shown");+ if (!i) return;+ watch.disconnect();+ requestAnimationFrame(() => { window.__firstWidth = i.getBoundingClientRect().width; });+ });+ watch.observe(document.body, { childList: true, subtree: true });+});await page.locator(".px-tile").first().dblclick();-await page.waitForTimeout(40);-const mid = await page.locator(".px-shown").evaluate((i) => i.getBoundingClientRect().width);+await page.waitForFunction(() => window.__firstWidth !== null);+const mid = await page.evaluate(() => window.__firstWidth);await page.waitForTimeout(600);const end = await page.locator(".px-shown").evaluate((i) => i.getBoundingClientRect().width);ok(mid < end * 0.8 && end > 200, `a photo opens out of its tile ${Math.round(mid)} → ${Math.round(end)}px`);@@ -150,9 +161,9 @@ await page.locator(".px-scroll").click({ position: { x: 600, y: 600 } });ok((await page.locator('.px-tile[aria-selected="true"]').count()) === 0, "a click on the empty space lets the selection go");// Hide, as Photos hides: asked, out of the library, into Hidden (under Utilities), and back.-page.once("dialog", (d) => void d.accept());await page.locator(".px-tile").nth(1).click({ button: "right" });await page.locator(".row-menu").getByText("Hide Photo").click();+await page.locator(".px-ask .is-act").click();await page.waitForTimeout(300);ok((await page.locator(".px-tile").count()) === 4, "Hide Photo takes it out of the library at once");await page.locator(".px-source", { hasText: "Hidden" }).click();@@ -174,11 +185,11 @@ await page.locator(".px-tile").nth(1).dblclick();await page.waitForTimeout(600);const scaleOf = () => page.locator(".px-pan").evaluate((el) => new DOMMatrix(getComputedStyle(el).transform).a);await page.locator(".px-pan").dblclick({ position: { x: 40, y: 40 } });-await page.waitForTimeout(150);+await page.waitForTimeout(400); // the zoom glidesok((await scaleOf()) > 2, `double-click zooms in ×${(await scaleOf()).toFixed(2)}`);ok(/full/.test((await page.locator(".px-sharp").getAttribute("src")) ?? ""), "and the full picture is laid over");await page.keyboard.press("Escape");-await page.waitForTimeout(150);+await page.waitForTimeout(400); // the zoom glidesok((await scaleOf()) === 1 && (await page.locator(".px-viewer").count()) === 1, "Escape zooms back out first, and keeps the photo open");const box = await page.locator(".px-pan").boundingBox();await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);@@ -190,7 +201,7 @@ ok((await scaleOf()) > 1.5, `Ctrl + scroll zooms about the pointer ×${(await sconst gridAcross = await page.evaluate(() => getComputedStyle(document.querySelector(".px-scroll")).getPropertyValue("--across"));await page.keyboard.press("Control+0");await page.keyboard.press("Control+=");-await page.waitForTimeout(150);+await page.waitForTimeout(400); // the zoom glidesok((await scaleOf()) > 1.2 && (await page.evaluate(() => getComputedStyle(document.querySelector(".px-scroll")).getPropertyValue("--across"))) === gridAcross,"Ctrl = zooms the photo, not the grid behind it");await page.keyboard.press("Control+0");@@ -216,9 +227,14 @@ ok((await left.count()) === 1 && (await left.innerText()) === "2 days" && /is-sook((await page.getByRole("button", { name: "Delete All" }).count()) === 1, "with nothing selected, the toolbar offers Delete All");await page.locator(".px-tile").first().click();ok((await page.locator(".px-word").allInnerTexts()).join() === "Recover,Delete", "with one selected, Recover and Delete");-let asked = "";-page.once("dialog", (d) => { asked = d.message(); void d.accept(); });await page.locator(".px-word", { hasText: /^Delete$/ }).click();+const asked = await page.locator(".px-ask").innerText();+ok((await page.locator(".px-ask .px-ask-symbol").count()) === 1 && (await page.locator(".px-ask button").first().evaluate((b) => b === document.activeElement)),+ "asked in a sheet, as icloud.com asks: the trash symbol, Cancel holding the focus");+await page.keyboard.press("Escape");+ok((await page.locator(".px-ask").count()) === 0 && (await page.locator(".px-tile").count()) === 1, "Escape cancels: nothing deleted");+await page.locator(".px-word", { hasText: /^Delete$/ }).click();+await page.locator(".px-ask .is-act").click();await page.waitForTimeout(300);ok(/permanently/.test(asked) && /cannot be undone/.test(asked), `Delete asks first, in Photos' words "${asked.split("\n")[0]}"`);ok((await page.locator(".px-tile").count()) === 0 && (await page.evaluate(() => window.__flags.at(-1).flag)) === "expunged",diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjsindex 140a805..6d1ea6f 100644--- a/.uiverify/stub.mjs+++ b/.uiverify/stub.mjs@@ -362,6 +362,22 @@ export function installStub({ screen, services, twoFactor, calendarFixture, noteif (cmd === "photos_album_remove") find(args.album).items = find(args.album).items.filter((i) => !args.ids.includes(i));return null;}+ case "photos_set_flag": {+ (window.__batches ??= []).push(args);+ if (window.__flagFail) throw "iCloud didn’t accept that change.";+ const out = [];+ for (const id of args.ids) {+ (window.__flags ??= []).push({ id, flag: args.flag, on: args.on });+ const p = (window.__photos ?? []).find((x) => x.id === id);+ if (!p) continue;+ if (args.flag === "favorite") p.favorite = args.on;+ if (args.flag === "hidden") p.hidden = args.on;+ if (args.flag === "expunged") { window.__photos.splice(window.__photos.indexOf(p), 1); continue; }+ if (args.flag === "deleted") { p.deleted = args.on; p.deletedAt = args.on ? 1792700000 : null; }+ out.push(p);+ }+ return out;+ }case "photo_set_flag": {(window.__flags ??= []).push(args);if (window.__flagFail) throw "iCloud didn’t accept that change.";@@ -412,6 +428,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, notereturn p;}case "photo_play": (window.__plays ??= []).push(args); return null;+ case "video_base": return window.__videoBase ?? null;case "photo_download": (window.__downloads ??= []).push(args); return `/home/test/Downloads/IMG_${args.id}.JPG`;// Each file is answered at once with where it stands; a test plays the rest in with __emit.case "photos_upload": {diff --git a/Cargo.toml b/Cargo.tomlindex 84f114c..e2848b2 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -22,6 +22,11 @@ quince-media = { path = "crates/quince-media" }# Line tables are kept for this project's own code, so a panic still names the line it came from.[profile.dev]debug = "line-tables-only"+# The app he runs every day is this build: unoptimised, every picture served, every reply+# parsed and every database read ran many times slower than it needs to. Our own code a+# little optimised (still quick to rebuild), everything it stands on fully.+opt-level = 1[profile.dev.package."*"]debug = false+opt-level = 3diff --git a/crates/quince-icloud/src/cloudkit.rs b/crates/quince-icloud/src/cloudkit.rsindex 939d302..e5d18ff 100644--- a/crates/quince-icloud/src/cloudkit.rs+++ b/crates/quince-icloud/src/cloudkit.rs@@ -962,6 +962,163 @@ impl ZoneClient<'_> {Ok(())}+ /// Many records updated at once, as icloud.com sends a selection: up to 200 operations to a+ /// `records/modify`, not atomic — each record stands or falls alone — and a record whose+ /// change tag had moved (the phone changed it) tried once more on its fresh tag. Answers+ /// each update's outcome in the order given: the record as it now is, or why not.+ pub async fn update_records(+ &self,+ zone: &str,+ record_type: &str,+ updates: &[(String, Option<String>, Value)],+ ) -> Result<Vec<std::result::Result<Value, String>>> {+ let mut out: Vec<std::result::Result<Value, String>> = Vec::with_capacity(updates.len());+ for chunk in updates.chunks(200) {+ let first = self.modify_many(zone, record_type, chunk).await?;+ // The stale ones, once more on the tag Apple has now.+ let stale: Vec<usize> = first+ .iter()+ .enumerate()+ .filter(|(_, r)| matches!(r, Err(Error::Conflict)))+ .map(|(i, _)| i)+ .collect();+ let mut answers: Vec<std::result::Result<Value, String>> = first+ .into_iter()+ .map(|r| r.map_err(|e| e.to_string()))+ .collect();+ if !stale.is_empty() {+ let names: Vec<&str> = stale.iter().map(|&i| chunk[i].0.as_str()).collect();+ let fresh = self.lookup_tags(zone, &names).await?;+ let again: Vec<(String, Option<String>, Value)> = stale+ .iter()+ .map(|&i| {+ let (name, _, fields) = &chunk[i];+ (name.clone(), fresh.get(name).cloned(), fields.clone())+ })+ .collect();+ let second = self.modify_many(zone, record_type, &again).await?;+ for (&i, r) in stale.iter().zip(second) {+ answers[i] = r.map_err(|e| e.to_string());+ }+ }+ out.extend(answers);+ }+ Ok(out)+ }++ /// One `records/modify` of many updates, not atomic; each record's own outcome.+ async fn modify_many(+ &self,+ zone: &str,+ record_type: &str,+ updates: &[(String, Option<String>, Value)],+ ) -> Result<Vec<Result<Value>>> {+ let operations: Vec<Value> = updates+ .iter()+ .map(|(name, tag, fields)| {+ let mut record =+ json!({ "recordName": name, "recordType": record_type, "fields": fields });+ if let Some(tag) = tag {+ record["recordChangeTag"] = Value::String(tag.clone());+ }+ json!({ "operationType": "update", "record": record })+ })+ .collect();+ let body = json!({+ "operations": operations,+ "zoneID": { "zoneName": zone, "zoneType": "REGULAR_CUSTOM_ZONE" },+ "atomic": false,+ });+ let url = format!(+ "{}/database/1/{}/production/private/records/modify",+ self.base, self.container+ );+ let (status, text) = self.post_json(&url, &body).await?;+ if status.as_u16() == 450 {+ return Err(Error::ReauthRequired);+ }+ if !status.is_success() {+ return Err(Error::Protocol(format!(+ "CloudKit refused the change ({status}): {}",+ text.chars().take(200).collect::<String>()+ )));+ }+ let parsed: Value = serde_json::from_str(&text)+ .map_err(|e| Error::Protocol(format!("CloudKit returned invalid JSON: {e}")))?;+ let records = parsed+ .get("records")+ .and_then(Value::as_array)+ .cloned()+ .unwrap_or_default();+ // Matched by name, not place: an answer missing for one is that one's failure.+ Ok(updates+ .iter()+ .map(|(name, _, _)| {+ let Some(r) = records+ .iter()+ .find(|r| r.get("recordName").and_then(Value::as_str) == Some(name.as_str()))+ else {+ return Err(Error::Protocol("CloudKit did not answer for it".into()));+ };+ match r.get("reason").and_then(Value::as_str) {+ None => Ok(r.clone()),+ Some(reason) => {+ let code = r+ .get("serverErrorCode")+ .and_then(Value::as_str)+ .unwrap_or("");+ Err(+ if code == "CONFLICT" || reason.to_ascii_lowercase().contains("oplock")+ {+ Error::Conflict+ } else {+ Error::Protocol(format!("CloudKit refused the change: {reason}"))+ },+ )+ }+ }+ })+ .collect())+ }++ /// The current change tags of many records, by name; one missing is not there any more.+ async fn lookup_tags(+ &self,+ zone: &str,+ names: &[&str],+ ) -> Result<std::collections::HashMap<String, String>> {+ let url = format!(+ "{}/database/1/{}/production/private/records/lookup",+ self.base, self.container+ );+ let body = json!({+ "records": names.iter().map(|n| json!({ "recordName": n })).collect::<Vec<_>>(),+ "zoneID": { "zoneName": zone, "zoneType": "REGULAR_CUSTOM_ZONE" },+ });+ let (status, text) = self.post_json(&url, &body).await?;+ if status.as_u16() == 450 {+ return Err(Error::ReauthRequired);+ }+ if !status.is_success() {+ return Err(Error::Protocol(format!(+ "CloudKit couldn't look those up ({status})"+ )));+ }+ let parsed: Value = serde_json::from_str(&text).unwrap_or(Value::Null);+ Ok(parsed+ .get("records")+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ .filter_map(|r| {+ Some((+ r.get("recordName")?.as_str()?.to_string(),+ r.get("recordChangeTag")?.as_str()?.to_string(),+ ))+ })+ .collect())+ }+pub async fn lookup_record(&self, zone: &str, record_name: &str) -> Result<Option<Value>> {let url = format!("{}/database/1/{}/production/private/records/lookup",diff --git a/crates/quince-icloud/src/photos.rs b/crates/quince-icloud/src/photos.rsindex 9c51de9..e5cd022 100644--- a/crates/quince-icloud/src/photos.rs+++ b/crates/quince-icloud/src/photos.rs@@ -426,6 +426,37 @@ pub async fn set_flag(.await}+/// One flag on many photos at once, as icloud.com sends a selection: batched, each photo+/// standing alone. `assets` are `(record name, change tag)`. Answers each photo's outcome in+/// the order given — the asset as it now is, or why not.+pub async fn set_flags(+ http: &reqwest::Client,+ ckdatabasews_root: &str,+ params: Vec<(String, String)>,+ assets: &[(String, Option<String>)],+ flag: Flag,+ on: bool,+) -> Result<Vec<std::result::Result<Value, String>>> {+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);+ let name = match flag {+ Flag::Favorite => "isFavorite",+ Flag::Deleted => "isDeleted",+ Flag::Hidden => "isHidden",+ Flag::Expunged => "isExpunged",+ };+ let updates: Vec<(String, Option<String>, Value)> = assets+ .iter()+ .map(|(id, tag)| {+ (+ id.clone(),+ tag.clone(),+ serde_json::json!({ name: { "value": i64::from(on) } }),+ )+ })+ .collect();+ client.update_records(ZONE, "CPLAsset", &updates).await+}+/// A photo's title and caption set, as icloud.com's Info sets them: the title is `captionEnc`/// and the caption `extendedDescEnc` (Apple's names), each base64 of its UTF-8 bytes, against/// the asset's change tag. Empty clears one. Answers the asset as it now is.diff --git a/probe/examples/photos_flags_batch_live.rs b/probe/examples/photos_flags_batch_live.rsnew file mode 100644index 0000000..98ef2bd--- /dev/null+++ b/probe/examples/photos_flags_batch_live.rs@@ -0,0 +1,139 @@+//! Live, on three synthetic photos it uploads itself: one batched `records/modify` per step —+//! favorite on and off, delete and recover, one of them sent on a stale change tag to prove the+//! retry — each read back from Apple; then all three deleted and deleted for good in two batches,+//! as "Delete All" in Recently Deleted does. Nothing of his is touched.+use anyhow::{anyhow, Result};+use quince_icloud::photos::Flag;+use quince_icloud::photos_upload::Outcome;+#[tokio::main]+async fn main() -> Result<()> {+ let files: Vec<std::path::PathBuf> = std::env::args().skip(1).map(Into::into).collect();+ anyhow::ensure!(files.len() == 3, "three jpeg paths");+ 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 up = client+ .session()+ .service_url("photosupload")+ .ok_or_else(|| anyhow!("no upload"))?;+ let root = client+ .session()+ .service_url("ckdatabasews")+ .ok_or_else(|| anyhow!("no ck"))?;+ let (http, p) = (client.http().clone(), client.service_params());+ let dsid = p+ .iter()+ .find(|(k, _)| k == "dsid")+ .map(|(_, v)| v.clone())+ .ok_or_else(|| anyhow!("no dsid"))?;+ let mut ids = Vec::new();+ for f in &files {+ let name = f.file_name().unwrap().to_string_lossy().to_string();+ let quiet: std::sync::Arc<dyn Fn(quince_icloud::photos_upload::Stage) + Send + Sync> =+ std::sync::Arc::new(|_| {});+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)?+ .as_millis() as i64;+ match quince_icloud::photos_upload::upload(+ &http,+ &up,+ &dsid,+ f,+ &name,+ now,+ "Asia/Kolkata",+ -330,+ &uuid::Uuid::new_v4().to_string(),+ quiet,+ )+ .await?+ {+ Outcome::Uploaded(u) => ids.push(u.asset),+ other => return Err(anyhow!("{name}: {other:?}")),+ }+ }+ println!("uploaded three throwaways: {ids:?}");+ let zc =+ quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.photos.cloud", p.clone());+ let read = |id: String| {+ let zc = &zc;+ async move {+ let r = zc.lookup_record("PrimarySync", &id).await?;+ anyhow::Ok(r.map(|r| {+ (+ quince_icloud::cloudkit::field::int(&r, "isFavorite").unwrap_or(0) == 1,+ quince_icloud::cloudkit::field::int(&r, "isDeleted").unwrap_or(0) == 1,+ quince_icloud::cloudkit::field::int(&r, "isExpunged").unwrap_or(0) == 1,+ r["recordChangeTag"].as_str().map(str::to_string),+ )+ }))+ }+ };+ let tags = |stale: Option<String>| {+ let ids = ids.clone();+ let read = &read;+ async move {+ let mut out = Vec::new();+ for (n, id) in ids.iter().enumerate() {+ let tag = read(id.clone()).await?.ok_or_else(|| anyhow!("gone"))?.3;+ out.push((+ id.clone(),+ if n == 0 && stale.is_some() {+ stale.clone()+ } else {+ tag+ },+ ));+ }+ anyhow::Ok(out)+ }+ };+ let first_tag = read(ids[0].clone())+ .await?+ .ok_or_else(|| anyhow!("gone"))?+ .3;+ let steps = [+ (Flag::Favorite, true, None),+ (Flag::Favorite, false, first_tag.clone()), // the first on its long-stale tag+ (Flag::Deleted, true, None),+ (Flag::Deleted, false, None),+ (Flag::Deleted, true, None),+ (Flag::Expunged, true, None),+ ];+ for (flag, on, stale) in steps {+ let assets = tags(stale.clone()).await?;+ let t = std::time::Instant::now();+ let out =+ quince_icloud::photos::set_flags(&http, &root, p.clone(), &assets, flag, on).await?;+ let refused: Vec<_> = out.iter().filter_map(|r| r.as_ref().err()).collect();+ println!(+ "{flag:?}={on}{}: one batch in {:?}, refused {refused:?}",+ if stale.is_some() {+ " (one stale tag)"+ } else {+ ""+ },+ t.elapsed()+ );+ anyhow::ensure!(refused.is_empty());+ for id in &ids {+ let s = read(id.clone()).await?;+ let ok = match (flag, s) {+ (Flag::Favorite, Some(s)) => s.0 == on,+ (Flag::Deleted, Some(s)) => s.1 == on,+ (Flag::Expunged, s) => s.is_none_or(|s| s.2),+ _ => false,+ };+ anyhow::ensure!(+ ok,+ "{id} did not take {flag:?}={on}: {s:?}",+ s = read(id.clone()).await?+ );+ }+ println!(" read back from Apple: all three");+ }+ println!("all three throwaways deleted for good; nothing of his touched");+ Ok(())+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex c20b913..ab88ea6 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -5,6 +5,7 @@ mod alerts;mod photos;mod push;mod refresh;+mod video;use quince_auth::{Client, SignInOutcome, TwoFactorOptions};use quince_core::calendar::{Calendar, Event};@@ -3461,23 +3462,32 @@ fn adopt_writer(library: &mut Library) {quince_icloud::topotext::set_writer(*id.as_bytes());}-/// WebKitGTK hands its frames to the compositor as DMA-BUFs; on Wayland that path tears and-/// flickers — whole-window flashes on a resize, on a menu, on a screen changing — which he saw-/// across the app. Turning it off (WebKitGTK's own switch, the one Tauri's Linux users are-/// pointed to) draws through shared memory instead, steadily. Only under Wayland, only when the-/// person has not set it themselves; `QUINCE_DMABUF=1` keeps DMA-BUF for anyone who wants it.+/// WebKitGTK hands its frames to the compositor as DMA-BUFs — the GPU's own buffers, no copy.+/// It was turned off once (`WEBKIT_DISABLE_DMABUF_RENDERER`) for flashes seen on resizes and+/// menus, but that copies every frame of the window through shared memory, and measured on+/// this machine's Iris Xe at 2560 wide it cost two thirds of every frame: the grid scrolled at+/// 23 fps against 60, a zoomed photo panned at 21 against 61, and opening one stalled. So it+/// stays on. `QUINCE_DMABUF=0` turns it off for anyone whose compositor flickers with it.fn steady_drawing() {- let wayland = std::env::var("XDG_SESSION_TYPE")- .is_ok_and(|s| s.eq_ignore_ascii_case("wayland"))- || std::env::var_os("WAYLAND_DISPLAY").is_some_and(|v| !v.is_empty());- let chosen = std::env::var_os("WEBKIT_DISABLE_DMABUF_RENDERER").is_some()- || std::env::var_os("QUINCE_DMABUF").is_some_and(|v| v == "1");- if wayland && !chosen {+ let chosen = std::env::var_os("WEBKIT_DISABLE_DMABUF_RENDERER").is_some();+ if !chosen && std::env::var_os("QUINCE_DMABUF").is_some_and(|v| v == "0") {// Before any thread starts: nothing else can be reading the environment yet.std::env::set_var("WEBKIT_DISABLE_DMABUF_RENDERER", "1");}}+/// WebKitGTK's player on its older pipeline (playbin) buffers a video read over HTTP to disk+/// and then stalls: "Pausing stream for buffering" after the whole file has arrived, the+/// picture frozen on its first frame. Its newer pipeline (playbin3, WebKit's own switch) plays+/// and seeks the same file smoothly — proven on this machine's WebKitGTK 2.54. Only when the+/// person has not chosen themselves.+fn smooth_video() {+ if std::env::var_os("WEBKIT_GST_USE_PLAYBIN3").is_none() {+ // Before any thread starts: nothing else can be reading the environment yet.+ std::env::set_var("WEBKIT_GST_USE_PLAYBIN3", "1");+ }+}+/// Whether this session runs under a tiling Wayland compositor, which manages windows itself.fn tiling_compositor() -> bool {let set = |k: &str| std::env::var_os(k).is_some_and(|v| !v.is_empty());@@ -3560,6 +3570,7 @@ fn build_tray(app: &tauri::App) -> tauri::Result<()> {fn main() {steady_drawing();+ smooth_video();tauri::Builder::default()// 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.@@ -3700,6 +3711,7 @@ fn main() {});}).setup(|app| {+ video::serve(app.handle().clone());let dir = state_dir(app.handle());let client = Arc::new(Mutex::new(Client::new(&dir)?));app.manage(Auth {@@ -3794,6 +3806,8 @@ fn main() {photos::photos_in_album,photos::photo_set_flag,photos::photo_play,+ photos::photos_set_flag,+ video::video_base,photos::photos_upload,photos::photos_upload_cancel,photos::photos_album_create,diff --git a/src-tauri/src/photos.rs b/src-tauri/src/photos.rsindex c704572..c174c3e 100644--- a/src-tauri/src/photos.rs+++ b/src-tauri/src/photos.rs@@ -43,7 +43,7 @@ fn fresh_links(master: &str) -> Option<Links> {}/// Which of a photo's pictures is wanted.-#[derive(Clone, Copy, PartialEq, Eq)]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum Size {Thumb,Medium,@@ -267,6 +267,47 @@ async fn new_link(}/// 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`.+pub fn byte_range(header: Option<&str>, len: u64, most: u64) -> Option<(u64, u64)> {+ if len == 0 || most == 0 {+ return None;+ }+ let (first, last) = match header {+ None => (0, len - 1),+ Some(h) => {+ let spec = h.trim().strip_prefix("bytes=")?.split(',').next()?.trim();+ let (a, b) = spec.split_once('-')?;+ match (a.trim(), b.trim()) {+ // The last n bytes: where a player looks for an index at the end.+ ("", n) => {+ let n: u64 = n.parse().ok()?;+ if n == 0 {+ return None;+ }+ (len.saturating_sub(n), len - 1)+ }+ (a, "") => (a.parse().ok()?, len - 1),+ (a, b) => (a.parse().ok()?, b.parse::<u64>().ok()?.min(len - 1)),+ }+ }+ };+ if first > last || first >= len {+ return None;+ }+ Some((first, last.min(first.saturating_add(most - 1))))+}++/// A video's type from its first bytes: a QuickTime film says so in its first box; everything+/// else Apple keeps is MPEG-4.+pub fn video_type(head: &[u8]) -> &'static str {+ if head.get(8..12) == Some(b"qt ") {+ "video/quicktime"+ } else {+ "video/mp4"+ }+}+pub fn content_type(bytes: &[u8], size: Size) -> &'static str {if size == Size::Video || bytes.get(4..8) == Some(b"ftyp") {return "video/mp4";@@ -603,6 +644,134 @@ pub async fn photo_set_flag(Ok(updated)}+/// One flag on many photos — a selection deleted, recovered, hidden, favorited, or deleted+/// for good from Recently Deleted — as Photos does it: the library changes first, so every view+/// (and a sync pass reading it) shows it at once, then Apple is told in batches; whatever Apple+/// refuses is put back as it was. Answers the photos as they now are, and an error naming how+/// many could not be changed, if any.+#[tauri::command]+pub async fn photos_set_flag(+ ids: Vec<String>,+ flag: quince_icloud::photos::Flag,+ on: bool,+ auth: State<'_, Auth>,+ data: State<'_, Data>,+) -> UiResult<Vec<Photo>> {+ use quince_icloud::photos::Flag;+ let now = jiff::Timestamp::now().as_second();+ let set = |p: &mut Photo| match flag {+ Flag::Favorite => p.favorite = on,+ Flag::Hidden => p.hidden = on,+ Flag::Deleted => {+ p.deleted = on;+ p.deleted_at = on.then_some(now);+ p.expunge_at = on.then_some(now + 30 * 86_400);+ }+ Flag::Expunged => {}+ };+ // At once, in the library.+ let before: Vec<Photo> = {+ let mut library = data.0.lock().await;+ let mut found = Vec::with_capacity(ids.len());+ for id in &ids {+ if let Some(p) = library.photo(id).map_err(|e| e.to_string())? {+ found.push(p);+ }+ }+ // Deleting for good is only ever from Recently Deleted, and only ever on.+ if flag == Flag::Expunged && (!on || found.iter().any(|p| !p.deleted)) {+ return Err("Only photos in Recently Deleted can be deleted for good.".into());+ }+ if flag == Flag::Expunged {+ let gone: Vec<String> = found.iter().map(|p| p.id.clone()).collect();+ library.forget_photos(&gone).map_err(|e| e.to_string())?;+ } else {+ let changed: Vec<Photo> = found+ .iter()+ .cloned()+ .map(|mut p| {+ set(&mut p);+ p+ })+ .collect();+ library.put_photos(&changed).map_err(|e| e.to_string())?;+ }+ found+ };+ if before.is_empty() {+ return Ok(Vec::new());+ }+ // Then to Apple, with no sync pass between the two.+ let _one = crate::PHOTOS_PASS.lock().await;+ let sent = async {+ let (http, root, params) = crate::cloudkit_context(&auth).await?;+ let assets: Vec<(String, Option<String>)> = before+ .iter()+ .map(|p| (p.id.clone(), p.change_tag.clone()))+ .collect();+ quince_icloud::photos::set_flags(&http, &root, params, &assets, flag, on)+ .await+ .map_err(|e| e.to_string())+ }+ .await;+ let answers = match sent {+ Ok(a) => a,+ Err(e) => {+ // Nothing reached Apple: all of it as it was.+ let mut library = data.0.lock().await;+ library.put_photos(&before).map_err(|e| e.to_string())?;+ return Err(e);+ }+ };+ let mut now_are = Vec::with_capacity(before.len());+ let mut refused = Vec::new();+ let mut why = None;+ for (old, answer) in before.iter().zip(answers) {+ match answer {+ Ok(record) => {+ if flag == Flag::Expunged {+ continue;+ }+ let mut p = old.clone();+ set(&mut p);+ if flag == Flag::Deleted && on {+ // Apple's own date for when it goes for good.+ if let Some(ms) = record+ .pointer("/fields/dateExpunged/value")+ .and_then(serde_json::Value::as_i64)+ {+ p.expunge_at = Some(ms / 1000);+ }+ }+ p.change_tag = record+ .get("recordChangeTag")+ .and_then(serde_json::Value::as_str)+ .map(str::to_string)+ .or(p.change_tag);+ now_are.push(p);+ }+ Err(e) => {+ why.get_or_insert(e);+ refused.push(old.clone());+ }+ }+ }+ {+ let mut library = data.0.lock().await;+ library.put_photos(&now_are).map_err(|e| e.to_string())?;+ library.put_photos(&refused).map_err(|e| e.to_string())?;+ }+ if let Some(why) = why {+ let n = refused.len();+ return Err(format!(+ "{n} of {} {} could not be changed: {why}",+ before.len(),+ if before.len() == 1 { "photo" } else { "photos" }+ ));+ }+ Ok(now_are)+}+/// A photo's title and caption, as typed in its Info: Apple's answer taken at once. Empty clears one.#[tauri::command]pub async fn photo_set_text(@@ -1442,3 +1611,46 @@ async fn refresh_photos(app: &AppHandle) {app.emit(crate::SYNCED, crate::refresh::status(&data.0).await).ok();}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn ranges_as_a_player_asks_for_them() {+ let len = 10 * 1024 * 1024;+ let all = u64::MAX;+ assert_eq!(byte_range(None, len, all), Some((0, len - 1)));+ assert_eq!(byte_range(Some("bytes=0-"), len, all), Some((0, len - 1)));+ assert_eq!(byte_range(Some("bytes=0-"), len, 4096), Some((0, 4095)));+ assert_eq!(byte_range(Some("bytes=0-1"), len, all), Some((0, 1)));+ assert_eq!(+ byte_range(Some("bytes=100-199"), len, all),+ Some((100, 199))+ );+ assert_eq!(+ byte_range(Some("bytes=-500"), len, all),+ Some((len - 500, len - 1))+ );+ assert_eq!(+ byte_range(Some("bytes=9000000-"), len, all),+ Some((9_000_000, len - 1))+ );+ assert_eq!(+ byte_range(Some("bytes=5-999999999"), 100, all),+ Some((5, 99))+ );+ assert_eq!(byte_range(Some("bytes=100-"), 100, all), None);+ assert_eq!(byte_range(Some("bytes=9-3"), 100, all), None);+ assert_eq!(byte_range(Some("bytes=-0"), 100, all), None);+ assert_eq!(byte_range(Some("items=0-1"), 100, all), None);+ assert_eq!(byte_range(None, 0, all), None);+ }++ #[test]+ fn quicktime_or_mpeg4() {+ assert_eq!(video_type(b"\0\0\0\x14ftypqt "), "video/quicktime");+ assert_eq!(video_type(b"\0\0\0\x18ftypmp42"), "video/mp4");+ assert_eq!(video_type(b""), "video/mp4");+ }+}diff --git a/src-tauri/src/video.rs b/src-tauri/src/video.rsnew file mode 100644index 0000000..609ff47--- /dev/null+++ b/src-tauri/src/video.rs@@ -0,0 +1,296 @@+//! Videos played in the window. WebKitGTK's player (GStreamer) reads only http(s), blob and+//! file sources — never a custom scheme like `quince://` ("No URI handler implemented") — and+//! a page of ours may not load `file://`. So the disk cache's videos are served over HTTP on+//! the loopback interface: a port of the system's choosing, a fresh secret in every path, only+//! cached videos by asset id, in the ranges the player asks for, streamed from disk.++use crate::photos::{self, Size};+use std::path::PathBuf;+use std::sync::OnceLock;+use tauri::AppHandle;+use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncSeekExt, AsyncWriteExt, BufReader};+use tokio::net::{TcpListener, TcpStream};++/// `http://127.0.0.1:<port>/<secret>`, once the server is listening.+static BASE: OnceLock<String> = OnceLock::new();++/// Where the window's player fetches a video from, or `None` if the server could not start+/// (the viewer then offers the system's player).+#[tauri::command]+pub fn video_base() -> Option<String> {+ BASE.get().cloned()+}++/// Listens on the loopback interface for as long as the app runs.+pub fn serve(app: AppHandle) {+ tauri::async_runtime::spawn(async move {+ let Ok(listener) = TcpListener::bind(("127.0.0.1", 0)).await else {+ return;+ };+ let Ok(addr) = listener.local_addr() else {+ return;+ };+ let secret = uuid::Uuid::new_v4().simple().to_string();+ let _ = BASE.set(format!("http://127.0.0.1:{}/{secret}", addr.port()));+ listen(listener, secret, move |id, size| {+ let app = app.clone();+ async move { photos::cached(&app, &id, size).await }+ })+ .await;+ });+}++/// Answers each connection on its own task; `find` gives a cached video's path on disk.+async fn listen<F, Fut>(listener: TcpListener, secret: String, find: F)+where+ F: Fn(String, Size) -> Fut + Clone + Send + Sync + 'static,+ Fut: std::future::Future<Output = Result<PathBuf, String>> + Send,+{+ while let Ok((stream, _)) = listener.accept().await {+ let (find, secret) = (find.clone(), secret.clone());+ tauri::async_runtime::spawn(async move {+ let _ = answer(find, &secret, stream).await;+ });+ }+}++/// What one request asks for: the video and its size, and the Range header if any.+#[derive(Debug, PartialEq)]+struct Asked {+ id: String,+ size: Size,+ range: Option<String>,+ head: bool,+}++/// The request line and headers, read up to the blank line; anything not ours is `None`.+fn parse(secret: &str, lines: &[String]) -> Option<Asked> {+ let mut first = lines.first()?.split_whitespace();+ let method = first.next()?;+ let head = match method {+ "GET" => false,+ "HEAD" => true,+ _ => return None,+ };+ let path = first.next()?.split('?').next()?;+ let rest = path.strip_prefix('/')?.strip_prefix(secret)?;+ let (id, size) = photos::requested(&format!("pic{rest}"))?;+ if !matches!(size, Size::Original | Size::Video) {+ return None;+ }+ let range = lines.iter().skip(1).find_map(|l| {+ let (k, v) = l.split_once(':')?;+ k.trim()+ .eq_ignore_ascii_case("range")+ .then(|| v.trim().to_string())+ });+ Some(Asked {+ id,+ size,+ range,+ head,+ })+}++async fn answer<F, Fut>(find: F, secret: &str, stream: TcpStream) -> std::io::Result<()>+where+ F: Fn(String, Size) -> Fut,+ Fut: std::future::Future<Output = Result<PathBuf, String>>,+{+ let mut reader = BufReader::new(stream);+ let mut lines = Vec::new();+ loop {+ let mut line = String::new();+ // Each line read only so far: an endless one is cut off, not held.+ let read = (&mut reader).take(8192).read_line(&mut line).await?;+ if read == 0 || lines.len() > 64 || !line.ends_with('\n') {+ return Ok(());+ }+ let line = line.trim_end().to_string();+ if line.is_empty() {+ break;+ }+ lines.push(line);+ }+ let mut stream = reader.into_inner();+ let Some(asked) = parse(secret, &lines) else {+ return status(&mut stream, "404 Not Found", "").await;+ };+ let Ok(path) = find(asked.id.clone(), asked.size).await else {+ return status(&mut stream, "404 Not Found", "").await;+ };+ let mut file = tokio::fs::File::open(&path).await?;+ let len = file.metadata().await?.len();+ let mut head = [0u8; 12];+ let _ = file.read(&mut head).await;+ let kind = photos::video_type(&head);+ let Some((first, last)) = photos::byte_range(asked.range.as_deref(), len, u64::MAX) else {+ let extra = format!("Content-Range: bytes */{len}\r\n");+ return status(&mut stream, "416 Range Not Satisfiable", &extra).await;+ };+ let n = last - first + 1;+ let line = if asked.range.is_some() {+ "206 Partial Content"+ } else {+ "200 OK"+ };+ let headers = format!(+ "HTTP/1.1 {line}\r\nContent-Type: {kind}\r\nContent-Length: {n}\r\nAccept-Ranges: bytes\r\n\+ Content-Range: bytes {first}-{last}/{len}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n"+ );+ stream.write_all(headers.as_bytes()).await?;+ if !asked.head {+ file.seek(std::io::SeekFrom::Start(first)).await?;+ // Streamed from disk: a long film is never held in memory, and a player that stops+ // reading (a seek elsewhere) just closes the connection.+ tokio::io::copy(&mut file.take(n), &mut stream).await?;+ }+ stream.shutdown().await+}++async fn status(stream: &mut TcpStream, line: &str, extra: &str) -> std::io::Result<()> {+ let text = format!("HTTP/1.1 {line}\r\n{extra}Content-Length: 0\r\nConnection: close\r\n\r\n");+ stream.write_all(text.as_bytes()).await?;+ stream.shutdown().await+}++#[cfg(test)]+mod tests {+ use super::*;++ /// One raw request to the server, and its whole answer: head and body.+ async fn get(port: u16, request: &str) -> (String, Vec<u8>) {+ let mut s = TcpStream::connect(("127.0.0.1", port)).await.unwrap();+ s.write_all(request.as_bytes()).await.unwrap();+ let mut all = Vec::new();+ s.read_to_end(&mut all).await.unwrap();+ let at = all.windows(4).position(|w| w == b"\r\n\r\n").unwrap();+ (+ String::from_utf8_lossy(&all[..at]).into_owned(),+ all[at + 4..].to_vec(),+ )+ }++ #[test]+ fn serves_a_cached_video_in_ranges() {+ tauri::async_runtime::block_on(async {+ let dir = std::env::temp_dir().join(format!("quince-video-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let file = dir.join("clip");+ let bytes: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect();+ std::fs::write(&file, &bytes).unwrap();+ let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();+ let port = listener.local_addr().unwrap().port();+ let found = file.clone();+ tauri::async_runtime::spawn(listen(listener, "k3y".into(), move |id, _| {+ let found = found.clone();+ async move {+ if id == "v1" {+ Ok(found)+ } else {+ Err("none".into())+ }+ }+ }));++ let (head, body) = get(port, "GET /k3y/v1/original HTTP/1.1\r\nHost: x\r\n\r\n").await;+ assert!(head.starts_with("HTTP/1.1 200 OK"), "{head}");+ assert!(+ head.contains("Accept-Ranges: bytes") && head.contains("Content-Type: video/mp4")+ );+ assert_eq!(body, bytes);++ let (head, body) = get(+ port,+ "GET /k3y/v1/original HTTP/1.1\r\nRange: bytes=1000-1999\r\n\r\n",+ )+ .await;+ assert!(head.starts_with("HTTP/1.1 206 Partial Content"), "{head}");+ assert!(+ head.contains("Content-Range: bytes 1000-1999/200000"),+ "{head}"+ );+ assert_eq!(body, bytes[1000..2000]);++ let (head, body) = get(+ port,+ "GET /k3y/v1/original HTTP/1.1\r\nrange: bytes=-10\r\n\r\n",+ )+ .await;+ assert!(+ head.contains("Content-Range: bytes 199990-199999/200000"),+ "{head}"+ );+ assert_eq!(body, bytes[199_990..]);++ let (head, body) = get(port, "HEAD /k3y/v1/original HTTP/1.1\r\n\r\n").await;+ assert!(+ head.contains("Content-Length: 200000") && body.is_empty(),+ "{head}"+ );++ let (head, _) = get(+ port,+ "GET /k3y/v1/original HTTP/1.1\r\nRange: bytes=300000-\r\n\r\n",+ )+ .await;+ assert!(head.starts_with("HTTP/1.1 416"), "{head}");+ let (head, _) = get(port, "GET /nope/v1/original HTTP/1.1\r\n\r\n").await;+ assert!(head.starts_with("HTTP/1.1 404"), "{head}");+ let (head, _) = get(port, "GET /k3y/v2/original HTTP/1.1\r\n\r\n").await;+ assert!(head.starts_with("HTTP/1.1 404"), "{head}");+ std::fs::remove_dir_all(&dir).ok();+ });+ }++ fn lines(s: &[&str]) -> Vec<String> {+ s.iter().map(|l| l.to_string()).collect()+ }++ #[test]+ fn only_our_secret_and_only_videos() {+ let ok = parse(+ "s3cret",+ &lines(&["GET /s3cret/abc-1/original HTTP/1.1", "Range: bytes=0-"]),+ );+ assert_eq!(+ ok,+ Some(Asked {+ id: "abc-1".into(),+ size: Size::Original,+ range: Some("bytes=0-".into()),+ head: false+ })+ );+ let live = parse("s3cret", &lines(&["HEAD /s3cret/abc/video HTTP/1.1"])).unwrap();+ assert!(live.head && live.size == Size::Video && live.range.is_none());+ // Someone else's guess, a picture, a path out of the cache, another method.+ assert_eq!(+ parse("s3cret", &lines(&["GET /wrong/abc/original HTTP/1.1"])),+ None+ );+ assert_eq!(+ parse("s3cret", &lines(&["GET /s3cret/abc/full HTTP/1.1"])),+ None+ );+ assert_eq!(+ parse("s3cret", &lines(&["GET /s3cret/../x/original HTTP/1.1"])),+ None+ );+ assert_eq!(+ parse(+ "s3cret",+ &lines(&["GET /s3cret/a%2F..%2Fb/original HTTP/1.1"])+ ),+ None+ );+ assert_eq!(+ parse("s3cret", &lines(&["POST /s3cret/abc/original HTTP/1.1"])),+ None+ );+ assert_eq!(+ parse("s3cret", &lines(&["GET /s3cretabc/original HTTP/1.1"])),+ None+ );+ }+}diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex be7789a..b24848e 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -95,7 +95,11 @@ export const api = {photosInAlbum: (album: string) => invoke<Photo[]>("photos_in_album", { album }),/** A video (or a Live Photo's moving part) opened in this computer's own player. */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"),/** Favorite, Delete (to Recently Deleted) or Recover; answers the photo as Apple now has it. */+ photosSetFlag: (ids: string[], flag: "favorite" | "deleted" | "hidden" | "expunged", on: boolean) =>+ invoke<Photo[]>("photos_set_flag", { ids, flag, on }),photoSetFlag: (id: string, flag: "favorite" | "deleted" | "hidden" | "expunged", on: boolean) =>invoke<Photo>("photo_set_flag", { id, flag, on }),/** The original saved to Downloads; answers where. */diff --git a/src/screens/PhotosView.tsx b/src/screens/PhotosView.tsxindex 273f09d..6faa5bb 100644--- a/src/screens/PhotosView.tsx+++ b/src/screens/PhotosView.tsx@@ -24,6 +24,7 @@ import { UploadPanel } from "./photos/UploadPanel";import { RowMenu, type MenuEntry } from "../components/RowMenu";import { Portal } from "../components/Portal";import { Slideshow } from "./photos/Slideshow";+import { useAsk } from "./photos/Ask";import { DownloadOptions, type Want } from "./photos/DownloadOptions";import { AdjustDate } from "./photos/AdjustDate";@@ -187,6 +188,25 @@ function warm(id: string): Promise<boolean> {return ready;}+/**+ * Photos whose thumbnail is too small for their tile. Apple's thumbnails run from about 360 to+ * 560 pixels on the long side; a large tile on a dense screen needs more, and a thumbnail+ * stretched over it is soft. Such a tile asks for the screen-sized picture instead, once.+ */+const finer = new Set<string>();+function sharpen(img: HTMLImageElement, id: string) {+ if (finer.has(id) || !img.naturalWidth || !img.naturalHeight) return;+ const fit = img.closest("[data-fit]") !== null;+ const sx = (img.clientWidth * window.devicePixelRatio) / img.naturalWidth;+ const sy = (img.clientHeight * window.devicePixelRatio) / img.naturalHeight;+ // Cover crops to the larger stretch; a fitted tile shows the whole picture.+ const stretch = fit ? Math.min(sx, sy) : Math.max(sx, sy);+ if (stretch > 1.1) {+ finer.add(id);+ img.src = pictureSrc(id, "medium");+ }+}+/** What a tile can ask of the screen; one object, kept the same, so tiles need not redraw. */type Acts = {pick: (index: number, e: React.MouseEvent) => void;@@ -259,7 +279,15 @@ const Tile = memo(function Tile({{/* The picture's own frame: the whole tile when squares, the photo's own shape whenfitted — what the badges and the selection sit on. */}<span className="px-pic" style={fit && photo.width && photo.height ? fitFrame(photo) : undefined}>- <img src={pictureSrc(photo.id, "thumb")} alt="" loading="lazy" decoding="async" draggable={false} />+ {/* Fetched as soon as its month is built, well ahead of the screen — not left to the+ engine's own lazy margin, which a fast scroll outran. */}+ <img+ src={pictureSrc(photo.id, finer.has(photo.id) ? "medium" : "thumb")}+ alt=""+ decoding="async"+ draggable={false}+ onLoad={(e) => sharpen(e.currentTarget, photo.id)}+ />{photo.kind === "video" && (<span className="px-badge px-duration"><Play size={10} strokeWidth={0} fill="currentColor" aria-hidden="true" />@@ -308,10 +336,16 @@ const Month = memo(function Month({setLive(true);return undefined;}- const watch = new IntersectionObserver(([e]) => setLive(e.isIntersecting), {- root: el.closest(".px-scroll"),- rootMargin: "1600px 0px",- });+ // 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;+ setLive(true);+ watch.disconnect();+ },+ { root: el.closest(".px-scroll"), rootMargin: "4000px 0px" },+ );watch.observe(el);return () => watch.disconnect();}, []);@@ -533,30 +567,22 @@ export function PhotosView() {a.cancel();});};- const [room, setRoom] = useState<{ w: number; h: number } | null>(null);- useLayoutEffect(() => {- const el = stage.current;- if (!el) return undefined;- const measure = () => {- const cs = getComputedStyle(el);- setRoom({- w: el.clientWidth - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight),- h: el.clientHeight - parseFloat(cs.paddingTop) - parseFloat(cs.paddingBottom),- });- };- measure();- const watch = new ResizeObserver(measure);- watch.observe(el);- return () => watch.disconnect();- }, [open !== null]); // eslint-disable-line react-hooks/exhaustive-deps- // The photo's own box, worked out before it loads, so its thumbnail fills that box at once- // and the sharper picture lands on top of it without anything moving.- const fitted = (p: Photo): React.CSSProperties | undefined => {- if (!room || !p.width || !p.height) return undefined;- const k = Math.min(room.w / p.width, room.h / p.height, 1.5);+ // The photo's own box, laid out by the engine itself against the stage (a size container):+ // as large as fits, never past 1.5× its own pixels, its shape exact. Known before it loads,+ // so its thumbnail fills that box at once and the sharper picture lands without anything+ // moving; and a window being resized redraws it every frame with no script in the way.+ 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")}")` };+ 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+ // aspect-ratio, and drew every photo square.+ const r = (p.width / p.height).toFixed(6);return {- width: Math.round(p.width * k),- height: Math.round(p.height * k),+ ...under,+ width: `min(100cqw, ${r} * 100cqh, ${Math.round(p.width * 1.5)}px)`,+ height: `min(100cqw / ${r}, 100cqh, ${Math.round(p.height * 1.5)}px)`,maxWidth: "none",maxHeight: "none",};@@ -573,7 +599,7 @@ export function PhotosView() {return `translate(${dx}px, ${dy}px) scale(${k})`;};useLayoutEffect(() => {- if (open === null || !room) return;+ if (open === null) return;const from = origin.current;origin.current = null;const el = viewer.current;@@ -585,9 +611,9 @@ export function PhotosView() {const t = img && toTile(img, from);if (img && t) img.animate([{ transform: t }, { transform: "none" }], { duration: 460, easing: spring() });for (const part of el.querySelectorAll<HTMLElement>(".px-backdrop, .px-viewer-bar, .px-nav, .px-info")) {- part.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 260, easing: "ease-out" });+ part.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 160, easing: "ease-out" });}- }, [open !== null && room !== null]); // eslint-disable-line react-hooks/exhaustive-deps+ }, [open !== null]); // eslint-disable-line react-hooks/exhaustive-depsconst close = useCallback(() => {const el = viewer.current;@@ -611,7 +637,7 @@ export function PhotosView() {};const t = seen && img ? toTile(img, box) : null;const parts = [...el.querySelectorAll<HTMLElement>(".px-backdrop, .px-viewer-bar, .px-nav, .px-info")];- const anims = parts.map((part) => part.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 220, easing: "ease-in", fill: "forwards" }));+ const anims = parts.map((part) => part.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 140, easing: "ease-in", fill: "forwards" }));const last = t && img? img.animate([{ transform: "none" }, { transform: t }], { duration: 340, easing: spring(), fill: "forwards" }): el.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 200, easing: "ease-in", fill: "forwards" });@@ -636,12 +662,43 @@ export function PhotosView() {* One transform on the photo's frame, so it is the compositor's work. Past the fit, the* full picture is laid over the screen-sized one once it has loaded.*/- const [lens, setLens] = useState({ k: 1, x: 0, y: 0 });- const lensRef = useRef(lens);- lensRef.current = lens;+ // The lens lives outside React: a gesture writes the frame's transform straight to it, once a+ // frame, so a pan or a pinch never redraws the screen (which made it crawl). Only crossing+ // into or out of zoom is state — the cursor and the double-click's meaning change with it.+ const lensRef = useRef({ k: 1, x: 0, y: 0 });+ const [zoomed, setZoomed] = useState(false);const pan = useRef<HTMLDivElement | null>(null);+ const settle = useRef<number | undefined>(undefined);+ const frame = useRef<number | null>(null);+ const paint = (next: { k: number; x: number; y: number }, glide = false) => {+ lensRef.current = next;+ setZoomed(next.k > 1);+ if (frame.current !== null) return;+ frame.current = requestAnimationFrame(() => {+ frame.current = null;+ const el = pan.current;+ if (!el) return;+ const { k, x, y } = lensRef.current;+ // Its own layer only while it moves — moved as one bitmap — and drawn afresh, sharp at+ // the new size, once it rests.+ el.style.willChange = "transform";+ el.style.transition = glide ? "transform 280ms var(--spring-smooth, ease-out)" : "none";+ el.style.transform = k > 1 ? `translate3d(${x}px, ${y}px, 0) scale(${k})` : "";+ window.clearTimeout(settle.current);+ settle.current = window.setTimeout(() => {+ if (pan.current) pan.current.style.willChange = "";+ }, glide ? 340 : 160);+ });+ };const [sharp, setSharp] = useState<string | null>(null);- const unzoom = () => setLens({ k: 1, x: 0, y: 0 });+ /** Videos this computer's engine could not play; each opens in the system's player instead. */+ 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);+ useEffect(() => {+ api.videoBase().then(setVideoBase, () => setVideoBase(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.const bound = (k: number, x: number, y: number) => {const el = pan.current;@@ -651,21 +708,24 @@ export function PhotosView() {return { k, x: Math.max(-mx, Math.min(mx, x)), y: Math.max(-my, Math.min(my, y)) };};// Zoom to k, keeping the point under (sx, sy) — screen coordinates — where it is.- const zoomAt = (k: number, sx: number, sy: number) => {+ const zoomAt = (k: number, sx: number, sy: number, glide = true) => {const el = pan.current;if (!el) return;- const box = el.getBoundingClientRect();+ // The frame's centre as laid out, before any transform: the transform on screen may be a+ // frame behind the lens while a pinch runs.+ const host = (el.offsetParent as HTMLElement | null)?.getBoundingClientRect();+ if (!host) return;const was = lensRef.current;- const cx = box.left + box.width / 2 - was.x;- const cy = box.top + box.height / 2 - was.y;+ const cx = host.left + el.offsetLeft + el.offsetWidth / 2;+ const cy = host.top + el.offsetTop + el.offsetHeight / 2;const [dx, dy] = [sx - cx, sy - cy];const px = (dx - was.x) / was.k;const py = (dy - was.y) / was.k;const next = Math.max(1, Math.min(5, k));- setLens(bound(next, dx - next * px, dy - next * py));+ paint(bound(next, dx - next * px, dy - next * py), glide);};useEffect(() => {- unzoom();+ unzoom(false);setSharp(null);}, [shown?.id]);// The whole picture, not the screen-sized one, as Photos shows a photo: fetched as soon as@@ -680,7 +740,7 @@ export function PhotosView() {const wheel = (e: WheelEvent) => {if (!e.ctrlKey && !e.metaKey) return;e.preventDefault();- zoomAt(lensRef.current.k * Math.exp(-e.deltaY * 0.01), e.clientX, e.clientY);+ zoomAt(lensRef.current.k * Math.exp(-e.deltaY * 0.01), e.clientX, e.clientY, false);};el.addEventListener("wheel", wheel, { passive: false });return () => el.removeEventListener("wheel", wheel);@@ -741,6 +801,7 @@ export function PhotosView() {* Favorite, Delete and Recover show at once, as on the phone; Apple's answer only matters if* it refuses, which puts the photo back as it was and says why.*/+ const [ask, asking] = useAsk();const change = (p: Photo, flag: Flag, on: boolean) => changeAll([p], flag, on);const changeAll = async (list: Photo[], flag: Flag, on: boolean) => {if (list.length === 0) return;@@ -748,25 +809,38 @@ export function PhotosView() {// Asked first, in icloud.com's words: a delete reaches every device.if (flag === "deleted" && on &&- !window.confirm(- `${n === 1 ? "Delete this photo?" : `Delete ${n} photos?`}\n\n${n === 1 ? "It" : "They"} will be deleted from iCloud Photos on all your devices. ${n === 1 ? "It stays" : "They stay"} in Recently Deleted for 30 days.`,- )+ !(await ask({+ title: n === 1 ? "Delete this photo?" : `Delete ${n} photos?`,+ body: `${n === 1 ? "It" : "They"} will be deleted from iCloud Photos on all your devices. ${n === 1 ? "It stays" : "They stay"} in Recently Deleted for 30 days.`,+ action: "Delete",+ danger: true,+ symbol: "trash",+ }))) {return;}// For good, in Photos' words: it cannot be undone.if (flag === "expunged" &&- !window.confirm(- `${n === 1 ? "Are you sure you want to delete this item permanently?" : `Are you sure you want to delete these ${n} items permanently?`}\n\nThis action cannot be undone.`,- )+ !(await ask({+ title: n === 1 ? "Are you sure you want to delete this item permanently?" : `Are you sure you want to delete these ${n} items permanently?`,+ body: "This action cannot be undone.",+ action: "Delete",+ danger: true,+ symbol: "trash",+ }))) {return;}// Hiding asks too, in Photos' words: where the photos go.if (flag === "hidden" && on &&- !window.confirm(`${n === 1 ? "Hide this photo?" : `Hide ${n} photos?`}\n\n${n === 1 ? "It" : "They"} will be hidden from your library, and can be found in the Hidden album.`)+ !(await ask({+ title: n === 1 ? "Hide this photo?" : `Hide ${n} photos?`,+ body: `${n === 1 ? "It" : "They"} will be hidden from your library, and can be found in the Hidden album.`,+ action: "Hide",+ symbol: "hide",+ }))) {return;}@@ -794,7 +868,8 @@ export function PhotosView() {});}try {- for (const p of list) await api.photoSetFlag(p.id, flag, on);+ // 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);read().catch(() => {});} catch (e) {setPhotos(before);@@ -838,10 +913,16 @@ export function PhotosView() {const deleteAlbum = async (a: PhotoAlbum) => {// A folder, in icloud.com's words: it goes with every album in it.- const words = a.folder- ? `Delete the folder “${a.name}”?\n\nThis will also delete all albums inside this folder. The photos in them stay in your library.`- : `Delete the album “${a.name}”?\n\nThe photos in it stay in your library.`;- if (!window.confirm(words)) return;+ const sure = await ask({+ title: a.folder ? `Delete the folder “${a.name}”?` : `Delete the album “${a.name}”?`,+ body: a.folder+ ? "This will also delete all albums inside this folder. The photos in them stay in your library."+ : "The photos in it stay in your library.",+ action: "Delete",+ danger: true,+ symbol: "trash",+ });+ if (!sure) return;const before = albums;// Everything under a folder goes with it, here as on iCloud.const gone = new Set([a.id]);@@ -882,7 +963,12 @@ export function PhotosView() {const removeFrom = async (gone: Photo[]) => {if (!album) return;const n = gone.length;- if (!window.confirm(`Remove ${n === 1 ? "this photo" : `${n} photos`} from the album?\n\n${n === 1 ? "It stays" : "They stay"} in your library.`)) return;+ const sure = await ask({+ title: `Remove ${n === 1 ? "this photo" : `${n} photos`} from the album?`,+ body: `${n === 1 ? "It stays" : "They stay"} in your library.`,+ action: "Remove",+ });+ if (!sure) return;const before = photos;const ids = new Set(gone.map((p) => p.id));setPhotos((list) => (list ?? []).filter((x) => !ids.has(x.id)));@@ -907,8 +993,9 @@ export function PhotosView() {const p = photos?.[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; past that it opens and the whole picture follows.- if (p.kind !== "video") await Promise.race([warm(p.id), new Promise((r) => window.setTimeout(r, 400))]);+ // waited on for longer than a blink (a click must answer at once); past that it opens on+ // its thumbnail and screen-sized picture, and the whole one follows.+ if (p.kind !== "video") await Promise.race([warm(p.id), new Promise((r) => window.setTimeout(r, 150))]);stopClosing();const tile = document.querySelector<HTMLElement>(`.px-tile[data-id="${CSS.escape(p.id)}"]`);origin.current = tile?.getBoundingClientRect() ?? null;@@ -2034,9 +2121,27 @@ export function PhotosView() {photoMenu(shown, { x: e.clientX, y: e.clientY, alignRight: false });}}>- {shown.kind === "video" ? (- // A still of the video, and Play opens it in this computer's own player: the- // window's engine plays nothing without codec plugins many systems lack.+ {shown.kind === "video" && videoBase && !unplayable.has(shown.id) ? (+ // Played here, as Photos plays one: from the disk cache, in the pieces the+ // player asks for, so it starts at once and seeks anywhere.+ <div className="px-video">+ <video+ key={shown.id}+ className="px-shown"+ src={`${videoBase}/${shown.id}/original`}+ poster={pictureSrc(shown.id, "medium")}+ aria-label={shown.filename ?? "Video"}+ controls+ autoPlay+ playsInline+ preload="auto"+ style={fitted(shown)}+ onError={() => setUnplayable((was) => new Set(was).add(shown.id))}+ />+ </div>+ ) : 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">@@ -2046,9 +2151,8 @@ export function PhotosView() {) : (<divref={pan}- className={`px-pan${lens.k > 1 ? " is-zoomed" : ""}`}- style={{ transform: lens.k > 1 ? `translate(${lens.x}px, ${lens.y}px) scale(${lens.k})` : undefined }}- onDoubleClick={(e) => (lens.k > 1 ? unzoom() : zoomAt(2.5, e.clientX, e.clientY))}+ className={`px-pan${zoomed ? " is-zoomed" : ""}`}+ onDoubleClick={(e) => (lensRef.current.k > 1 ? unzoom() : zoomAt(2.5, e.clientX, e.clientY))}onPointerDown={(e) => {if (lensRef.current.k <= 1 || e.button !== 0) return;e.currentTarget.setPointerCapture(e.pointerId);@@ -2057,14 +2161,14 @@ export function PhotosView() {onPointerMove={(e) => {const d = dragging.current;if (!d) return;- setLens(bound(lensRef.current.k, d.lx + e.clientX - d.x, d.ly + e.clientY - d.y));+ paint(bound(lensRef.current.k, d.lx + e.clientX - d.x, d.ly + e.clientY - d.y));}}onPointerUp={() => (dragging.current = null)}onPointerCancel={() => (dragging.current = null)}>{decodedFull.has(shown.id) ? (// Already whole and decoded: drawn at once, at full quality, alone.- <img key={`${shown.id}-whole`} className="px-shown" src={pictureSrc(shown.id, "full")} alt={shown.filename ?? ""} decoding="sync" draggable={false} style={fitted(shown)} />+ <img key={`${shown.id}-whole`} className="px-shown" src={pictureSrc(shown.id, "full")} alt={shown.filename ?? ""} decoding="async" draggable={false} style={fitted(shown)} />) : (<img key={shown.id} className="px-shown" src={pictureSrc(shown.id, "medium")} alt={shown.filename ?? ""} decoding="async" draggable={false} style={fitted(shown)} />)}@@ -2231,6 +2335,7 @@ export function PhotosView() {</p>)}{menu && <RowMenu at={menu.at} entries={menu.entries} onClose={() => setMenu(null)} />}+ {asking}{/* Drawn at the top of the page: inside the screen, whose content moves by a transform,"fixed" was fixed to the screen and a slideshow played inside a box, not the window. */}{show && (diff --git a/src/screens/photos/Ask.tsx b/src/screens/photos/Ask.tsxnew file mode 100644index 0000000..b431e09--- /dev/null+++ b/src/screens/photos/Ask.tsx@@ -0,0 +1,73 @@+/**+ * A question before a change that reaches every device, as icloud.com's Photos asks it: a+ * sheet over the dimmed window — a symbol, the question in bold, a line on what follows, and+ * Cancel beside the action, red when it destroys. Escape or a click outside cancels; Cancel+ * has the focus, so Return never deletes by accident.+ */+import { useCallback, useRef, useState } from "react";+import { EyeOff, Trash2 } from "lucide-react";+import { Portal } from "../../components/Portal";++export type Question = {+ title: string;+ body: string;+ action: string;+ /** Red, and the trash symbol: a delete. */+ danger?: boolean;+ symbol?: "trash" | "hide";+};++export function useAsk(): [(q: Question) => Promise<boolean>, React.ReactNode] {+ const [asking, setAsking] = useState<Question | null>(null);+ const answer = useRef<((yes: boolean) => void) | null>(null);+ const ask = useCallback(+ (q: Question) =>+ new Promise<boolean>((resolve) => {+ answer.current?.(false);+ answer.current = resolve;+ setAsking(q);+ }),+ [],+ );+ const done = (yes: boolean) => {+ answer.current?.(yes);+ answer.current = null;+ setAsking(null);+ };+ const sheet = asking && (+ <Portal>+ <div className="modal-veil" onClick={() => done(false)}>+ <div+ className="modal-sheet px-ask"+ role="alertdialog"+ aria-modal="true"+ aria-label={asking.title}+ onClick={(e) => e.stopPropagation()}+ onKeyDown={(e) => {+ if (e.key === "Escape") {+ e.stopPropagation();+ done(false);+ }+ }}+ >+ {asking.symbol && (+ <span className={`px-ask-symbol${asking.danger ? " is-danger" : ""}`} aria-hidden="true">+ {asking.symbol === "trash" ? <Trash2 size={30} strokeWidth={1.6} /> : <EyeOff size={30} strokeWidth={1.6} />}+ </span>+ )}+ <h2>{asking.title}</h2>+ <p>{asking.body}</p>+ <div className="px-ask-actions">+ <button autoFocus onClick={() => done(false)}>+ Cancel+ </button>+ <button className={`is-act${asking.danger ? " danger" : ""}`} onClick={() => done(true)}>+ {asking.action}+ </button>+ </div>+ </div>+ </div>+ </Portal>+ );+ return [ask, sheet];+}diff --git a/src/screens/photos/Slideshow.tsx b/src/screens/photos/Slideshow.tsxindex d4818e7..ad94b60 100644--- a/src/screens/photos/Slideshow.tsx+++ b/src/screens/photos/Slideshow.tsx@@ -27,10 +27,14 @@ export function Slideshow({ photos, start, onClose }: { photos: Photo[]; start:return () => window.clearTimeout(t);}, [at, playing, go, photos.length]);- // The next picture is fetched now, so it is there when its turn comes.+ // The next picture is fetched and decoded now, whole, so it is there when its turn comes.useEffect(() => {const next = photos[(at + 1) % photos.length];- if (next) new Image().src = pictureSrc(next.id, "medium");+ if (!next || next.kind === "video") return;+ const img = new Image();+ img.decoding = "async";+ img.src = pictureSrc(next.id, "full");+ void img.decode().catch(() => undefined);}, [at, photos]);useEffect(() => {@@ -86,12 +90,27 @@ export function Slideshow({ photos, start, onClose }: { photos: Photo[]; start:{before !== null && photos[before] && (<img key={`b${photos[before].id}`} className="px-slide is-leaving" src={pictureSrc(photos[before].id, "medium")} alt="" />)}+ {before !== null && photos[before] && photos[before].kind !== "video" && (+ <img key={`bw${photos[before].id}`} className="px-slide is-leaving" src={pictureSrc(photos[before].id, "full")} alt="" aria-hidden="true" />+ )}<imgkey={`a${photo.id}-${at}`}className={`px-slide${playing ? "" : " is-paused"}`}src={pictureSrc(photo.id, "medium")}alt={photo.filename ?? "Photo"}/>+ {/* The screen-sized copy is soft on a large screen; the whole picture covers it, moving+ with it on the same clock. */}+ {photo.kind !== "video" && (+ <img+ key={`w${photo.id}-${at}`}+ className={`px-slide${playing ? "" : " is-paused"}`}+ src={pictureSrc(photo.id, "full")}+ alt=""+ aria-hidden="true"+ decoding="async"+ />+ )}<div className="px-show-bar px-capsule" role="toolbar" aria-label="Slideshow controls"><button className="px-cap" aria-label="Previous" onClick={() => go(-1)}><ChevronLeft size={18} />diff --git a/src/styles/photos.css b/src/styles/photos.cssindex 6d4d066..b549790 100644--- a/src/styles/photos.css+++ b/src/styles/photos.css@@ -322,11 +322,14 @@.px-viewer-when strong { font-size: var(--t-13); font-weight: 600; }.px-viewer-when span { color: var(--text-2); font-size: var(--t-11); }.px-cap[aria-pressed="true"] { background: color-mix(in srgb, var(--text) 12%, transparent); }-.px-stage { position: relative; display: grid; place-items: center; min-width: 0; min-height: 0; overflow: hidden; padding: 62px 64px 70px; }+.px-stage { position: relative; display: grid; place-items: center; min-width: 0; min-height: 0; overflow: hidden; padding: 62px 64px 70px; container-type: size; }.px-stage img, .px-stage video { max-width: 100%; max-height: 100%; object-fit: contain; }/* The photo's frame: what zooms and pans. The full picture lies over the screen-sized one,faded in once loaded, so zooming never shows a blank. */-.px-pan { position: relative; display: grid; transform-origin: center; will-change: transform; }+/* No standing will-change on the picture: it pins the layer's bitmap at the scale it was first+ drawn at, so a resized window or the zoom from a tile left it soft. The animations promote+ it themselves while they run, and it is drawn sharp again when they end. */+.px-pan { position: relative; display: grid; transform-origin: center; }.px-pan.is-zoomed { cursor: grab; }.px-pan.is-zoomed:active { cursor: grabbing; }.px-pan > img { grid-area: 1 / 1; }@@ -346,7 +349,7 @@}.px-sharp.is-in { opacity: 1; }/* The thumbnail, already on disk, fills the photo's box until the sharper picture covers it. */-.px-shown { background-size: 100% 100%; transform-origin: center; will-change: transform; }+.px-shown { background-size: 100% 100%; transform-origin: center; }.px-nav {position: absolute;top: 50%;@@ -410,6 +413,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-play {position: absolute;display: grid;@@ -452,7 +456,6 @@object-fit: contain;transform-origin: 50% 45%;animation: px-arrive 900ms ease-out both, px-drift 4900ms linear both;- will-change: transform, opacity;}.px-slide.is-leaving { animation: none; transform: scale(1.06); z-index: -1; }.px-slide.is-paused { animation-play-state: paused; }@@ -877,3 +880,26 @@.px-albums .px-parent-row.px-depth .px-twisty { left: calc(10px + var(--depth, 0) * 14px); }.px-albums .px-parent-row.px-depth .px-parent { padding-left: calc(30px + var(--depth, 0) * 14px); }.px-card.is-folder .px-card-pic { color: var(--accent); }++/* ---- a question before a change, as icloud.com's Photos asks it: centred, a symbol over the+ question in bold, one quiet line, Cancel and the action side by side and equal ----------- */+.px-ask { width: min(400px, 92vw); align-items: center; text-align: center; gap: 10px; padding: 26px 30px 26px; }+.px-ask-symbol { display: grid; place-items: center; color: var(--accent); margin-bottom: 4px; }+.px-ask-symbol.is-danger { color: var(--accent); }+.px-ask h2 { white-space: normal; font-size: var(--t-17); font-weight: 700; line-height: 1.3; text-wrap: balance; }+.px-ask p { margin: 0; font-size: var(--t-13); color: var(--text-2, color-mix(in srgb, var(--text) 70%, transparent)); text-wrap: balance; }+.px-ask-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; width: 100%; margin-top: 14px; }+.px-ask-actions button {+ height: 36px;+ border: 0;+ border-radius: 9px;+ font: inherit;+ font-size: var(--t-15, 15px);+ font-weight: 500;+ color: var(--text);+ background: color-mix(in srgb, var(--text) 12%, transparent);+}+.px-ask-actions button:hover { background: color-mix(in srgb, var(--text) 17%, transparent); }+.px-ask-actions button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+.px-ask-actions .is-act { color: var(--accent); }+.px-ask-actions .is-act.danger { color: var(--danger); }