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.

Photos: no flicker, full-quality HEIC, bursts and Live Photos, never stuck

Yashwanth Kamireddi0b109ad5d965
diff --git a/.uiverify/photos-burst-live.mjs b/.uiverify/photos-burst-live.mjs
new file mode 100644
index 0000000..690f0a7
--- /dev/null
+++ b/.uiverify/photos-burst-live.mjs
@@ -0,0 +1,74 @@
+// A burst shows as its chosen photo; in the viewer its BURST mark goes through all of it —
+// "Burst · 2 of 3" — and Done (or closing) brings the library back on the chosen one. A Live
+// Photo's LIVE mark plays its moving part over the still while the pointer rests on it.
+import http from "node:http";
+import fs from "node:fs";
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+// The moving part: a short clip from a server of the app's kind.
+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 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;
+ // p2 is a burst's chosen photo (of 3), p4 a Live Photo.
+ window.__photoExtra = { p2: { burst: "B1", burstPick: true, burstCount: 3 }, p4: { kind: "live" } };
+}, 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++; };
+const tiles = () => page.locator(".px-tile").count();
+const before = await tiles();
+
+await page.locator('.px-tile[data-id="p2"]').dblclick();
+await page.waitForTimeout(600);
+const burst = page.getByRole("button", { name: /View all 3 photos in this burst/ });
+ok((await burst.count()) === 1 && /BURST/.test(await burst.innerText()), "a burst's chosen photo is marked BURST, with how many it holds");
+await burst.click();
+await page.waitForTimeout(400);
+ok(/Burst · 2 of 3/.test(await page.locator(".px-mark.is-burst").innerText()), "BURST goes through the burst: the chosen one is 2 of 3");
+await page.keyboard.press("ArrowLeft");
+await page.waitForTimeout(250);
+ok(/1 of 3/.test(await page.locator(".px-mark.is-burst").innerText()) && /p2-s0/.test(decodeURIComponent(await page.locator(".px-stage .px-shown").getAttribute("src"))),
+ "the arrows step through its shots");
+await page.getByRole("button", { name: "Done" }).click();
+await page.waitForTimeout(500);
+ok((await page.locator(".px-mark.is-burst").count()) === 0 && /p2/.test(decodeURIComponent(await page.locator(".px-stage .px-shown").getAttribute("src"))) && !/p2-s/.test(decodeURIComponent(await page.locator(".px-stage .px-shown").getAttribute("src"))),
+ "Done brings the library back, on the chosen photo");
+// Into the burst again, then closing the viewer: the library is whole again behind it.
+await page.getByRole("button", { name: /View all 3 photos/ }).click();
+await page.waitForTimeout(300);
+await page.keyboard.press("Escape");
+await page.waitForTimeout(900);
+ok((await page.locator(".px-viewer").count()) === 0 && (await tiles()) === before && (await page.locator('.px-tile[data-id^="p2-s"]').count()) === 0,
+ `closing inside a burst leaves the library as it was (${await tiles()} tiles)`);
+
+// A Live Photo: LIVE, and resting on it plays the moving part over the still.
+await page.locator('.px-tile[data-id="p4"]').dblclick();
+await page.waitForTimeout(600);
+const live = page.getByRole("button", { name: "Play Live Photo" });
+ok((await live.count()) === 1 && /LIVE/.test(await live.innerText()), "a Live Photo is marked LIVE");
+await live.hover();
+await page.waitForTimeout(200);
+const v = page.locator(".px-pan video.px-live");
+ok((await v.count()) === 1 && (await v.getAttribute("src")) === `${base}/p4/video`, `resting on LIVE plays its moving part over the still ${await v.getAttribute("src").catch(() => "")}`);
+await page.keyboard.press("ArrowRight");
+await page.waitForTimeout(250);
+ok((await page.locator("video.px-live").count()) === 0, "and it stops when the photo changes");
+await b.close();
+server.close();
+process.exitCode = failures ? 1 : (process.exitCode ?? 0);
diff --git a/.uiverify/photos-close.mjs b/.uiverify/photos-close.mjs
index 7ab8971..5d5c7c2 100644
--- a/.uiverify/photos-close.mjs
+++ b/.uiverify/photos-close.mjs
@@ -1,6 +1,7 @@
-// Closing a photo never flashes it: frame by frame the photo only shrinks back into its tile,
-// and no frame after it arrives shows it larger again before the viewer is gone. (WebKit drew
-// the photo at full size for one frame as the animation ended — a whole-window flash.)
+// A photo opens and closes at once — no animation at all, nothing moving or fading to flicker:
+// the viewer is there the frame after a double-click and gone the frame after Escape; nothing
+// on the page animates; the grid is painted again the moment the viewer goes, no tile left
+// hidden. The window's own colour follows what fills its edges.
import { engine } from "./engine.mjs";
import { SERVICES, installStub, openScreen } from "./stub.mjs";
const b = await engine.launch();
@@ -15,78 +16,49 @@ let failures = 0;
const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
for (const round of [1, 2]) {
- await page.locator(".px-tile").nth(round).dblclick();
- await page.waitForTimeout(700);
- const trace = await page.evaluate(() => new Promise((resolve) => {
+ const trace = await page.evaluate((n) => new Promise((resolve) => {
const frames = [];
+ let at = null;
+ const t0 = performance.now();
const tick = () => {
- const v = document.querySelector(".px-viewer");
- const p = document.querySelector(".px-pan, .px-video");
- if (!v || !p) { frames.push(null); return resolve(frames); }
- const shown = getComputedStyle(v).visibility !== "hidden";
- frames.push(shown ? Math.round(p.getBoundingClientRect().width) : 0);
- if (frames.length < 120) requestAnimationFrame(tick); else resolve(frames);
+ frames.push({
+ t: Math.round(performance.now() - t0),
+ viewer: !!document.querySelector(".px-viewer"),
+ animating: document.getAnimations().filter((a) => a.playState === "running").length,
+ gridHidden: getComputedStyle(document.querySelector(".px-scroll")).visibility === "hidden",
+ lifted: document.querySelectorAll("[data-lifted]").length,
+ });
+ if (performance.now() - t0 < 1400) requestAnimationFrame(tick); else resolve({ frames, at });
};
- window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
requestAnimationFrame(tick);
- }));
- const seen = trace.filter((w) => w !== null && w > 0);
- const grew = seen.some((w, i) => i > 0 && w > seen[i - 1] + 1);
- ok(!grew && trace.at(-1) === null, `close ${round}: the photo only shrinks, then the viewer is gone — no frame drawn larger ${JSON.stringify(seen)}`);
- await page.waitForTimeout(300);
+ document.querySelectorAll(".px-tile")[n].dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
+ setTimeout(() => { at = Math.round(performance.now() - t0); window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); }, 700);
+ }), round);
+ const f = trace.frames;
+ const opened = f.findIndex((x) => x.viewer);
+ const afterClose = f.filter((x) => x.t > trace.at);
+ const closedIn = afterClose.findIndex((x) => !x.viewer);
+ ok(opened >= 0 && opened <= 12, `open ${round}: the viewer is there at once (frame ${opened})`);
+ ok(closedIn >= 0 && closedIn <= 2, `close ${round}: and gone at once (${closedIn} frames after Escape)`);
+ ok(f.every((x) => x.animating === 0), `${round}: nothing animates as a photo opens or closes (max ${Math.max(...f.map((x) => x.animating))})`);
+ const gone = afterClose.slice(closedIn);
+ ok(gone.length > 0 && gone.every((x) => !x.gridHidden && x.lifted === 0), `${round}: the grid is painted again and whole the moment it goes`);
+ await page.waitForTimeout(200);
}
-// No frame can flash however the engine starts or ends an animation: the backdrop's own
-// style is its first frame (hidden) the moment the viewer appears, its last (shown) once the
-// fade runs; closing, its own style is gone (hidden) while it fades out.
-const own = await page.evaluate(() => new Promise((resolve) => {
- const seen = {};
- new MutationObserver((_, mo) => {
- const bd = document.querySelector(".px-backdrop");
- if (bd && seen.first === undefined) {
- seen.first = bd.style.opacity;
- mo.disconnect();
- document.getAnimations().forEach((a) => a.ready.then(() => { seen.running = bd.style.opacity; }));
- setTimeout(() => resolve(seen), 400);
- }
- }).observe(document.body, { childList: true, subtree: true });
- document.querySelectorAll(".px-tile")[2].dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
-}));
-ok(own.first === "0" && own.running === "1", `opening: the backdrop's own style is hidden before its fade, shown once it runs ${JSON.stringify(own)}`);
-await page.waitForTimeout(500);
-const closingOwn = await page.evaluate(() => new Promise((resolve) => {
- window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
- const bd = document.querySelector(".px-backdrop");
- Promise.all(bd.getAnimations().map((a) => a.ready)).then(() => resolve(bd.style.opacity));
-}));
-ok(closingOwn === "0", `closing: its own style is already gone while it fades ${JSON.stringify(closingOwn)}`);
-await page.waitForTimeout(700);
// The window's own colour follows what fills its edges, so a resize shows no lighter band.
const rgb = (sel) => page.evaluate((s) => /(\d+), (\d+), (\d+)/.exec(getComputedStyle(document.querySelector(s)).backgroundColor).slice(1).join(","), sel);
const body = await rgb("body");
ok((await page.evaluate(() => window.__tints?.at(-1))) === body, `the window is the app's colour ${body}`);
await page.locator(".px-tile").nth(1).dblclick();
-await page.waitForTimeout(600);
+await page.waitForTimeout(300);
const backdrop = await rgb(".px-backdrop");
ok((await page.evaluate(() => window.__tints.at(-1))) === backdrop, `the viewer's own colour while a photo is open ${backdrop}`);
await page.keyboard.press("Escape");
-await page.waitForTimeout(600);
+await page.waitForTimeout(300);
ok((await page.evaluate(() => window.__tints.at(-1))) === body, "and the app's colour again once it closes");
-
-// Opened again at once after a close: shown, not left hidden.
await page.locator(".px-tile").nth(1).dblclick();
-await page.waitForTimeout(600);
+await page.waitForTimeout(300);
ok(await page.locator(".px-viewer").evaluate((v) => getComputedStyle(v).visibility === "visible" && getComputedStyle(v.querySelector(".px-backdrop")).opacity === "1"), "a photo opened again is fully shown");
-// In dark, the viewer's near-black: the band a resize shows is never lighter than the photo's surround.
-const dark = await b.newContext({ viewport: { width: 1280, height: 800 }, colorScheme: "dark" });
-await dark.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });
-const dp = await dark.newPage();
-await dp.goto("http://localhost:4173", { waitUntil: "networkidle" });
-await openScreen(dp, "Photos");
-await dp.waitForTimeout(400);
-await dp.locator(".px-tile").nth(1).dblclick();
-await dp.waitForTimeout(600);
-const tint = await dp.evaluate(() => window.__tints.at(-1));
-ok(tint.split(",").every((v) => Number(v) < 20), `in dark, the window goes near-black with the viewer ${tint}`);
await b.close();
process.exitCode = failures ? 1 : (process.exitCode ?? 0);
diff --git a/.uiverify/photos-jump.mjs b/.uiverify/photos-jump.mjs
new file mode 100644
index 0000000..9374818
--- /dev/null
+++ b/.uiverify/photos-jump.mjs
@@ -0,0 +1,51 @@
+// Going to a month, as icloud.com's calendar button does: years down the side, the year's
+// months as tiles with a photo each in calendar order; a tile takes the grid to that month.
+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: 700 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });
+// A library across two years, a few photos a month.
+await ctx.addInitScript(() => {
+ const P = (i, t) => ({ id: `j${i}`, master: `mj${i}`, takenAt: t, addedAt: t, kind: "image", width: 4032, height: 3024, duration: null, filename: `IMG_${i}.JPG`, size: 1, uti: "public.jpeg", favorite: false, hidden: false, deleted: false, deletedAt: null, subtype: 0, changeTag: null });
+ const out = [];
+ let i = 0;
+ for (let m = 0; m < 20; m++) for (let k = 0; k < 9; k++) out.push(P(i++, Date.UTC(2026, 9 - m, 20 - k) / 1000));
+ window.__photos = out;
+});
+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(500);
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+
+await page.getByRole("button", { name: "Go to a Month" }).click();
+await page.waitForTimeout(250);
+const dialog = page.getByRole("dialog", { name: "Go to a month" });
+ok((await dialog.count()) === 1, "the calendar button opens the month picker");
+ok(JSON.stringify(await dialog.getByRole("tab").allInnerTexts()) === JSON.stringify(["2026", "2025"]), `years down the side, newest first ${await dialog.getByRole("tab").allInnerTexts()}`);
+const months2026 = await dialog.locator(".px-jump-month span").allInnerTexts();
+ok(months2026.join() === "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct", `the year's months in calendar order, each with a photo ${months2026}`);
+await dialog.getByRole("tab", { name: "2025" }).click();
+ok((await dialog.locator(".px-jump-month span").allInnerTexts()).join() === "Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec", "another year shows its own months");
+await dialog.getByRole("button", { name: "June 2025" }).click();
+// A smooth scroll, however far: settled once the scroller stops moving.
+await page.locator(".px-scroll").evaluate((el) => new Promise((done) => {
+ let last = -1, still = 0;
+ const tick = () => { if (el.scrollTop === last) still++; else { still = 0; last = el.scrollTop; } if (still > 8) done(); else requestAnimationFrame(tick); };
+ tick();
+}));
+const top = await page.evaluate(() => {
+ const s = document.querySelector(".px-scroll").getBoundingClientRect();
+ const m = document.querySelector('.px-month[aria-label="June 2025"]').getBoundingClientRect();
+ return Math.round(m.top - s.top);
+});
+ok((await dialog.count()) === 0 && Math.abs(top) <= 8, `a month takes the grid there (its heading ${top}px from the top)`);
+await page.getByRole("button", { name: "Go to a Month" }).click();
+await page.waitForTimeout(200);
+await page.keyboard.press("Escape");
+ok((await page.getByRole("dialog", { name: "Go to a month" }).count()) === 0, "Escape closes it");
+await b.close();
+process.exitCode = failures ? 1 : (process.exitCode ?? 0);
diff --git a/.uiverify/photos-loading.mjs b/.uiverify/photos-loading.mjs
new file mode 100644
index 0000000..b7b4a56
--- /dev/null
+++ b/.uiverify/photos-loading.mjs
@@ -0,0 +1,50 @@
+// The app never looks stuck: a view whose photos are slow to come has its title up at once and
+// its tiles as plain boxes until they do; one that comes quickly shows no boxes at all (nothing
+// to flash); and a month far down, not built yet, is plain boxes, never an empty page.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const b = await engine.launch();
+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });
+await ctx.addInitScript(() => {
+ const P = (i, t) => ({ id: `l${i}`, master: `ml${i}`, takenAt: t, addedAt: t, kind: "image", width: 4032, height: 3024, duration: null, filename: `I${i}`, size: 1, uti: "public.jpeg", favorite: i % 3 === 0, hidden: false, deleted: false, deletedAt: null, subtype: 0, changeTag: null });
+ const out = []; let i = 0;
+ for (let m = 0; m < 30; m++) for (let k = 0; k < 14; k++) out.push(P(i++, Date.UTC(2026, 9 - m, 20 - k) / 1000));
+ window.__photos = out;
+});
+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(500);
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+
+// A month far down, not built: boxes, laid out on the grid.
+const far = await page.evaluate(() => {
+ const later = [...document.querySelectorAll(".px-later")];
+ return { months: later.length, boxes: later.reduce((n, l) => n + l.querySelectorAll(".px-ph").length, 0) };
+});
+ok(far.months > 0 && far.boxes === far.months * 14, `months not yet built show their tiles as boxes (${far.months} months, ${far.boxes} boxes)`);
+
+// A slow view: title at once, boxes, then the photos.
+await page.evaluate(() => { window.__slowView = "favorites"; });
+await page.locator(".px-source", { hasText: "Favorites" }).first().click();
+await page.waitForTimeout(250);
+ok((await page.locator(".px-bar h1").innerText()) === "Favorites" && (await page.locator(".px-month[aria-busy] .px-ph").count()) > 0 && (await page.locator(".px-tile").count()) === 0,
+ "a slow view has its title up at once and its tiles as boxes, not the last view's photos");
+await page.waitForTimeout(700);
+ok((await page.locator(".px-month[aria-busy]").count()) === 0 && (await page.locator(".px-tile").count()) > 0, "and its photos take their place when they come");
+
+// A quick view: never a box, frame by frame.
+await page.evaluate(() => { window.__slowView = null; });
+const boxed = await page.evaluate(() => new Promise((resolve) => {
+ let seen = false;
+ const t0 = performance.now();
+ const tick = () => { if (document.querySelector(".px-month[aria-busy]")) seen = true; if (performance.now() - t0 < 600) requestAnimationFrame(tick); else resolve(seen); };
+ requestAnimationFrame(tick);
+ [...document.querySelectorAll(".px-source")].find((e) => /Library/.test(e.textContent)).click();
+}));
+ok(!boxed, "a view that comes quickly never shows the boxes — nothing flashes");
+await b.close();
+process.exitCode = failures ? 1 : (process.exitCode ?? 0);
diff --git a/.uiverify/photos-narrow.mjs b/.uiverify/photos-narrow.mjs
new file mode 100644
index 0000000..3607287
--- /dev/null
+++ b/.uiverify/photos-narrow.mjs
@@ -0,0 +1,47 @@
+// Any window size, as a Mac app keeps its toolbar: the title whole (never squeezed to a letter),
+// its dates on one line, the controls together beside it or under it, and the first photos
+// below all of it — never under it. Recently Deleted is one grid, never the same month again.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+for (const [w, h] of [[1280, 800], [900, 700], [760, 700], [560, 700]]) {
+ const ctx = await b.newContext({ viewport: { width: w, height: h } });
+ 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}`); failures++; });
+ await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+ await openScreen(page, "Photos");
+ await page.waitForTimeout(500);
+ for (const view of ["Library", "Favorites"]) {
+ await page.locator(".px-source", { hasText: view }).first().click();
+ await page.waitForTimeout(300);
+ const r = await page.evaluate(() => {
+ const t = document.querySelector(".px-bar h1"), span = document.querySelector(".px-bar .px-span");
+ const bar = document.querySelector(".px-bar").getBoundingClientRect();
+ const first = document.querySelector(".px-month-title, .px-tile, .px-empty, .px-scroll > *")?.getBoundingClientRect();
+ const tools = [...document.querySelectorAll(".px-tools > *")].map((e) => e.getBoundingClientRect().top);
+ return {
+ whole: t.scrollWidth <= t.clientWidth + 1 && t.clientWidth > 40,
+ oneLine: !span || span.getBoundingClientRect().height < 24,
+ clear: !first || first.top >= bar.bottom - 1,
+ rows: new Set(tools.map((x) => Math.round(x / 10))).size,
+ };
+ });
+ ok(r.whole && r.oneLine && r.clear, `${w}px ${view}: title whole, dates on one line, photos clear of the header ${JSON.stringify(r)}`);
+ }
+ await ctx.close();
+}
+// Recently Deleted: one grid in the order things were deleted, no month headings to repeat.
+const ctx = await b.newContext({ viewport: { width: 900, height: 700 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });
+const page = await ctx.newPage();
+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await openScreen(page, "Photos");
+await page.waitForTimeout(400);
+await page.locator(".px-source", { hasText: "Recently Deleted" }).click();
+await page.waitForTimeout(300);
+ok((await page.locator(".px-month-title").count()) === 0 && (await page.locator(".px-tile").count()) > 0, "Recently Deleted is one grid, with no month headings to repeat");
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/photos-quality.mjs b/.uiverify/photos-quality.mjs
index 1704942..186132a 100644
--- a/.uiverify/photos-quality.mjs
+++ b/.uiverify/photos-quality.mjs
@@ -16,13 +16,13 @@ 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 shown = () => page.locator(".px-stage .px-shown").getAttribute("src");
+const shown = () => page.locator(".px-stage .px-shown").getAttribute("data-picture");
await page.locator(".px-tile").nth(0).dblclick();
await page.waitForTimeout(80);
const enough = () => page.evaluate(() => {
const img = document.querySelector(".px-stage .px-shown");
- const step = Number(/fit(\d+)/.exec(decodeURIComponent(img.getAttribute("src")))?.[1] ?? 0);
+ const step = Number(/fit(\d+)/.exec(decodeURIComponent(img.getAttribute("data-picture")))?.[1] ?? 0);
// Its laid-out size, not its box on screen: that is still growing as the viewer opens.
const long = Math.max(img.offsetWidth, img.offsetHeight) * devicePixelRatio;
return step >= long - 1 && step < long * 2;
diff --git a/.uiverify/photos-show.mjs b/.uiverify/photos-show.mjs
index af9a334..b749c2b 100644
--- a/.uiverify/photos-show.mjs
+++ b/.uiverify/photos-show.mjs
@@ -29,11 +29,23 @@ ok((await count()) === "3 of 5", `and goes on by itself "${await count()}"`);
await page.keyboard.press(" ");
await page.waitForTimeout(4400);
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.
await page.keyboard.press("ArrowRight");
+await page.waitForTimeout(150);
ok((await count()) === "4 of 5", "the right arrow steps on");
await page.keyboard.press("ArrowLeft");
+await page.waitForTimeout(150);
await page.keyboard.press("ArrowLeft");
+await page.waitForTimeout(150);
ok((await count()) === "2 of 5", "and the left back");
+// The one leaving dissolves away above the next (never left whole behind it), then is gone.
+await page.keyboard.press("ArrowRight");
+await page.waitForTimeout(250);
+const mid = await page.locator(".px-slide.is-leaving").evaluate((e) => Number(getComputedStyle(e).opacity)).catch(() => -1);
+await page.waitForTimeout(900);
+ok(mid > 0 && mid < 1 && (await page.locator(".px-slide.is-leaving").count()) === 0, `the photo leaving fades out over the next, then goes (opacity ${mid.toFixed?.(2)} mid-way)`);
+await page.keyboard.press("ArrowLeft");
+await page.waitForTimeout(150);
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-strip.mjs b/.uiverify/photos-strip.mjs
index 0626f89..4c44e78 100644
--- a/.uiverify/photos-strip.mjs
+++ b/.uiverify/photos-strip.mjs
@@ -48,7 +48,11 @@ const after = await which();
const ids = await page.evaluate(() => window.__photos.map((p) => p.id));
ok(ids.indexOf(after) - ids.indexOf(before) === 4, `scrolling over the strip skims through the photos (${ids.indexOf(before)} → ${ids.indexOf(after)})`);
ok((await centred()) <= 1, "and the strip keeps the shown one in the middle");
-ok(await page.locator(".px-slip").first().evaluate((e) => getComputedStyle(e).transform !== "none" && /transform/.test(getComputedStyle(e).transitionProperty)),
- "slips are placed and eased by transform");
+ok(await page.evaluate(() => [...document.querySelectorAll(".px-slip, .px-strip-run")].every((e) => {
+ const cs = getComputedStyle(e);
+ return cs.transitionDuration.split(",").every((d) => parseFloat(d) === 0);
+}) && document.getAnimations().filter((a) => a.playState === "running").length === 0),
+ "the strip and its slips move at once — nothing in it animates (animated, it flickered)");
+ok((await page.locator(".px-slip img[loading=lazy]").count()) === 0, "and every slip's picture is fetched at once, never lazily");
await b.close();
process.exitCode = failures ? 1 : (process.exitCode ?? 0);
diff --git a/.uiverify/photos.mjs b/.uiverify/photos.mjs
index ef95e7e..48f7f70 100644
--- a/.uiverify/photos.mjs
+++ b/.uiverify/photos.mjs
@@ -36,10 +36,10 @@ await page.waitForTimeout(200);
await page.locator(".px-tile").first().dblclick();
await page.waitForTimeout(150);
ok((await page.locator(".px-viewer").count()) === 1, "a photo opens in the viewer");
-const first = await page.locator(".px-stage .px-shown").getAttribute("src");
+const first = await page.locator(".px-stage .px-shown").getAttribute("data-picture");
await page.keyboard.press("ArrowRight");
await page.waitForTimeout(100);
-const second = await page.locator(".px-stage .px-shown").getAttribute("src");
+const second = await page.locator(".px-stage .px-shown").getAttribute("data-picture");
ok(first && second && first !== second && /fit\d+/.test(second), "the right arrow goes to the next photo, made the size the screen shows it");
await page.getByRole("button", { name: "Download" }).click();
await page.waitForTimeout(200);
@@ -56,7 +56,7 @@ ok(JSON.stringify(flags) === JSON.stringify(["p2:favorite:true", "p2:favorite:fa
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");
+const next = await page.locator(".px-stage .px-shown").first().evaluate((i) => i.getAttribute("data-picture") ?? i.getAttribute("src"));
ok(/p3|p4/.test(next ?? "") && (await page.locator(".px-tile").count()) === 4, "Delete, once agreed, takes it out and shows the next");
// A video shows its still; Play opens it in the computer's own player.
if (await page.getByRole("button", { name: "Play in your video player" }).count()) {
@@ -87,8 +87,8 @@ await page.evaluate(() => { window.__flagFail = false; });
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.
+// Opening is at once — no growing out of the tile, which flickered on his screen: the photo is
+// its whole size in the very frame it first appears (caught in the page, not after a round trip).
await page.evaluate(() => {
window.__firstWidth = null;
const watch = new MutationObserver(() => {
@@ -104,7 +104,7 @@ 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`);
+ok(Math.abs(mid - end) <= 1 && end > 200, `a photo opens at once, its whole size from its first frame ${Math.round(mid)} → ${Math.round(end)}px`);
await page.keyboard.press("Escape");
await page.waitForTimeout(650);
// Another photo opened while the last is still closing stays open, and is seen.
@@ -207,7 +207,7 @@ ok((await scaleOf()) > 1.2 && (await page.evaluate(() => getComputedStyle(docume
await page.keyboard.press("Control+0");
await page.keyboard.press("ArrowLeft");
await page.waitForTimeout(60);
-ok(/p1/.test((await page.locator(".px-shown").getAttribute("src")) ?? ""), "the left arrow goes to the photo before, at once");
+ok(/p1/.test((await page.locator(".px-shown").getAttribute("data-picture")) ?? ""), "the left arrow goes to the photo before, at once");
await page.keyboard.press("ArrowRight");
await page.keyboard.press("ArrowRight");
await page.waitForTimeout(60);
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index d54d8c2..dfe728a 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -310,7 +310,9 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
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",
- favorite: false, hidden: false, deleted: false, deletedAt: null, subtype: 0, changeTag: null, ...extra });
+ favorite: false, hidden: false, deleted: false, deletedAt: null, subtype: 0, changeTag: null, ...extra,
+ // A test's own marks on a photo (a burst, a Live Photo), set before the first read.
+ ...(window.__photoExtra?.[id] ?? {}) });
const all = (window.__photos ??= [
P("p1", 1792500000, { favorite: true }), P("p2", 1792400000, { keywords: ["beach"], latitude: 17.7653751, longitude: 83.357605 }), P("p3", 1792300000, { kind: "video", duration: 12.4, uti: "public.mpeg-4", filename: "clip.mp4" }),
P("p4", 1789900000, { addedAt: 1792700000 }), P("p5", 1789800000, { rating: 5 }), P("p6", 1789700000, { deleted: true, deletedAt: 1792600000, expungeAt: Math.floor(Date.now() / 1000) + 2 * 86400 + 600 }),
@@ -328,6 +330,14 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
if (window.__slowView === args.view) return new Promise((r) => setTimeout(() => r(answer), 600));
return answer;
}
+ case "photos_prepare": (window.__prepared ??= []).push(args.shown); return null;
+ case "photos_burst": {
+ // Three shots; the library's own photo is the chosen one, in the middle.
+ 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 }));
+ }
case "photos_albums": {
const albums = (window.__albums ??= [{ id: "AL1", name: "Trips", position: 0, changeTag: null, items: ["p4", "p2"] }]);
return albums.map(({ items, ...a }) => [a, items.length]);
diff --git a/Cargo.lock b/Cargo.lock
index 6ba64a4..284e7de 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -243,7 +243,7 @@ dependencies = [
"glib-sys",
"gobject-sys",
"libc",
- "system-deps",
+ "system-deps 6.2.2",
]
[[package]]
@@ -431,7 +431,7 @@ checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51"
dependencies = [
"glib-sys",
"libc",
- "system-deps",
+ "system-deps 6.2.2",
]
[[package]]
@@ -519,7 +519,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02"
dependencies = [
"smallvec",
- "target-lexicon",
+ "target-lexicon 0.12.16",
+]
+
+[[package]]
+name = "cfg-expr"
+version = "0.20.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ba9e9ec16c447027685b1f897b720e18e9a8afd00bd7332c483537e38086c9f"
+dependencies = [
+ "smallvec",
+ "target-lexicon 0.13.5",
]
[[package]]
@@ -1133,6 +1143,17 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "enumn"
+version = "0.1.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f9ed6b3789237c8a0c1c505af1c7eb2c560df6186f01b098c3a1064ea532f38"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "equivalent"
version = "1.0.2"
@@ -1294,6 +1315,12 @@ dependencies = [
"percent-encoding",
]
+[[package]]
+name = "four-cc"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "795cbfc56d419a7ce47ccbb7504dd9a5b7c484c083c356e797de08bd988d9629"
+
[[package]]
name = "futures"
version = "0.3.34"
@@ -1433,7 +1460,7 @@ dependencies = [
"glib-sys",
"gobject-sys",
"libc",
- "system-deps",
+ "system-deps 6.2.2",
]
[[package]]
@@ -1450,7 +1477,7 @@ dependencies = [
"libc",
"pango-sys",
"pkg-config",
- "system-deps",
+ "system-deps 6.2.2",
]
[[package]]
@@ -1464,7 +1491,7 @@ dependencies = [
"gobject-sys",
"libc",
"pkg-config",
- "system-deps",
+ "system-deps 6.2.2",
]
[[package]]
@@ -1490,7 +1517,7 @@ dependencies = [
"gdk-sys",
"glib-sys",
"libc",
- "system-deps",
+ "system-deps 6.2.2",
"x11",
]
@@ -1571,7 +1598,7 @@ dependencies = [
"glib-sys",
"gobject-sys",
"libc",
- "system-deps",
+ "system-deps 6.2.2",
"winapi",
]
@@ -1619,7 +1646,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898"
dependencies = [
"libc",
- "system-deps",
+ "system-deps 6.2.2",
]
[[package]]
@@ -1636,7 +1663,7 @@ checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44"
dependencies = [
"glib-sys",
"libc",
- "system-deps",
+ "system-deps 6.2.2",
]
[[package]]
@@ -1675,7 +1702,7 @@ dependencies = [
"gobject-sys",
"libc",
"pango-sys",
- "system-deps",
+ "system-deps 6.2.2",
]
[[package]]
@@ -2150,7 +2177,7 @@ dependencies = [
"glib-sys",
"gobject-sys",
"libc",
- "system-deps",
+ "system-deps 6.2.2",
]
[[package]]
@@ -2356,6 +2383,32 @@ dependencies = [
"pkg-config",
]
+[[package]]
+name = "libheif-rs"
+version = "3.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eeba013228b7f744e2ede32bbc4ea9056a9a27910e2ff61fdb146f94ed89f7ea"
+dependencies = [
+ "cfg-if",
+ "enumn",
+ "four-cc",
+ "libc",
+ "libheif-sys",
+]
+
+[[package]]
+name = "libheif-sys"
+version = "5.3.1+1.23.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f554864c5f34c7f285ff6acdcadb64bcc2a3de1609e9135cec702c5edc703864"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "system-deps 8.0.0",
+ "vcpkg",
+ "walkdir",
+]
+
[[package]]
name = "libloading"
version = "0.7.4"
@@ -2961,7 +3014,7 @@ dependencies = [
"glib-sys",
"gobject-sys",
"libc",
- "system-deps",
+ "system-deps 6.2.2",
]
[[package]]
@@ -3283,6 +3336,7 @@ dependencies = [
"base64 0.22.1",
"futures-util",
"jiff",
+ "libc",
"notify-rust",
"quince-auth",
"quince-core",
@@ -3365,6 +3419,7 @@ version = "0.1.0"
dependencies = [
"fast_image_resize",
"image",
+ "libheif-rs",
]
[[package]]
@@ -4304,7 +4359,7 @@ dependencies = [
"glib-sys",
"gobject-sys",
"libc",
- "system-deps",
+ "system-deps 6.2.2",
]
[[package]]
@@ -4424,13 +4479,26 @@ version = "6.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349"
dependencies = [
- "cfg-expr",
+ "cfg-expr 0.15.8",
"heck 0.5.0",
"pkg-config",
"toml 0.8.2",
"version-compare",
]
+[[package]]
+name = "system-deps"
+version = "8.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "83779a5c956bcb6ba627a4ecf0a9d7625db47d7537e0892d97f712ac995648a3"
+dependencies = [
+ "cfg-expr 0.20.10",
+ "heck 0.5.0",
+ "pkg-config",
+ "toml 1.1.6+spec-1.1.0",
+ "version-compare",
+]
+
[[package]]
name = "tao"
version = "0.35.3"
@@ -4488,6 +4556,12 @@ version = "0.12.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
+[[package]]
+name = "target-lexicon"
+version = "0.13.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
+
[[package]]
name = "tauri"
version = "2.11.5"
@@ -5562,7 +5636,7 @@ dependencies = [
"libc",
"pkg-config",
"soup3-sys",
- "system-deps",
+ "system-deps 6.2.2",
]
[[package]]
diff --git a/crates/quince-core/src/photos.rs b/crates/quince-core/src/photos.rs
index 618ab86..2de99fe 100644
--- a/crates/quince-core/src/photos.rs
+++ b/crates/quince-core/src/photos.rs
@@ -89,6 +89,15 @@ pub struct Photo {
pub rendered: i64,
/// Photos' subtype: 1 and 3 mark screenshots and the like (`assetSubtypeV2`).
pub subtype: i64,
+ /// The burst it was shot in (`burstId`): a burst shows as its one chosen photo.
+ #[serde(default)]
+ pub burst: Option<String>,
+ /// The burst's chosen photo — the one Photos shows for it (`burstFlags` 16).
+ #[serde(default)]
+ pub burst_pick: bool,
+ /// How many photos its burst holds (filled when read; not stored).
+ #[serde(default)]
+ pub burst_count: i64,
/// The asset's change tag, for writing back to it.
pub change_tag: Option<String>,
}
@@ -150,7 +159,14 @@ pub enum View {
const COLUMNS: &str = "id, master, taken_at, added_at, kind, width, height, duration, filename, \
size, uti, favorite, hidden, deleted, deleted_at, subtype, change_tag, expunge_at, title, caption, rating, \
- keywords, latitude, longitude, rendered";
+ keywords, latitude, longitude, rendered, burst, burst_pick";
+
+/// A burst shows as its chosen photo, as Photos shows it (Apple's library says as much: its
+/// `burstsExcludedFromPhotosCount` is every burst's photos less one each). A burst whose chosen
+/// photo is not in the library shows whole rather than not at all.
+const ONE_PER_BURST: &str =
+ "(burst IS NULL OR burst_pick = 1 OR NOT EXISTS (SELECT 1 FROM photos k \
+ WHERE k.burst = photos.burst AND k.burst_pick = 1 AND k.deleted = 0))";
fn row_to_photo(r: &rusqlite::Row<'_>) -> rusqlite::Result<Photo> {
Ok(Photo {
@@ -182,6 +198,9 @@ fn row_to_photo(r: &rusqlite::Row<'_>) -> rusqlite::Result<Photo> {
latitude: r.get(22)?,
longitude: r.get(23)?,
rendered: r.get(24)?,
+ burst: r.get(25)?,
+ burst_pick: r.get::<_, i64>(26)? != 0,
+ burst_count: 0,
})
}
@@ -194,9 +213,9 @@ impl Library {
"INSERT INTO photos (id, master, taken_at, added_at, kind, width, height, duration,
filename, size, uti, favorite, hidden, deleted, deleted_at,
subtype, change_tag, expunge_at, title, caption, rating,
- keywords, latitude, longitude, rendered)
+ keywords, latitude, longitude, rendered, burst, burst_pick)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?21,
- ?22, ?23, ?24, ?25)
+ ?22, ?23, ?24, ?25, ?26, ?27)
ON CONFLICT(id) DO UPDATE SET
master = excluded.master, taken_at = excluded.taken_at,
added_at = excluded.added_at, kind = excluded.kind, width = excluded.width,
@@ -208,7 +227,8 @@ impl Library {
expunge_at = excluded.expunge_at, title = excluded.title,
caption = excluded.caption, rating = excluded.rating,
keywords = excluded.keywords, latitude = excluded.latitude,
- longitude = excluded.longitude, rendered = excluded.rendered",
+ longitude = excluded.longitude, rendered = excluded.rendered,
+ burst = excluded.burst, burst_pick = excluded.burst_pick",
)?;
for p in photos {
stmt.execute(params![
@@ -237,7 +257,9 @@ impl Library {
.then(|| serde_json::to_string(&p.keywords).unwrap_or_default()),
p.latitude,
p.longitude,
- p.rendered
+ p.rendered,
+ p.burst,
+ i64::from(p.burst_pick)
])?;
}
}
@@ -264,11 +286,44 @@ impl Library {
/// A view's photos, newest first.
pub fn photos(&self, view: View) -> Result<Vec<Photo>> {
let (filter, order) = Self::view_query(view);
+ let bursts = if view == View::RecentlyDeleted {
+ "1"
+ } else {
+ ONE_PER_BURST
+ };
let mut stmt = self.conn.prepare(&format!(
- "SELECT {COLUMNS} FROM photos WHERE {filter} ORDER BY {order}, id"
+ "SELECT {COLUMNS} FROM photos WHERE {filter} AND {bursts} ORDER BY {order}, id"
))?;
let rows = stmt.query_map([], row_to_photo)?;
- Ok(rows.collect::<std::result::Result<_, _>>()?)
+ self.with_bursts(rows.collect::<std::result::Result<_, _>>()?)
+ }
+
+ /// Each photo's burst size, from one count over the library.
+ fn with_bursts(&self, mut photos: Vec<Photo>) -> Result<Vec<Photo>> {
+ 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<_, _>>()?;
+ for p in &mut photos {
+ if let Some(b) = &p.burst {
+ p.burst_count = sizes.get(b).copied().unwrap_or(1);
+ }
+ }
+ Ok(photos)
+ }
+
+ /// Every photo of one burst, in the order they were shot.
+ pub fn burst_photos(&self, burst: &str) -> Result<Vec<Photo>> {
+ let mut stmt = self.conn.prepare(&format!(
+ "SELECT {COLUMNS} FROM photos WHERE burst = ?1 AND deleted = 0 ORDER BY taken_at, id"
+ ))?;
+ let rows = stmt.query_map(params![burst], row_to_photo)?;
+ self.with_bursts(rows.collect::<std::result::Result<_, _>>()?)
}
/// Photos found by what is typed, as Photos' search finds them: every word must match the
@@ -300,7 +355,7 @@ impl Library {
.map(|n| one.replace("{n}", &n.to_string()))
.collect();
let sql = format!(
- "SELECT {COLUMNS} FROM photos WHERE deleted = 0 AND hidden = 0 AND {}
+ "SELECT {COLUMNS} FROM photos WHERE deleted = 0 AND hidden = 0 AND {ONE_PER_BURST} AND {}
ORDER BY taken_at DESC, id LIMIT {}",
conditions.join(" AND "),
limit.min(50_000)
@@ -317,7 +372,7 @@ impl Library {
.collect();
let mut stmt = self.conn.prepare(&sql)?;
let rows = stmt.query_map(rusqlite::params_from_iter(patterns.iter()), row_to_photo)?;
- Ok(rows.collect::<std::result::Result<_, _>>()?)
+ self.with_bursts(rows.collect::<std::result::Result<_, _>>()?)
}
/// Which photos a view holds, and in what order.
@@ -367,7 +422,11 @@ impl Library {
.conn
.prepare(&format!("SELECT {COLUMNS} FROM photos WHERE id = ?1"))?;
let mut rows = stmt.query_map(params![id], row_to_photo)?;
- Ok(rows.next().transpose()?)
+ let one: Option<Photo> = rows.next().transpose()?;
+ Ok(match one {
+ Some(p) => self.with_bursts(vec![p])?.pop(),
+ None => None,
+ })
}
/// How many photos each view holds.
@@ -387,8 +446,13 @@ impl Library {
// Counted where the rows are: a library of twenty thousand is not read seven times
// over to say how many each view holds.
let (filter, _) = Self::view_query(view);
+ let bursts = if view == View::RecentlyDeleted {
+ "1"
+ } else {
+ ONE_PER_BURST
+ };
let n: i64 = self.conn.query_row(
- &format!("SELECT COUNT(*) FROM photos WHERE {filter}"),
+ &format!("SELECT COUNT(*) FROM photos WHERE {filter} AND {bursts}"),
[],
|r| r.get(0),
)?;
@@ -550,7 +614,7 @@ impl Library {
ORDER BY i.position, p.taken_at DESC, p.id"
))?;
let rows = stmt.query_map(params![album], row_to_photo)?;
- Ok(rows.collect::<std::result::Result<_, _>>()?)
+ self.with_bursts(rows.collect::<std::result::Result<_, _>>()?)
}
/// One album added or changed, as Apple answered a write.
@@ -695,9 +759,45 @@ mod tests {
latitude: None,
longitude: None,
rendered: 0,
+ burst: None,
+ burst_pick: false,
+ burst_count: 0,
}
}
+ /// A burst shows as its chosen photo in every view and count, carrying how many it holds;
+ /// all of it is there to look through; with its chosen photo gone it shows whole.
+ #[test]
+ fn a_burst_shows_as_its_chosen_photo() {
+ let mut lib = Library::in_memory().unwrap();
+ let mut shots: Vec<Photo> = (0..5)
+ .map(|i| Photo {
+ burst: Some("B".into()),
+ burst_pick: i == 2,
+ ..photo(&format!("b{i}"), 100 + i)
+ })
+ .collect();
+ shots.push(photo("alone", 50));
+ lib.put_photos(&shots).unwrap();
+ let shown = lib.photos(View::Library).unwrap();
+ assert_eq!(
+ shown.iter().map(|p| p.id.as_str()).collect::<Vec<_>>(),
+ vec!["b2", "alone"]
+ );
+ assert_eq!(shown[0].burst_count, 5);
+ let counts = lib.photo_counts().unwrap();
+ assert_eq!(
+ counts.iter().find(|(v, _)| *v == View::Library).unwrap().1,
+ 2
+ );
+ assert_eq!(lib.burst_photos("B").unwrap().len(), 5);
+ // The chosen one deleted: the rest show, rather than the burst vanishing.
+ let mut gone = lib.photo("b2").unwrap().unwrap();
+ gone.deleted = true;
+ lib.put_photos(&[gone]).unwrap();
+ assert_eq!(lib.photos(View::Library).unwrap().len(), 5);
+ }
+
/// Each view is the right photos, newest first; Recently Deleted holds only the deleted.
#[test]
fn views_sort_and_filter() {
diff --git a/crates/quince-core/src/schema.rs b/crates/quince-core/src/schema.rs
index 4d0483c..b818a6b 100644
--- a/crates/quince-core/src/schema.rs
+++ b/crates/quince-core/src/schema.rs
@@ -507,4 +507,12 @@ pub const MIGRATIONS: &[&str] = &[
r#"
UPDATE photos SET duration = duration / 1000.0 WHERE duration IS NOT NULL;
"#,
+ // The burst each photo was shot in, and whether it is the burst's chosen one; Photos read
+ // again so every photo has them.
+ r#"
+ ALTER TABLE photos ADD COLUMN burst TEXT;
+ ALTER TABLE photos ADD COLUMN burst_pick INTEGER NOT NULL DEFAULT 0;
+ CREATE INDEX photos_by_burst ON photos (burst) WHERE burst IS NOT NULL;
+ UPDATE sync_state SET token = NULL WHERE service = 'photos';
+ "#,
];
diff --git a/crates/quince-icloud/src/photos.rs b/crates/quince-icloud/src/photos.rs
index 1123c02..451e83e 100644
--- a/crates/quince-icloud/src/photos.rs
+++ b/crates/quince-icloud/src/photos.rs
@@ -140,6 +140,24 @@ fn millis(record: &Value, name: &str) -> Option<i64> {
/// A photo from its asset and the master it shows.
#[must_use]
+/// The burst a photo was shot in (`burstId`).
+fn burst_of(asset: &Value) -> Option<String> {
+ asset
+ .pointer("/fields/burstId/value")
+ .and_then(Value::as_str)
+ .filter(|s| !s.is_empty())
+ .map(str::to_string)
+}
+
+/// Whether it is its burst's chosen photo, the one Photos shows: read on his library, each
+/// burst has exactly one with `burstFlags` 20 (16 set) and `burstFlagsExt` 32; the rest are 2
+/// or 4 — and Apple's own count of photos kept out of the library (67) is the bursts' 70 less
+/// those three.
+fn burst_pick_of(asset: &Value) -> bool {
+ field::int(asset, "burstFlags").is_some_and(|f| f & 16 != 0)
+ || field::int(asset, "burstFlagsExt").is_some_and(|f| f & 32 != 0)
+}
+
pub fn photo_of(asset: &Value, master: &Value) -> Option<Photo> {
let id = field::record_name(asset)?;
let master_id = field::record_name(master)?;
@@ -205,6 +223,9 @@ pub fn photo_of(asset: &Value, master: &Value) -> Option<Photo> {
rating: field::int(asset, "rating").unwrap_or(0).clamp(0, 5),
keywords: keywords_of(asset),
rendered: field::int(asset, "customRenderedValue").unwrap_or(0),
+ burst: burst_of(asset),
+ burst_pick: burst_pick_of(asset),
+ burst_count: 0,
latitude: location_of(asset).map(|l| l.0),
longitude: location_of(asset).map(|l| l.1),
expunge_at: (field::int(asset, "isDeleted") == Some(1))
@@ -237,6 +258,10 @@ fn with_asset(mut p: Photo, asset: &Value) -> Photo {
p.rating = field::int(asset, "rating").unwrap_or(0).clamp(0, 5);
p.keywords = keywords_of(asset);
p.rendered = field::int(asset, "customRenderedValue").unwrap_or(p.rendered);
+ if asset.pointer("/fields/burstId").is_some() {
+ p.burst = burst_of(asset);
+ p.burst_pick = burst_pick_of(asset);
+ }
if let Some((lat, lon)) = location_of(asset) {
(p.latitude, p.longitude) = (Some(lat), Some(lon));
}
@@ -955,6 +980,21 @@ mod tests {
);
}
+ /// A burst's photos know their burst; the chosen one (flags 20 / 32) says so.
+ #[test]
+ fn a_burst_and_its_chosen_photo() {
+ let pick = photo_of(
+ &asset(json!({"burstId": "B1", "burstFlags": 20, "burstFlagsExt": 32})),
+ &master(),
+ )
+ .unwrap();
+ let other = photo_of(&asset(json!({"burstId": "B1", "burstFlags": 2})), &master()).unwrap();
+ let four = photo_of(&asset(json!({"burstId": "B1", "burstFlags": 4})), &master()).unwrap();
+ assert_eq!(pick.burst.as_deref(), Some("B1"));
+ assert!(pick.burst_pick && !other.burst_pick && !four.burst_pick);
+ assert_eq!(photo_of(&asset(json!({})), &master()).unwrap().burst, None);
+ }
+
/// A video's length: Apple's milliseconds, kept as seconds (a 62.18 s clip, not 1036 minutes).
#[test]
fn a_video_length_is_seconds() {
diff --git a/crates/quince-media/Cargo.toml b/crates/quince-media/Cargo.toml
index 1f302bf..368c613 100644
--- a/crates/quince-media/Cargo.toml
+++ b/crates/quince-media/Cargo.toml
@@ -9,3 +9,4 @@ fast_image_resize = "6.1.0"
# Only the formats Apple has been observed to serve. Every extra decoder is compile time and
# attack surface for no gain.
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
+libheif-rs = "3.0.0"
diff --git a/crates/quince-media/src/lib.rs b/crates/quince-media/src/lib.rs
index ee220e1..d6fbaf9 100644
--- a/crates/quince-media/src/lib.rs
+++ b/crates/quince-media/src/lib.rs
@@ -91,6 +91,52 @@ fn cut(image: image::DynamicImage, crop: Option<Crop>) -> image::DynamicImage {
///
/// A photograph re-encoded as PNG is several times the size for no visible gain, and these are
/// read back on every scroll.
+/// A HEIC (or HEIF) original as a high-quality JPEG, turned, cropped and mirrored as the file
+/// says. Apple keeps no full-size JPEG of any HEIC photo (none of 495 in his library) and, for
+/// screenshots and the like, often nothing larger than a thumbnail: without this, the sharpest a
+/// HEIC photo could be shown was 2048 pixels, and some only a thumbnail stretched — or a broken
+/// picture where none could be made. Decoded here from the original, as Photos on a Mac does.
+///
+/// # Errors
+/// When the bytes are not a HEIF image libheif can decode.
+pub fn heic_to_jpeg(bytes: &[u8]) -> Result<Vec<u8>, String> {
+ use libheif_rs::{ColorSpace, HeifContext, LibHeif, RgbChroma};
+ let lib = LibHeif::new();
+ let ctx = HeifContext::read_from_bytes(bytes).map_err(|e| e.to_string())?;
+ let handle = ctx.primary_image_handle().map_err(|e| e.to_string())?;
+ let image = lib
+ .decode(&handle, ColorSpace::Rgb(RgbChroma::Rgb), None)
+ .map_err(|e| e.to_string())?;
+ let plane = image
+ .planes()
+ .interleaved
+ .ok_or("the picture had no colour plane")?;
+ let (w, h, stride) = (plane.width, plane.height, plane.stride);
+ let row = w as usize * 3;
+ let mut rgb = Vec::with_capacity(row * h as usize);
+ for y in 0..h as usize {
+ rgb.extend_from_slice(&plane.data[y * stride..y * stride + row]);
+ }
+ let picture = image::RgbImage::from_raw(w, h, rgb).ok_or("the picture had the wrong size")?;
+ let mut out = std::io::Cursor::new(Vec::new());
+ image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 92)
+ .encode_image(&picture)
+ .map_err(|e| e.to_string())?;
+ Ok(out.into_inner())
+}
+
+/// Whether bytes are a HEIF file (HEIC and its kin): an `ftyp` box naming a HEIF brand.
+#[must_use]
+pub fn is_heif(bytes: &[u8]) -> bool {
+ bytes.get(4..8) == Some(b"ftyp")
+ && bytes.get(8..12).is_some_and(|b| {
+ matches!(
+ b,
+ b"heic" | b"heix" | b"heim" | b"heis" | b"hevc" | b"hevx" | b"mif1" | b"msf1"
+ )
+ })
+}
+
/// A picture's longer side, read from its header alone (nothing decoded).
#[must_use]
pub fn long_side(bytes: &[u8]) -> Option<u32> {
diff --git a/probe/examples/heic_check.rs b/probe/examples/heic_check.rs
new file mode 100644
index 0000000..f46686e
--- /dev/null
+++ b/probe/examples/heic_check.rs
@@ -0,0 +1,34 @@
+//! Read only: one photo's original fetched into a folder, and made a JPEG the app's way.
+use anyhow::{anyhow, Result};
+#[tokio::main]
+async fn main() -> Result<()> {
+ let args: Vec<String> = std::env::args().collect();
+ let (master, out) = (&args[1], std::path::PathBuf::from(&args[2]));
+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");
+ let mut client = quince_auth::Client::new(&dir)?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let root = client
+ .session()
+ .service_url("ckdatabasews")
+ .ok_or_else(|| anyhow!("no ck"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ let links = quince_icloud::photos::links(&http, &root, p, master)
+ .await?
+ .ok_or_else(|| anyhow!("no links"))?;
+ let url = links.original.ok_or_else(|| anyhow!("no original"))?;
+ let heic = out.join("original.heic");
+ quince_icloud::photos::fetch_to_file(&http, &url, &heic).await?;
+ let bytes = std::fs::read(&heic)?;
+ println!(
+ "original {} bytes, heif = {}",
+ bytes.len(),
+ quince_media::is_heif(&bytes)
+ );
+ let t = std::time::Instant::now();
+ let jpg = quince_media::heic_to_jpeg(&bytes).map_err(|e| anyhow!(e))?;
+ println!("decoded to JPEG in {:?}, {} bytes", t.elapsed(), jpg.len());
+ std::fs::write(out.join("ours.jpg"), jpg)?;
+ Ok(())
+}
diff --git a/probe/examples/photos_burst_audit.rs b/probe/examples/photos_burst_audit.rs
new file mode 100644
index 0000000..b7ee0b2
--- /dev/null
+++ b/probe/examples/photos_burst_audit.rs
@@ -0,0 +1,46 @@
+//! Read only: the library's own counts (CPLLibraryInfo) against what Quince shows once bursts
+//! are stacked — every field of that record printed, then Quince's Library count.
+use anyhow::{anyhow, Result};
+#[tokio::main]
+async fn main() -> Result<()> {
+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");
+ let mut client = quince_auth::Client::new(&dir)?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let root = client
+ .session()
+ .service_url("ckdatabasews")
+ .ok_or_else(|| anyhow!("no ck"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ let fetched = quince_icloud::photos::fetch(&http, &root, p, None).await?;
+ for r in &fetched.records {
+ if r["recordType"] == "CPLLibraryInfo" {
+ for (k, v) in r["fields"].as_object().unwrap() {
+ println!("LibraryInfo.{k} = {}", v["value"]);
+ }
+ }
+ }
+ let mut lib = quince_core::Library::in_memory()?;
+ quince_icloud::photos::apply(&mut lib, fetched)?;
+ for (v, n) in lib.photo_counts()? {
+ println!("quince {v:?}: {n}");
+ }
+ let lib_view = lib.photos(quince_core::photos::View::Library)?;
+ let (videos, photos) = lib_view.iter().fold((0, 0), |(v, p), x| {
+ if x.kind == quince_core::photos::Kind::Video {
+ (v + 1, p)
+ } else {
+ (v, p + 1)
+ }
+ });
+ let bursts: Vec<_> = lib_view
+ .iter()
+ .filter(|x| x.burst.is_some())
+ .map(|x| x.burst_count)
+ .collect();
+ println!(
+ "quince Library: {photos} photos, {videos} videos; bursts shown as one each: {bursts:?}"
+ );
+ Ok(())
+}
diff --git a/probe/examples/photos_burst_live_fields.rs b/probe/examples/photos_burst_live_fields.rs
new file mode 100644
index 0000000..38e9985
--- /dev/null
+++ b/probe/examples/photos_burst_live_fields.rs
@@ -0,0 +1,95 @@
+//! Read only: which fields Apple puts on a burst's photos and on a Live Photo, and their values
+//! across his library — so bursts can be stacked and Live Photos marked by Apple's own words.
+use anyhow::{anyhow, Result};
+use std::collections::BTreeMap;
+#[tokio::main]
+async fn main() -> Result<()> {
+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");
+ let mut client = quince_auth::Client::new(&dir)?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let root = client
+ .session()
+ .service_url("ckdatabasews")
+ .ok_or_else(|| anyhow!("no ck"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ let fetched = quince_icloud::photos::fetch(&http, &root, p, None).await?;
+ let mut names: BTreeMap<String, BTreeMap<String, usize>> = BTreeMap::new();
+ let mut bursts: BTreeMap<String, Vec<(String, i64, i64)>> = BTreeMap::new();
+ let mut types: BTreeMap<String, usize> = BTreeMap::new();
+ for r in &fetched.records {
+ let kind = r["recordType"].as_str().unwrap_or("?").to_string();
+ *types.entry(kind.clone()).or_default() += 1;
+ let Some(fields) = r["fields"].as_object() else {
+ continue;
+ };
+ for (k, v) in fields {
+ let lk = k.to_lowercase();
+ if lk.contains("burst")
+ || lk.contains("live")
+ || lk.contains("subtype")
+ || lk.contains("vidcompl")
+ || lk.contains("adjustmenttype")
+ || lk.contains("playback")
+ || lk.contains("variation")
+ {
+ let val = v["value"].clone();
+ let shown = if val.is_object() {
+ "{object}".to_string()
+ } else {
+ val.to_string()
+ };
+ let shown = if shown.len() > 40 {
+ format!("{}…", &shown[..40])
+ } else {
+ shown
+ };
+ *names
+ .entry(format!("{kind}.{k}"))
+ .or_default()
+ .entry(shown)
+ .or_default() += 1;
+ }
+ }
+ if kind == "CPLAsset" {
+ if let Some(id) = fields.get("burstId").and_then(|v| v["value"].as_str()) {
+ bursts.entry(id.to_string()).or_default().push((
+ r["recordName"].as_str().unwrap_or("").to_string(),
+ fields
+ .get("burstFlags")
+ .and_then(|v| v["value"].as_i64())
+ .unwrap_or(-1),
+ fields
+ .get("burstFlagsExt")
+ .and_then(|v| v["value"].as_i64())
+ .unwrap_or(-1),
+ ));
+ }
+ }
+ }
+ println!("record types: {types:?}");
+ for (k, vals) in &names {
+ let mut v: Vec<_> = vals.iter().collect();
+ v.sort_by(|a, b| b.1.cmp(a.1));
+ println!(
+ "{k}: {}",
+ v.iter()
+ .take(8)
+ .map(|(x, n)| format!("{x}×{n}"))
+ .collect::<Vec<_>>()
+ .join(" ")
+ );
+ }
+ println!("bursts: {}", bursts.len());
+ for (id, members) in bursts.iter().take(5) {
+ let flags: Vec<String> = members.iter().map(|m| format!("{}/{}", m.1, m.2)).collect();
+ println!(
+ " {}…: {} photos, flags {}",
+ &id[..8.min(id.len())],
+ members.len(),
+ flags.join(" ")
+ );
+ }
+ Ok(())
+}
diff --git a/probe/examples/photos_heic_renditions.rs b/probe/examples/photos_heic_renditions.rs
new file mode 100644
index 0000000..99c6f91
--- /dev/null
+++ b/probe/examples/photos_heic_renditions.rs
@@ -0,0 +1,40 @@
+//! Read only: of the HEIC originals, how many Apple also keeps as a full-size JPEG
+//! (resJPEGFullRes), and how large their screen-sized one (resJPEGMedRes) is.
+use anyhow::{anyhow, Result};
+#[tokio::main]
+async fn main() -> Result<()> {
+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");
+ let mut client = quince_auth::Client::new(&dir)?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let root = client
+ .session()
+ .service_url("ckdatabasews")
+ .ok_or_else(|| anyhow!("no ck"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ let fetched = quince_icloud::photos::fetch(&http, &root, p, None).await?;
+ let (mut heic, mut with_full, mut med_small) = (0, 0, 0);
+ let mut med_sizes = std::collections::BTreeMap::new();
+ for r in &fetched.records {
+ if r["recordType"] != "CPLMaster" || r["fields"]["itemType"]["value"] != "public.heic" {
+ continue;
+ }
+ heic += 1;
+ let f = &r["fields"];
+ if f.get("resJPEGFullRes").is_some() {
+ with_full += 1;
+ }
+ let mw = f["resJPEGMedWidth"]["value"]
+ .as_i64()
+ .unwrap_or(0)
+ .max(f["resJPEGMedHeight"]["value"].as_i64().unwrap_or(0));
+ if mw < 1500 {
+ med_small += 1;
+ }
+ *med_sizes.entry(mw).or_insert(0) += 1;
+ }
+ println!("HEIC masters: {heic}; with a full-size JPEG: {with_full}; screen-sized under 1500 px: {med_small}");
+ println!("screen-sized long sides: {med_sizes:?}");
+ Ok(())
+}
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index a618b18..4a7063f 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -28,6 +28,7 @@ tauri-plugin-opener = "2"
notify-rust = "4"
zbus = "5"
tauri-plugin-single-instance = "2"
+libc = "0.2"
[dev-dependencies]
tempfile = "3"
diff --git a/src-tauri/src/cpu.rs b/src-tauri/src/cpu.rs
new file mode 100644
index 0000000..86d10d0
--- /dev/null
+++ b/src-tauri/src/cpu.rs
@@ -0,0 +1,102 @@
+//! Where the app's heavy picture work runs, by who it is for.
+//!
+//! For the screen (a tile or a photo the window has asked for and is waiting on): on the
+//! runtime's blocking threads, every core if need be. For later (pictures made ahead, a HEIC
+//! decoded before it is opened): on one worker thread at the lowest CPU priority, so it only
+//! ever has the time the window is not using. Made ahead on every core at normal priority, the
+//! work starved the window — his scrolling froze for most of a second at a time while a newly
+//! synced library was being prepared.
+
+use std::sync::mpsc;
+use std::sync::OnceLock;
+
+tokio::task_local! {
+ /// Set for work done ahead of being asked for (see `ahead`).
+ static AHEAD: bool;
+}
+
+/// Runs `work` as work done ahead: everything it does on the CPU (through `run`) goes to the
+/// background worker.
+pub async fn ahead<F: std::future::Future>(work: F) -> F::Output {
+ AHEAD.scope(true, work).await
+}
+
+/// Whether the current task is work done ahead.
+pub fn is_ahead() -> bool {
+ AHEAD.try_with(|a| *a).unwrap_or(false)
+}
+
+type Job = Box<dyn FnOnce() + Send>;
+
+/// The one background worker, started at the lowest priority the first time it is needed.
+fn background() -> &'static mpsc::Sender<Job> {
+ static TX: OnceLock<mpsc::Sender<Job>> = OnceLock::new();
+ TX.get_or_init(|| {
+ let (tx, rx) = mpsc::channel::<Job>();
+ std::thread::Builder::new()
+ .name("quince-ahead".into())
+ .spawn(move || {
+ // Nice 19 for this thread alone (Linux schedules threads, so the window's own
+ // threads keep their place).
+ #[cfg(target_os = "linux")]
+ unsafe {
+ let tid = libc::syscall(libc::SYS_gettid) as libc::id_t;
+ libc::setpriority(libc::PRIO_PROCESS, tid, 19);
+ }
+ for job in rx {
+ job();
+ }
+ })
+ .expect("could not start the background worker");
+ tx
+ })
+}
+
+/// Runs CPU-heavy `work` where it belongs: on the background worker inside `ahead`, otherwise
+/// on the runtime's blocking threads.
+pub async fn run<T, F>(work: F) -> Result<T, String>
+where
+ T: Send + 'static,
+ F: FnOnce() -> T + Send + 'static,
+{
+ if is_ahead() {
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ background()
+ .send(Box::new(move || {
+ let _ = tx.send(work());
+ }))
+ .map_err(|_| "the background worker has stopped".to_string())?;
+ rx.await
+ .map_err(|_| "the background worker dropped the work".to_string())
+ } else {
+ tokio::task::spawn_blocking(work)
+ .await
+ .map_err(|e| e.to_string())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn work_ahead_runs_on_the_low_priority_worker_and_the_rest_does_not() {
+ tauri::async_runtime::block_on(async {
+ let name = || std::thread::current().name().map(str::to_string);
+ let now = super::run(name).await.unwrap();
+ let later = super::ahead(super::run(name)).await.unwrap();
+ assert_ne!(now.as_deref(), Some("quince-ahead"));
+ assert_eq!(later.as_deref(), Some("quince-ahead"));
+ #[cfg(target_os = "linux")]
+ {
+ let nice = super::ahead(super::run(|| unsafe {
+ libc::getpriority(
+ libc::PRIO_PROCESS,
+ libc::syscall(libc::SYS_gettid) as libc::id_t,
+ )
+ }))
+ .await
+ .unwrap();
+ assert_eq!(nice, 19);
+ }
+ });
+ }
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 81e9c3e..e273853 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -2,6 +2,7 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod alerts;
+mod cpu;
mod outbox;
mod photos;
mod push;
@@ -3867,6 +3868,8 @@ fn main() {
photos::photo_set_flag,
photos::photo_play,
photos::photos_set_flag,
+ photos::photos_burst,
+ photos::photos_prepare,
video::video_base,
window_tint,
photos::photos_upload,
diff --git a/src-tauri/src/photos.rs b/src-tauri/src/photos.rs
index 99023a2..8a412f8 100644
--- a/src-tauri/src/photos.rs
+++ b/src-tauri/src/photos.rs
@@ -192,10 +192,20 @@ pub async fn fitted(app: &AppHandle, id: &str, long: u32) -> Result<Vec<u8>, Str
});
let mut last = None;
for size in [Size::Thumb, Size::Medium, Size::Full] {
- let source = picture(app, id, size).await?;
+ // A picture Apple has not got (a HEIC whose original cannot be read, a screenshot with
+ // no screen-sized copy) is passed over: the largest there is serves, never an error
+ // where a picture could be shown.
+ let Ok(source) = picture(app, id, size).await else {
+ continue;
+ };
let src = source.clone();
- let _turn = MAKING.acquire().await.map_err(|e| e.to_string())?;
- let made = tokio::task::spawn_blocking(move || {
+ // On-screen work takes a core each; work ahead has its own one low-priority thread.
+ let _turn = if crate::cpu::is_ahead() {
+ None
+ } else {
+ Some(MAKING.acquire().await.map_err(|e| e.to_string())?)
+ };
+ let made = crate::cpu::run(move || {
let big = quince_media::long_side(&src).is_some_and(|l| l >= long);
if !big && size != Size::Full {
return Ok(None);
@@ -240,6 +250,69 @@ 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() {
+ return Ok(path);
+ }
+ if size == Size::Full && is_heic(app, id).await {
+ return heic_full(app, id, &path).await;
+ }
+ from_apple(app, id, size, path).await
+}
+
+/// Whether a photo's original is HEIC (or another HEIF).
+async fn is_heic(app: &AppHandle, id: &str) -> bool {
+ let data = app.state::<Data>();
+ let library = data.0.lock().await;
+ library
+ .photo(id)
+ .ok()
+ .flatten()
+ .and_then(|p| p.uti)
+ .is_some_and(|u| {
+ let u = u.to_ascii_lowercase();
+ u.contains("heic") || u.contains("heif")
+ })
+}
+
+/// A HEIC photo's whole picture: Apple keeps no full-size JPEG of one, so its original is
+/// fetched and decoded here (quince_media::heic_to_jpeg), once, and kept like any other.
+async fn heic_full(app: &AppHandle, id: &str, path: &std::path::Path) -> Result<PathBuf, String> {
+ let original = from_apple(app, id, Size::Original, cache_path(app, id, Size::Original)).await?;
+ let bytes = tokio::fs::read(&original)
+ .await
+ .map_err(|e| e.to_string())?;
+ let jpeg = crate::cpu::run(move || {
+ if quince_media::is_heif(&bytes) {
+ quince_media::heic_to_jpeg(&bytes)
+ } else {
+ // Said HEIC, sent as something the engine shows as it is.
+ Ok(bytes)
+ }
+ })
+ .await
+ .map_err(|e| e.to_string())??;
+ if let Some(dir) = path.parent() {
+ tokio::fs::create_dir_all(dir)
+ .await
+ .map_err(|e| e.to_string())?;
+ }
+ let part = path.with_extension("part");
+ tokio::fs::write(&part, &jpeg)
+ .await
+ .map_err(|e| e.to_string())?;
+ tokio::fs::rename(&part, path)
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(path.to_path_buf())
+}
+
+/// A picture (or video) fetched from Apple once and kept: see `cached`.
+async fn from_apple(
+ app: &AppHandle,
+ id: &str,
+ size: Size,
+ path: PathBuf,
+) -> Result<PathBuf, String> {
if tokio::fs::metadata(&path).await.is_ok() {
return Ok(path);
}
@@ -277,6 +350,8 @@ pub async fn cached(app: &AppHandle, id: &str, size: Size) -> Result<PathBuf, St
/// never waiting on the network. Newest first, two at a time, at most 600 and 3 GB a pass, after
/// each sync; one pass at a time; what is on disk already is skipped.
pub fn keep_ahead(app: AppHandle) {
+ // The pictures the window shows, for whatever the sync brought.
+ prepare(app.clone());
static RUNNING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
if RUNNING.swap(true, std::sync::atomic::Ordering::SeqCst) {
return;
@@ -309,7 +384,7 @@ pub fn keep_ahead(app: AppHandle) {
if budget.load(std::sync::atomic::Ordering::Relaxed) == 0 {
return;
}
- if let Ok(path) = cached(&app, &id, size).await {
+ if let Ok(path) = crate::cpu::ahead(cached(&app, &id, size)).await {
let len = tokio::fs::metadata(&path).await.map_or(0, |m| m.len());
let _ = budget.fetch_update(
std::sync::atomic::Ordering::Relaxed,
@@ -324,6 +399,109 @@ pub fn keep_ahead(app: AppHandle) {
});
}
+/// What the window is showing pictures at: a grid cell's width in device pixels, whether the
+/// grid shows whole photos or squares, and the viewer's stage in CSS pixels with the screen's
+/// pixel density. See `prepare`.
+#[derive(Clone, Copy, Debug, PartialEq, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Shown {
+ pub cell: f64,
+ pub fit: bool,
+ pub stage_w: f64,
+ pub stage_h: f64,
+ pub dpr: f64,
+}
+
+/// The step a picture is made at for a longer side of `long` device pixels — the window's own
+/// rule (fitSrc), so the picture made ahead is the one it will ask for.
+fn step_for(long: f64) -> u32 {
+ FITS.iter()
+ .copied()
+ .find(|&f| f64::from(f) >= long)
+ .unwrap_or(FITS[FITS.len() - 1])
+}
+
+/// The steps one photo is shown at: in the grid (the whole cell when fitted, cropped to fill a
+/// square otherwise) and in the viewer (as large as the stage allows, never past 1.5×).
+fn steps_of(p: &Photo, s: Shown) -> (u32, u32) {
+ let (w, h) = (p.width.max(1) as f64, p.height.max(1) as f64);
+ let r = w / h;
+ let tile = if s.fit {
+ s.cell
+ } else {
+ s.cell * (w.max(h) / w.min(h))
+ };
+ let vw = s.stage_w.min(s.stage_h * r).min(w * 1.5);
+ (step_for(tile), step_for(vw.max(vw / r) * s.dpr))
+}
+
+/// Which `prepare` is current: a newer one (the window resized, zoomed) stops the older.
+static PREPARING: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+static LAST_SHOWN: Mutex<Option<Shown>> = Mutex::new(None);
+
+/// Makes every picture the window is about to show before it is shown, as Photos keeps its
+/// thumbnails ready: the grid's for the whole library, the viewer's for the newest 600 — newest
+/// first, what is on disk skipped, one core each. Made the first time a photo was seen, a tile
+/// came in soft and turned sharp, and a photo opened on its thumbnail and snapped to the sharp
+/// picture: the glitch in both. Started again whenever what is shown changes, and after a sync.
+#[tauri::command]
+pub fn photos_prepare(shown: Shown, app: AppHandle) {
+ {
+ let mut last = LAST_SHOWN
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if *last == Some(shown) {
+ return;
+ }
+ *last = Some(shown);
+ }
+ prepare(app);
+}
+
+/// Prepare again with what the window last said it shows (after a sync brought new photos).
+pub fn prepare(app: AppHandle) {
+ let Some(shown) = *LAST_SHOWN
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ else {
+ return;
+ };
+ let mine = PREPARING.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
+ tauri::async_runtime::spawn(async move {
+ use futures_util::StreamExt;
+ let photos = {
+ let data = app.state::<Data>();
+ let library = data.0.lock().await;
+ library.photos(View::Library).unwrap_or_default()
+ };
+ let fit_dir = crate::state_dir(&app).join("photos").join("fit");
+ let wanted: Vec<(String, u32)> = photos
+ .iter()
+ .filter(|p| p.kind != quince_core::photos::Kind::Video)
+ .map(|p| (p.id.clone(), steps_of(p, shown).0))
+ .chain(
+ photos
+ .iter()
+ .filter(|p| p.kind != quince_core::photos::Kind::Video)
+ .take(600)
+ .map(|p| (p.id.clone(), steps_of(p, shown).1)),
+ )
+ .filter(|(id, step)| !fit_dir.join(step.to_string()).join(id).exists())
+ .collect();
+ futures_util::stream::iter(wanted)
+ .for_each_concurrent(4, |(id, step)| {
+ let app = app.clone();
+ async move {
+ if PREPARING.load(std::sync::atomic::Ordering::SeqCst) != mine {
+ return;
+ }
+ let _ = crate::cpu::ahead(fitted(&app, &id, step)).await;
+ }
+ })
+ .await;
+ });
+}
+
async fn new_link(
http: &reqwest::Client,
root: &str,
@@ -395,6 +573,16 @@ 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())
}
+/// Every photo of one burst, in the order they were shot — what "View all" shows.
+#[tauri::command]
+pub async fn photos_burst(burst: String, data: State<'_, Data>) -> UiResult<Vec<Photo>> {
+ data.0
+ .lock()
+ .await
+ .burst_photos(&burst)
+ .map_err(|e| e.to_string())
+}
+
/// The albums the person made, each with how many photos it holds.
#[tauri::command]
pub async fn photos_albums(
@@ -1721,6 +1909,29 @@ mod tests {
assert_eq!(byte_range(None, 0, all), None);
}
+ /// The steps made ahead are the ones the window asks for (fitSrc, tileSrc, viewSrc).
+ #[test]
+ fn steps_are_the_window_s() {
+ let p: Photo = serde_json::from_value(serde_json::json!({
+ "id": "a", "master": "m", "takenAt": 0, "kind": "image", "width": 4032, "height": 3024,
+ "favorite": false, "hidden": false, "deleted": false, "subtype": 0
+ }))
+ .unwrap();
+ let shown = Shown {
+ cell: 180.0,
+ fit: false,
+ stage_w: 1300.0,
+ stage_h: 800.0,
+ dpr: 1.0,
+ };
+ // A square crop of a 4:3 photo reaches 240 along its long side; the stage draws it
+ // 1066 wide (800 high × 4/3).
+ assert_eq!(steps_of(&p, shown), (256, 1536));
+ assert_eq!(steps_of(&p, Shown { fit: true, ..shown }).0, 256);
+ assert_eq!(step_for(5000.0), 3840);
+ assert_eq!(step_for(100.0), 128);
+ }
+
#[test]
fn a_fitted_picture_is_asked_for_by_its_step_only() {
assert_eq!(
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 435c7dd..7c2b1bd 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -97,6 +97,11 @@ 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 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 }) =>
+ invoke<void>("photos_prepare", { shown }),
+ /** Every photo of one burst, in the order they were shot. */
+ photosBurst: (burst: string) => invoke<Photo[]>("photos_burst", { burst }),
/** 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 }),
@@ -622,6 +627,11 @@ export type Photo = {
deletedAt: number | null;
/** In Recently Deleted: when Apple deletes it for good, unix seconds. */
expungeAt?: number | null;
+ /** The burst it was shot in; a burst shows as its chosen photo. */
+ burst?: string | null;
+ burstPick?: boolean;
+ /** How many photos its burst holds. */
+ burstCount?: number;
/** Its title and caption, as typed in Photos' Info. */
title?: string | null;
caption?: string | null;
diff --git a/src/lib/motion.ts b/src/lib/motion.ts
deleted file mode 100644
index cf959cd..0000000
--- a/src/lib/motion.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- * An animation that can never flash.
- *
- * WebKitGTK hands an animation to its compositor a frame after it is asked for, and takes it
- * back a frame after it ends. For that frame the element is drawn as its own style says, not
- * as the animation does: a backdrop fading in drew fully black for one frame before its fade
- * began, and a viewer fading out drew fully there for one frame after it had gone — the
- * whole-window flicker on every open and close, frame by frame in his recordings.
- *
- * So the element's own style is always where the animation is: its first frame before the
- * animation starts, its last frame once the engine says it is running (`ready`). Whenever the
- * engine draws the element without the animation, it draws the right thing.
- */
-export function glide(
- el: HTMLElement,
- frames: [Keyframe, Keyframe],
- options: KeyframeAnimationOptions,
-): Animation {
- const [from, to] = frames;
- set(el, from);
- const a = el.animate(frames, { ...options, fill: "both" });
- a.ready.then(
- () => {
- if (a.playState !== "idle") set(el, to);
- },
- () => {},
- );
- // Done, it lets go: its last frame is the element's own style by then, so nothing moves —
- // and nothing held over that style (a zoom writes the photo's transform itself).
- a.finished.then(
- () => {
- set(el, to);
- a.cancel();
- },
- () => {},
- );
- return a;
-}
-
-function set(el: HTMLElement, frame: Keyframe) {
- for (const [k, v] of Object.entries(frame)) {
- if (k === "offset" || k === "easing" || k === "composite") continue;
- el.style.setProperty(k.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`), v == null ? "" : String(v));
- }
-}
diff --git a/src/screens/PhotosView.tsx b/src/screens/PhotosView.tsx
index cb4da01..4cd06f1 100644
--- a/src/screens/PhotosView.tsx
+++ b/src/screens/PhotosView.tsx
@@ -7,7 +7,7 @@ import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useStat
import { listen } from "@tauri-apps/api/event";
import { getCurrentWebview } from "@tauri-apps/api/webview";
import { open as openFileDialog } from "@tauri-apps/plugin-dialog";
-import { ChevronLeft, ChevronRight, CopyMinus, CopyPlus, Download, Clock, Heart, ImagePlus, Images, Info, Minus, Play, Plus, RotateCcw, Scan, Trash2, EyeOff, ArrowDownUp, MonitorPlay, Square, RectangleHorizontal, Star, Layers, Search as SearchIcon, Folder as FolderIcon, Aperture, Video, X, type LucideIcon } from "lucide-react";
+import { ChevronLeft, ChevronRight, CopyMinus, CopyPlus, Download, Clock, Heart, ImagePlus, Images, Info, Minus, Play, Plus, RotateCcw, Scan, Trash2, EyeOff, ArrowDownUp, MonitorPlay, Square, RectangleHorizontal, Star, Layers, Search as SearchIcon, Folder as FolderIcon, Aperture, Video, X, CalendarDays, type LucideIcon } from "lucide-react";
import {
api,
messageOf,
@@ -27,8 +27,8 @@ import { Portal } from "../components/Portal";
import { Slideshow } from "./photos/Slideshow";
import { useAsk } from "./photos/Ask";
import { VideoPlayer } from "./photos/VideoPlayer";
+import { JumpTo, type MonthCover } from "./photos/JumpTo";
import { tintFrom } from "../lib/tint";
-import { glide } from "../lib/motion";
import { DownloadOptions, type Want } from "./photos/DownloadOptions";
import { AdjustDate } from "./photos/AdjustDate";
@@ -124,7 +124,7 @@ const fitFrame = (p: Photo): React.CSSProperties =>
/**
* The viewer's filmstrip, as icloud.com's: the photos either side as narrow slips, the one shown
* wider in the middle; a click goes to it. Only the sixty or so nearest are built, and the
- * strip glides on the compositor to keep the one shown in the middle.
+ * strip moves at once to keep the one shown in the middle (animated, it flickered on his screen).
*/
const SLIP = 26;
const SHOWN = 54;
@@ -134,7 +134,7 @@ function Filmstrip({ photos, at, onPick }: { photos: Photo[]; at: number; onPick
const from = Math.max(0, at - REACH);
const to = Math.min(photos.length - 1, at + REACH);
// 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 glides to put the shown one's centre in the middle.
+ // 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);
const slips = [];
for (let i = from; i <= to; i++) {
@@ -150,7 +150,8 @@ function Filmstrip({ photos, at, onPick }: { photos: Photo[]; at: number; onPick
aria-current={i === at}
onClick={() => i !== at && onPick(i)}
>
- <img src={fitSrc(p.id, (i === at ? SHOWN : SLIP * 2) * (window.devicePixelRatio || 1))} alt="" loading="lazy" decoding="async" draggable={false} />
+ {/* At once, never lazily: a slip coming into the strip showed empty for a moment. */}
+ <img src={fitSrc(p.id, (i === at ? SHOWN : SLIP * 2) * (window.devicePixelRatio || 1))} alt="" decoding="async" draggable={false} />
</button>,
);
}
@@ -258,6 +259,7 @@ const Tile = memo(function Tile({
cell: number;
act: Acts;
}) {
+ const born = useRef(performance.now());
return (
<button
role="listitem"
@@ -305,7 +307,18 @@ const Tile = memo(function Tile({
{/* 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 — and made the size it is
drawn at, so the engine never shrinks it. */}
- <img src={tileSrc(photo, cell, fit)} alt="" decoding="async" draggable={false} />
+ <img
+ src={tileSrc(photo, cell, fit)}
+ alt=""
+ decoding="async"
+ draggable={false}
+ // Already made (as it nearly always is, see photos_prepare): there at once. Still on
+ // its way: it fades in over the thumbnail rather than snapping from soft to sharp.
+ // Never made: the thumbnail stays.
+ onLoad={(e) => {
+ e.currentTarget.dataset.in = performance.now() - born.current > 80 ? "fade" : "now";
+ }}
+ />
{photo.kind === "video" && (
<span className="px-badge px-duration">
<Play size={10} strokeWidth={0} fill="currentColor" aria-hidden="true" />
@@ -332,7 +345,6 @@ const Month = memo(function Month({
anchor,
deleted,
eager,
- across,
fit,
cell,
act,
@@ -343,7 +355,6 @@ const Month = memo(function Month({
anchor: number | null;
deleted: boolean;
eager: boolean;
- across: number;
fit: boolean;
cell: number;
act: Acts;
@@ -393,7 +404,13 @@ const Month = memo(function Month({
})}
</div>
) : (
- <div className="px-later" style={{ "--rows": Math.ceil(items.length / across) } as React.CSSProperties} aria-hidden="true" />
+ // Not built yet (far from the screen): its tiles as plain boxes on the very grid the photos
+ // will use, so a fast scroll shows photos on their way — never an empty page.
+ <div className="px-grid px-later" aria-hidden="true">
+ {items.map(({ photo }) => (
+ <div key={photo.id} className="px-ph" />
+ ))}
+ </div>
)}
</section>
);
@@ -427,6 +444,12 @@ export function PhotosView() {
});
/** The view's photos as read; `photos`, below, is them in the order chosen to show. */
const [raw, setPhotos] = useState<Photo[] | null>(null);
+ /**
+ * 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
+ * closes) brings the library back where it was. `from` is the chosen photo to come back to.
+ */
+ const [inBurst, setInBurst] = useState<{ from: string; count: number } | null>(null);
const [counts, setCounts] = useState<Partial<Record<PhotoView, number>>>({});
const [error, setError] = useState<string | null>(null);
const [zoom, setZoom] = useState(1);
@@ -500,14 +523,17 @@ export function PhotosView() {
// 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 ? sortList(raw, sort) : raw),
- [raw, sort?.by, sort?.oldest], // eslint-disable-line react-hooks/exhaustive-deps
+ () => (raw && sort && !inBurst ? sortList(raw, sort) : raw),
+ [raw, sort?.by, sort?.oldest, inBurst !== null], // eslint-disable-line react-hooks/exhaustive-deps
);
// 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 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),
@@ -529,7 +555,10 @@ export function PhotosView() {
// Grouped by month, as the library reads; an album is one grid in its own order.
const months = useMemo(() => {
const out: { label: string; items: { photo: Photo; index: number }[] }[] = [];
- if (drawn.album) return [{ label: "", items: (photos ?? []).map((photo, index) => ({ photo, index })) }];
+ // 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: "", items: (photos ?? []).map((photo, index) => ({ photo, index })) }];
(photos ?? []).forEach((photo, index) => {
// Rated is grouped by how many stars, as icloud.com's Rated page is.
const stars = photo.rating ?? 0;
@@ -575,18 +604,29 @@ export function PhotosView() {
const origin = useRef<DOMRect | null>(null);
const closing = useRef(false);
/**
- * While a photo is open the grid behind it is not drawn at all (content-visibility): each
- * step to the next photo moved the selection in it, and the engine laid out and painted
- * thousands of tiles no one could see — 80 ms a step, the stutter in going through photos.
- * It keeps its place and state, and is back the moment the viewer starts to close.
+ * The grid behind a photo that has finished opening is not painted (visibility): WebKit
+ * painted every tile under the opaque viewer on each step to the next photo, 80 ms a step.
+ * Only while the photo rests — never while it opens or closes. Hidden with content-visibility
+ * instead, the grid was dropped from the page: an open showed it one frame and then an empty
+ * background under the fading backdrop, and a close brought it back over several frames,
+ * dropping out again in one (his recording: 26 → 61 → 118 → 33 → 145) — the flicker on every
+ * open and close. Visibility keeps its layout and its decoded pictures, so it is back whole in
+ * the very frame the close begins.
*/
- const [leaving, setLeaving] = useState(false);
+ const gridBehind = (on: boolean) => {
+ const grid = scroller.current;
+ if (!grid) return;
+ if (on) grid.setAttribute("data-behind", "");
+ else grid.removeAttribute("data-behind");
+ };
useEffect(() => {
- if (open === null) setLeaving(false);
+ if (open === null) gridBehind(false);
}, [open === null]); // eslint-disable-line react-hooks/exhaustive-deps
// A close still running: its animations and its fallback, so a photo opened in the middle
// of it is not shut by the close finishing, nor left faded out by it.
const closingRun = useRef<{ anims: Animation[]; timer: number } | null>(null);
+ /** Every tile lifted for a photo's flight put back. */
+ const land = () => document.querySelectorAll(".px-tile[data-lifted]").forEach((t) => t.removeAttribute("data-lifted"));
const stopClosing = () => {
const run = closingRun.current;
if (!run) return;
@@ -629,33 +669,16 @@ export function PhotosView() {
};
};
const still = () => typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
- const spring = () => getComputedStyle(document.documentElement).getPropertyValue("--spring-smooth").trim() || "ease-out";
- // From the shown picture's box to a tile's: the transform that lays one on the other.
- const toTile = (img: HTMLElement, tile: DOMRect) => {
- const r = img.getBoundingClientRect();
- if (!r.width || !r.height) return null;
- const k = Math.max(tile.width / r.width, tile.height / r.height);
- const dx = tile.left + tile.width / 2 - (r.left + r.width / 2);
- const dy = tile.top + tile.height / 2 - (r.top + r.height / 2);
- return `translate(${dx}px, ${dy}px) scale(${k})`;
- };
+ // 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
+ // shown during the move — still showed him a flicker in WebKitGTK on Hyprland. Opened, the
+ // grid behind it is left unpainted (gridBehind); it is painted again before the viewer goes.
useLayoutEffect(() => {
if (open === null) return;
- const from = origin.current;
origin.current = null;
const el = viewer.current;
- // A viewer hidden as its last close ended, opened again before it went: shown again.
if (el) el.style.visibility = "";
- if (!from || !el || still() || typeof el.animate !== "function") return;
- // The photo's whole frame moves — the screen-sized picture and the whole one over it
- // together. Moving the one alone, the whole one (already on disk) stood full size over
- // it as it grew: two photos, torn.
- const img = el.querySelector<HTMLElement>(".px-pan, .px-video");
- const t = img && toTile(img, from);
- if (img && t) glide(img, [{ transform: t }, { transform: "none" }], { duration: 460, easing: spring() });
- for (const part of el.querySelectorAll<HTMLElement>(".px-backdrop, .px-viewer-bar, .px-nav, .px-info, .px-strip")) {
- glide(part, [{ opacity: "0" }, { opacity: "1" }], { duration: 160, easing: "ease-out" });
- }
+ gridBehind(true);
}, [open !== null]); // eslint-disable-line react-hooks/exhaustive-deps
// The window takes the viewer's near-black while it is open, and the app's colour again
@@ -667,54 +690,10 @@ export function PhotosView() {
}, [open !== null]); // eslint-disable-line react-hooks/exhaustive-deps
const close = useCallback(() => {
- // The grid back in the page first (see `behind`): the photo goes back into its tile, which
- // must be laid out to be found.
- document.querySelector(".px-scroll")?.removeAttribute("data-behind");
- setLeaving(true);
- const el = viewer.current;
- const current = open !== null ? photos?.[open] : null;
- const tile = current ? document.querySelector<HTMLElement>(`.px-tile[data-id="${CSS.escape(current.id)}"]`) : null;
- const img = el?.querySelector<HTMLElement>(".px-pan, .px-video");
- const box = tile?.getBoundingClientRect();
- const scroller = tile?.closest(".px-scroll")?.getBoundingClientRect();
- // Only back into a tile that is on screen; otherwise the viewer just fades.
- const seen = box && scroller && box.bottom > scroller.top && box.top < scroller.bottom;
- if (!el || closing.current || still() || typeof el.animate !== "function") {
- setOpen(null);
- return;
- }
- closing.current = true;
- const done = () => {
- const run = closingRun.current;
- if (!run) return;
- closingRun.current = null;
- closing.current = false;
- // Hidden in the same moment the animations end, with their last frame kept as real
- // styles: an ended animation let WebKit draw the photo at full size for one frame
- // before the viewer went — a whole-window flash on every close.
- if (el) {
- for (const a of run.anims) {
- try {
- a.commitStyles();
- } catch {
- // An element already gone has nothing to keep.
- }
- }
- el.style.visibility = "hidden";
- }
- setOpen(null);
- };
- const t = seen && img ? toTile(img, box) : null;
- const parts = [...el.querySelectorAll<HTMLElement>(".px-backdrop, .px-viewer-bar, .px-nav, .px-info, .px-strip")];
- const anims = parts.map((part) => glide(part, [{ opacity: "1" }, { opacity: "0" }], { duration: 140, easing: "ease-in" }));
- const last = t && img
- ? glide(img, [{ transform: "none" }, { transform: t }], { duration: 340, easing: spring() })
- : glide(el, [{ opacity: "1" }, { opacity: "0" }], { duration: 200, easing: "ease-in" });
- anims.push(last);
- last.onfinish = done;
- // A finish that never comes (a hidden window stops the clock) must not leave it open.
- closingRun.current = { anims, timer: window.setTimeout(done, 600) };
- }, [open, photos]);
+ gridBehind(false);
+ land();
+ setOpen(null);
+ }, []); // eslint-disable-line react-hooks/exhaustive-deps
const step = useCallback(
(by: number) =>
setOpen((at) => {
@@ -759,6 +738,62 @@ export function PhotosView() {
}, glide ? 340 : 160);
});
};
+ const viewBurst = async (p: Photo) => {
+ if (!p.burst) return;
+ try {
+ const list = await api.photosBurst(p.burst);
+ reads.current++; // a sync's read landing now must not put the library back over it
+ setPhotos(list);
+ setInBurst({ from: p.id, count: list.length });
+ // Opened by the photo, not a place: the list is drawn as it is shown.
+ setReopen(p.id);
+ burstOpen.current = true;
+ } catch (e) {
+ setError(messageOf(e));
+ }
+ };
+ const leaveBurst = async (keepOpen: boolean) => {
+ const back = inBurst?.from;
+ setInBurst(null);
+ burstOpen.current = false;
+ await read().catch(() => {});
+ if (keepOpen && back) setReopen(back);
+ };
+ /** A photo to open again once the library is back (after a burst). */
+ const [reopen, setReopen] = useState<string | null>(null);
+ useEffect(() => {
+ if (!reopen || !photos) return;
+ const at = photos.findIndex((x) => x.id === reopen);
+ setReopen(null);
+ if (at >= 0) setOpen(at);
+ }, [reopen, photos]);
+ // No picture anywhere in Photos — tile, slip, cover — ever shows the engine's broken box: one
+ // listener (errors do not bubble, so it listens on the way down) marks any that fails, and the
+ // style draws nothing for it; what is under it shows. The viewer tries the thumbnail first.
+ useEffect(() => {
+ const failed = (e: Event) => {
+ const img = e.target;
+ if (img instanceof HTMLImageElement && img.closest(".px, .px-viewer, .px-jump, .px-show") && !img.classList.contains("px-shown")) {
+ img.dataset.failed = "";
+ }
+ };
+ document.addEventListener("error", failed, true);
+ return () => document.removeEventListener("error", failed, true);
+ }, []);
+ // However the viewer went (closed, its last photo deleted, another view chosen), no tile is
+ // left lifted out after it.
+ useEffect(() => {
+ if (open !== null) return undefined;
+ const id = requestAnimationFrame(land);
+ return () => cancelAnimationFrame(id);
+ }, [open === null]); // eslint-disable-line react-hooks/exhaustive-deps
+ // Closing the viewer inside a burst brings the library back.
+ useEffect(() => {
+ if (open === null && inBurst) void leaveBurst(false);
+ }, [open === null]); // eslint-disable-line react-hooks/exhaustive-deps
+ /** A Live Photo's moving part playing over it. */
+ const [moving, setMoving] = useState<string | null>(null);
+ useEffect(() => setMoving(null), [shown?.id]);
/** 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.
@@ -1078,9 +1113,9 @@ export function PhotosView() {
// its thumbnail and screen-sized picture, and the whole one follows.
if (p.kind !== "video") await Promise.race([warm(p), new Promise((r) => window.setTimeout(r, 150))]);
stopClosing();
- setLeaving(false);
const tile = document.querySelector<HTMLElement>(`.px-tile[data-id="${CSS.escape(p.id)}"]`);
origin.current = tile?.getBoundingClientRect() ?? null;
+ land();
setOpen(index);
};
@@ -1616,6 +1651,30 @@ export function PhotosView() {
// Scrolled, the line under the title names the month at the top of the view, as Photos
// does; read once a frame at most, and set only when it changes.
const [here, setHere] = useState<string | null>(null);
+ /** The month picker, open under its button. */
+ const [jumping, setJumping] = useState<DOMRect | null>(null);
+ // Each month the grid shows, with a photo from it, for the picker: the grid's own months, so
+ // the two always agree.
+ const monthCovers = useMemo<MonthCover[]>(() => {
+ if (drawn.album || drawn.view === "rated") return [];
+ return months
+ .filter((m) => m.label && m.items.length)
+ .map((m) => {
+ const cover = m.items[0].photo;
+ const d = new Date(sortKey(cover, sort?.by ?? "taken") * 1000);
+ return { label: m.label, year: d.getFullYear(), month: d.getMonth(), cover };
+ });
+ }, [months, drawn, sort?.by]);
+ const goToMonth = (label: string) => {
+ const el = scroller.current;
+ const at = el?.querySelector<HTMLElement>(`.px-month[aria-label="${CSS.escape(label)}"]`);
+ // Measured against the scroller itself: offsetTop counts from whatever positioned box
+ // happens to hold the month, which is not always the scroller.
+ if (el && at) {
+ const top = at.getBoundingClientRect().top - el.getBoundingClientRect().top + el.scrollTop - 4;
+ el.scrollTo({ top, behavior: still() ? "auto" : "smooth" });
+ }
+ };
const scroller = useRef<HTMLDivElement | null>(null);
const looking = useRef(false);
// Read a few times a second, not every frame, and by halving rather than going down every
@@ -1663,11 +1722,26 @@ export function PhotosView() {
return () => window.removeEventListener("keydown", onKey);
}, []);
- const title = drawn.query
- ? `“${drawn.query}”`
- : drawn.album
- ? (album?.id === drawn.album.id ? album.name : drawn.album.name)
- : [...VIEWS, ...MEDIA, ...UTILITIES].find((v) => v.key === drawn.view)?.label ?? "Photos";
+ // A view chosen whose photos have not come yet. Nearly always they come within a frame or
+ // two and nothing in between is shown; when the app is busy and they take longer, the new
+ // view's title is up at once with its tiles as plain boxes — never the last view lingering
+ // under the new choice, which read as the app not having heard the click.
+ const switching = drawn.view !== view || (drawn.album?.id ?? null) !== (album?.id ?? null) || drawn.query !== searching;
+ const [slow, setSlow] = useState(false);
+ useEffect(() => {
+ setSlow(false);
+ if (!switching) return undefined;
+ const t = window.setTimeout(() => setSlow(true), 120);
+ return () => window.clearTimeout(t);
+ }, [switching, view, album?.id, searching]);
+ const waiting = switching && slow;
+ const shownAs = waiting ? { view, album, query: searching } : drawn;
+ const title = shownAs.query
+ ? `“${shownAs.query}”`
+ : shownAs.album
+ ? (album?.id === shownAs.album.id ? album.name : shownAs.album.name)
+ : [...VIEWS, ...MEDIA, ...UTILITIES].find((v) => v.key === shownAs.view)?.label ?? "Photos";
+ const waitingFor = waiting ? Math.min(84, album ? (albums.find(([a]) => a.id === album.id)?.[1] ?? 21) : (counts[view] ?? 21)) : 0;
// A view arrives at its top, not wherever the last one was scrolled to.
useLayoutEffect(() => {
if (scroller.current) scroller.current.scrollTop = 0;
@@ -1676,6 +1750,31 @@ export function PhotosView() {
// A cell's width in device pixels, for the size each tile's picture is made at; in steps of
// 32, so a window being resized does not redraw every tile on every frame.
const [gridWidth, setGridWidth] = useState(0);
+ // The header's height, for the room the grid leaves under it: one row in a wide window, two
+ // when the controls go under the title.
+ const bar = useRef<HTMLElement | null>(null);
+ useLayoutEffect(() => {
+ const el = bar.current;
+ const main = el?.parentElement;
+ if (!el || !main) return undefined;
+ // Written only when it changes, and a frame later: the room it makes changes the grid's own
+ // box, which its own watcher sees — in the same frame, a loop the engine reports.
+ let frame = 0;
+ const measure = () => {
+ cancelAnimationFrame(frame);
+ frame = requestAnimationFrame(() => {
+ const h = `${Math.ceil(el.getBoundingClientRect().height)}px`;
+ if (main.style.getPropertyValue("--bar") !== h) main.style.setProperty("--bar", h);
+ });
+ };
+ measure();
+ const watch = new ResizeObserver(measure);
+ watch.observe(el);
+ return () => {
+ cancelAnimationFrame(frame);
+ watch.disconnect();
+ };
+ }, []);
useLayoutEffect(() => {
const el = scroller.current;
if (!el) return undefined;
@@ -1686,6 +1785,16 @@ export function PhotosView() {
return () => watch.disconnect();
}, []);
const cell = Math.round(((gridWidth || 1200) / across) * (window.devicePixelRatio || 1));
+ // 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(() => {});
+ }, 400);
+ return () => window.clearTimeout(t);
+ }, [cell, fit, open !== null]); // 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) => {
@@ -1978,7 +2087,7 @@ export function PhotosView() {
)}
{/* As in Photos on macOS 26: the title and the controls float over the library, which
scrolls beneath them and fades out at the top edge. */}
- <header className="px-bar">
+ <header className="px-bar" ref={bar}>
<div className="px-heading">
<h1>{title}</h1>
{selected.length > 0 ? (
@@ -1991,6 +2100,7 @@ export function PhotosView() {
)
)}
</div>
+ <div className="px-tools">
{view === "recentlyDeleted" && !album && photos && photos.length > 0 && (
// Recently Deleted's own toolbar, in Photos' words: Recover and Delete for what is
// selected, Delete All when nothing is.
@@ -2047,6 +2157,21 @@ export function PhotosView() {
</button>
</div>
)}
+ {monthCovers.length > 1 && (
+ <div className="px-capsule">
+ <button
+ className="px-cap"
+ aria-label="Go to a Month"
+ aria-haspopup="dialog"
+ aria-expanded={jumping !== null}
+ title="Go to a month"
+ onClick={(e) => setJumping(jumping ? null : e.currentTarget.getBoundingClientRect())}
+ >
+ <CalendarDays size={16} strokeWidth={1.9} aria-hidden="true" />
+ </button>
+ </div>
+ )}
+ {jumping && <JumpTo months={monthCovers} at={jumping} current={here ?? monthCovers[0]?.label ?? null} onPick={goToMonth} onClose={() => setJumping(null)} />}
<div className="px-capsule" role="group" aria-label="Zoom">
<button className="px-cap" aria-label="Zoom Out" title="Zoom Out (Ctrl −)" disabled={zoom === 0} onClick={() => setZoom((z) => Math.max(0, z - 1))}>
<Minus size={15} strokeWidth={2.2} aria-hidden="true" />
@@ -2086,6 +2211,7 @@ export function PhotosView() {
</button>
)}
</label>
+ </div>
</header>
{error && (
@@ -2115,8 +2241,18 @@ export function PhotosView() {
onClick={(e) => {
// A click on the space between photos lets the selection go, as in Photos.
if (!(e.target as HTMLElement).closest(".px-tile")) setChosen(new Set());
- }} data-fit={fit || undefined} data-behind={(open !== null && !leaving) || undefined} style={{ "--across": across } as React.CSSProperties}>
- {months.map((m, k) => (
+ }} data-fit={fit || undefined} style={{ "--across": across } as React.CSSProperties}>
+ {waiting && (
+ <div className="px-month" aria-busy="true">
+ <h2 className="px-month-title px-month-title-ph" aria-hidden="true">&nbsp;</h2>
+ <div className="px-grid px-later" aria-hidden="true">
+ {Array.from({ length: waitingFor }, (_, i) => (
+ <div key={i} className="px-ph" />
+ ))}
+ </div>
+ </div>
+ )}
+ {!waiting && months.map((m, k) => (
<Month
key={`${k}/${m.label}`}
label={m.label}
@@ -2125,7 +2261,6 @@ export function PhotosView() {
anchor={anchor.current}
deleted={drawn.view === "recentlyDeleted" && !drawn.album}
eager={k < 3}
- across={across}
fit={fit}
cell={cell}
act={act}
@@ -2259,7 +2394,38 @@ export function PhotosView() {
>
{/* The picture made the size the stage draws it at — every pixel used, none
thrown away by the engine — over the thumbnail until it is decoded. */}
- <img key={shown.id} className="px-shown" src={viewSrc(shown)} alt={shown.filename ?? ""} decoding="async" draggable={false} style={fitted(shown)} />
+ <img
+ key={shown.id}
+ className="px-shown"
+ src={viewSrc(shown)}
+ // What was asked for, kept whatever the fallback below does to `src`.
+ data-picture={viewSrc(shown)}
+ alt={shown.filename ?? ""}
+ decoding="async"
+ draggable={false}
+ style={fitted(shown)}
+ // Never the engine's broken-picture box (a white frame, a question mark, the
+ // file's name): a picture that will not come falls back to the thumbnail,
+ // and past that shows nothing over the thumbnail already painted under it.
+ onError={(e) => {
+ const img = e.currentTarget;
+ const thumb = pictureSrc(shown.id, "thumb");
+ if (!img.src.includes("thumb")) img.src = thumb;
+ else img.dataset.failed = "";
+ }}
+ />
+ {moving === shown.id && videoBase && (
+ // The moving part, laid exactly over the still, played once and gone.
+ <video
+ key={`${shown.id}-live`}
+ className="px-live"
+ src={`${videoBase}/${shown.id}/video`}
+ autoPlay
+ playsInline
+ onEnded={() => setMoving(null)}
+ onError={() => setMoving(null)}
+ />
+ )}
{/* Zoomed in, the whole picture: only then are its own pixels the ones seen. */}
{zoomed && (
<img
@@ -2275,6 +2441,41 @@ export function PhotosView() {
)}
</div>
)}
+ {/* What kind of photo it is, as Photos marks it at the stage's corner: a Live
+ Photo plays its moving part while the pointer rests on LIVE; a burst's BURST
+ goes through all of it. */}
+ {shown.kind === "live" && videoBase && (
+ <button
+ className={`px-mark${moving === shown.id ? " is-on" : ""}`}
+ aria-label="Play Live Photo"
+ onPointerEnter={() => setMoving(shown.id)}
+ onFocus={() => setMoving(shown.id)}
+ onClick={() => setMoving(shown.id)}
+ >
+ <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true">
+ <circle cx="8" cy="8" r="2.2" fill="currentColor" />
+ <circle cx="8" cy="8" r="4.6" fill="none" stroke="currentColor" strokeWidth="1.3" />
+ <circle cx="8" cy="8" r="7" fill="none" stroke="currentColor" strokeWidth="1.1" strokeDasharray="1.2 1.6" />
+ </svg>
+ LIVE
+ </button>
+ )}
+ {shown.burst && (shown.burstCount ?? 0) > 1 && !inBurst && (
+ <button className="px-mark" aria-label={`View all ${shown.burstCount} photos in this burst`} onClick={() => void viewBurst(shown)}>
+ <Layers size={13} aria-hidden="true" />
+ BURST
+ <span className="px-mark-count">{shown.burstCount}</span>
+ </button>
+ )}
+ {inBurst && (
+ <div className="px-mark is-burst" role="status">
+ <Layers size={13} aria-hidden="true" />
+ Burst · {(open ?? 0) + 1} of {inBurst.count}
+ <button className="px-mark-done" onClick={() => void leaveBurst(true)}>
+ Done
+ </button>
+ </div>
+ )}
{open !== null && open > 0 && (
<button className="px-nav is-prev" aria-label="Previous" onClick={() => step(-1)}>
<ChevronLeft size={22} />
diff --git a/src/screens/photos/JumpTo.tsx b/src/screens/photos/JumpTo.tsx
new file mode 100644
index 0000000..349e92a
--- /dev/null
+++ b/src/screens/photos/JumpTo.tsx
@@ -0,0 +1,94 @@
+/**
+ * Going to a month, as icloud.com's calendar button does: the years down the side, the chosen
+ * year's months as tiles with a photo from each, in the calendar's order. A tile takes the grid
+ * to that month. Only months the library has photos in are offered.
+ */
+import { useEffect, useMemo, useRef, useState } from "react";
+import { fitSrc, type Photo } from "../../lib/ipc";
+import { Portal } from "../../components/Portal";
+
+export type MonthCover = { label: string; year: number; month: number; cover: Photo };
+
+const SHORT = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+
+export function JumpTo({
+ months,
+ at,
+ current,
+ onPick,
+ onClose,
+}: {
+ months: MonthCover[];
+ /** The button it opened from. */
+ at: DOMRect;
+ /** The month at the top of the grid now. */
+ current: string | null;
+ onPick: (label: string) => void;
+ onClose: () => void;
+}) {
+ const years = useMemo(() => [...new Set(months.map((m) => m.year))].sort((a, b) => b - a), [months]);
+ const startYear = months.find((m) => m.label === current)?.year ?? years[0];
+ const [year, setYear] = useState(startYear);
+ const box = useRef<HTMLDivElement | null>(null);
+ const shown = months.filter((m) => m.year === year).sort((a, b) => a.month - b.month);
+
+ useEffect(() => {
+ box.current?.focus({ preventScroll: true });
+ const down = (e: MouseEvent) => {
+ if (!box.current?.contains(e.target as Node)) onClose();
+ };
+ const key = (e: KeyboardEvent) => {
+ if (e.key !== "Escape") return;
+ e.preventDefault();
+ e.stopPropagation();
+ onClose();
+ };
+ document.addEventListener("mousedown", down);
+ window.addEventListener("keydown", key, true);
+ return () => {
+ document.removeEventListener("mousedown", down);
+ window.removeEventListener("keydown", key, true);
+ };
+ }, [onClose]);
+
+ const dpr = window.devicePixelRatio || 1;
+ return (
+ <Portal>
+ <div
+ ref={box}
+ className="px-jump"
+ role="dialog"
+ aria-label="Go to a month"
+ tabIndex={-1}
+ style={{ top: at.bottom + 8, left: Math.max(8, Math.min(at.left - 120, window.innerWidth - 408)) }}
+ >
+ <div className="px-jump-years" role="tablist" aria-label="Years">
+ {years.map((y) => (
+ <button key={y} role="tab" aria-selected={y === year} className={`px-jump-year${y === year ? " is-on" : ""}`} onClick={() => setYear(y)}>
+ {y}
+ </button>
+ ))}
+ </div>
+ <div className="px-jump-body">
+ <h2 className="px-jump-title">{year}</h2>
+ <div className="px-jump-months">
+ {shown.map((m) => (
+ <button
+ key={m.label}
+ className={`px-jump-month${m.label === current ? " is-here" : ""}`}
+ aria-label={m.label}
+ onClick={() => {
+ onPick(m.label);
+ onClose();
+ }}
+ >
+ <img src={fitSrc(m.cover.id, 128 * dpr)} alt="" decoding="async" draggable={false} />
+ <span>{SHORT[m.month]}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+ </Portal>
+ );
+}
diff --git a/src/screens/photos/Slideshow.tsx b/src/screens/photos/Slideshow.tsx
index ad94b60..02b25a9 100644
--- a/src/screens/photos/Slideshow.tsx
+++ b/src/screens/photos/Slideshow.tsx
@@ -1,41 +1,87 @@
/**
* A slideshow, as Photos plays one: the photos one after another on black, each easing slowly
- * larger while it shows and fading into the next. Space pauses, the arrows step, Escape ends.
+ * 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.
*
- * Only opacity and transform move — the compositor's work — and the next picture is fetched
- * while the one before it shows, so a change never waits on a download.
+ * 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.
*/
import { useCallback, useEffect, useRef, useState } from "react";
import { ChevronLeft, ChevronRight, Pause, Play, X } from "lucide-react";
-import { pictureSrc, type Photo } from "../../lib/ipc";
+import { fitSrc, type Photo } from "../../lib/ipc";
const HOLD = 4000;
const FADE = 900;
+/** The picture a photo is shown at, whole on this screen. */
+const screenSrc = (p: Photo) => {
+ 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));
+};
+
+/** Fetched and decoded, by address. */
+const ready = new Map<string, Promise<void>>();
+const decode = (url: string) => {
+ let p = ready.get(url);
+ if (!p) {
+ const img = new Image();
+ img.decoding = "async";
+ img.src = url;
+ p = img.decode().catch(() => {});
+ ready.set(url, p);
+ }
+ return p;
+};
+
export function Slideshow({ photos, start, onClose }: { photos: Photo[]; start: number; onClose: () => void }) {
- const [at, setAt] = useState(Math.max(0, Math.min(start, photos.length - 1)));
+ // 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 still = typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
- const go = useCallback((by: number) => setAt((i) => (i + by + photos.length) % photos.length), [photos.length]);
+ const shown = useRef(first);
+
+ // To another photo, once its picture is decoded.
+ const asked = useRef(0);
+ const go = useCallback(
+ (by: number) => {
+ const to = (shown.current + by + list.length) % list.length;
+ 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);
+ });
+ },
+ [list],
+ );
+ 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 || photos.length < 2) return undefined;
+ if (!playing || list.length < 2) return undefined;
const t = window.setTimeout(() => go(1), HOLD);
return () => window.clearTimeout(t);
- }, [at, playing, go, photos.length]);
+ }, [at, playing, go, list.length]);
- // The next picture is fetched and decoded now, whole, so it is there when its turn comes.
+ // The next is on its way while this one shows.
useEffect(() => {
- const next = photos[(at + 1) % photos.length];
- 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]);
+ const next = list[(at + 1) % list.length];
+ if (next) void decode(screenSrc(next));
+ }, [at, list]);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
@@ -66,19 +112,9 @@ export function Slideshow({ photos, start, onClose }: { photos: Photo[]; start:
};
}, []); // eslint-disable-line react-hooks/exhaustive-deps
- // The one showing and the one before it, so the old fades out over the new.
- const [before, setBefore] = useState<number | null>(null);
- const shown = useRef(at);
- useEffect(() => {
- if (shown.current === at) return undefined;
- setBefore(shown.current);
- shown.current = at;
- const t = window.setTimeout(() => setBefore(null), FADE);
- return () => window.clearTimeout(t);
- }, [at]);
-
- const photo = photos[at];
+ const photo = list[at];
if (!photo) return null;
+ const old = leaving !== null ? list[leaving] : null;
return (
<div
className={`px-show${awake ? " is-awake" : ""}${still ? " is-still" : ""}`}
@@ -87,30 +123,13 @@ export function Slideshow({ photos, start, onClose }: { photos: Photo[]; start:
onMouseMove={wake}
onClick={wake}
>
- {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" />
- )}
+ {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}`}
className={`px-slide${playing ? "" : " is-paused"}`}
- src={pictureSrc(photo.id, "medium")}
+ src={screenSrc(photo)}
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} />
@@ -122,7 +141,7 @@ export function Slideshow({ photos, start, onClose }: { photos: Photo[]; start:
<ChevronRight size={18} />
</button>
<span className="px-show-count" aria-live="polite">
- {at + 1} of {photos.length}
+ {at + 1} of {list.length}
</span>
<button className="px-cap" aria-label="End Slideshow" title="End Slideshow (Esc)" onClick={onClose}>
<X size={17} />
diff --git a/src/styles/photos.css b/src/styles/photos.css
index 186e23d..2cdb2d5 100644
--- a/src/styles/photos.css
+++ b/src/styles/photos.css
@@ -92,13 +92,19 @@
inset: 0 0 auto 0;
z-index: 4;
display: flex;
+ /* A narrow window puts the controls on a row of their own, under the title, rather than
+ squeezing the title to a letter and folding its dates down over the photos. */
+ flex-wrap: wrap;
align-items: flex-start;
gap: 8px;
padding: 12px 16px 0 18px;
pointer-events: none;
}
.px-bar > * { pointer-events: auto; }
-.px-heading { margin-right: auto; min-width: 0; }
+.px-heading { margin-right: auto; min-width: 0; flex: 1 1 200px; }
+/* The controls, as one: beside the title in a wide window, all together under it in a narrow
+ one — never split between the two rows. */
+.px-tools { display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: flex-start; gap: 8px; max-width: 100%; }
.px-bar h1 {
margin: 0;
font-size: var(--t-22, 22px);
@@ -109,7 +115,7 @@
text-overflow: ellipsis;
white-space: nowrap;
}
-.px-span { margin: 1px 0 0; color: var(--text-2); font-size: var(--t-13); font-weight: 500; }
+.px-span { margin: 1px 0 0; color: var(--text-2); font-size: var(--t-13); font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* Liquid Glass, as Photos' toolbar has it: small capsules floating over the photos. The live
blur is kept to these few small, still surfaces — never to what moves, which WebKitGTK
@@ -203,7 +209,8 @@
flex: 1;
min-height: 0;
overflow-y: auto;
- padding: 80px 2px 24px;
+ /* Room for the header floating over it, however many rows it takes (--bar, measured). */
+ padding: calc(var(--bar, 68px) + 12px) 2px 24px;
}
.px-bar { isolation: isolate; }
.px-bar::before {
@@ -214,18 +221,8 @@
background: linear-gradient(to bottom, var(--bg) 0, var(--bg) 58%, color-mix(in srgb, var(--bg) 0%, transparent) 100%);
pointer-events: none;
}
-/* A month not yet built: one cell laid out on the very grid its photos will use, as tall as
- all its rows — square tiles, 2px between — so nothing moves when it is built. */
-.px-later {
- display: grid;
- grid-template-columns: repeat(var(--across, 7), minmax(0, 1fr));
- column-gap: 2px;
-}
-.px-later::before {
- content: "";
- aspect-ratio: 1 / var(--rows);
- margin-bottom: calc((var(--rows) - 1) * 2px);
-}
+/* A month not yet built: its tiles as plain boxes in the photos' own tone, on the same grid. */
+.px-ph { aspect-ratio: 1; background: color-mix(in srgb, var(--text) 7%, transparent); }
.px-month-title {
margin: 0;
padding: 12px 16px 8px;
@@ -252,11 +249,13 @@
.px-tile { display: grid; place-items: center; }
/* The picture's frame: the whole cell as a square, the photo's own shape when fitted. */
.px-pic { position: relative; display: block; width: 100%; height: 100%; overflow: hidden; }
-.px-pic img { width: 100%; height: 100%; object-fit: cover; display: block; }
+.px-pic img { width: 100%; height: 100%; object-fit: cover; display: block; opacity: 0; }
+/* The thumbnail (the frame's background) shows until the picture made for the tile is in. */
+.px-pic { background-size: cover; background-position: center; }
+.px-pic img[data-in] { opacity: 1; }
+.px-pic img[data-in="fade"] { transition: opacity 160ms ease-out; }
/* Whole photos, as icloud.com shows them: each in its own shape, with room around it. */
.px-scroll[data-fit] .px-grid { gap: 14px; padding: 0 14px; }
-.px-scroll[data-fit] .px-later { column-gap: 14px; padding: 0 14px; }
-.px-scroll[data-fit] .px-later::before { margin-bottom: calc((var(--rows) - 1) * 14px); }
.px-scroll[data-fit] .px-tile { background: transparent; overflow: visible; }
.px-scroll[data-fit] .px-pic { background: color-mix(in srgb, var(--text) 7%, transparent); }
/* Selected, as Photos marks it: an accent frame drawn inside the photo, over the picture. */
@@ -267,9 +266,13 @@
border: 3px solid var(--accent);
opacity: 0;
pointer-events: none;
- transition: opacity 90ms ease;
}
+/* At once, as Photos marks a selection: a fade begun as a photo opened was frozen half way
+ while the grid was not drawn, and finished as the photo flew back into it. */
.px-tile[aria-selected="true"] .px-pic::after { opacity: 1; }
+/* The tile a photo is flying out of or back into is lifted out while it flies, as Photos
+ does: the picture is in one place at a time, never the tile and the photo both. */
+.px-tile[data-lifted] .px-pic { visibility: hidden; }
.px-tile:focus-visible { outline: none; }
.px-tile:focus-visible .px-pic::after { opacity: 1; border-color: var(--accent-ring); }
.px-tile[aria-selected="true"]:focus-visible .px-pic::after { border-color: var(--accent); }
@@ -457,13 +460,17 @@
transform-origin: 50% 45%;
animation: px-arrive 900ms ease-out both, px-drift 4900ms linear both;
}
-.px-slide.is-leaving { animation: none; transform: scale(1.06); z-index: -1; }
+/* The one leaving dissolves away from where its drift ended, over the next fading in. */
+.px-slide.is-leaving { animation: px-leave 900ms ease-in-out both; transform: scale(1.06); z-index: 1; pointer-events: none; }
+@keyframes px-leave { from { opacity: 1; } to { opacity: 0; } }
+.px-show.is-still .px-slide.is-leaving { animation: none; opacity: 0; }
.px-slide.is-paused { animation-play-state: paused; }
@keyframes px-arrive { from { opacity: 0; } to { opacity: 1; } }
@keyframes px-drift { from { transform: scale(1); } to { transform: scale(1.06); } }
.px-show.is-still .px-slide { animation: none; }
.px-show-bar {
position: absolute;
+ z-index: 2;
left: 50%;
bottom: 28px;
transform: translateX(-50%);
@@ -678,14 +685,13 @@
left: 50%;
top: 0;
height: 44px;
- transition: transform 260ms var(--spring-smooth);
- will-change: transform;
+ /* No glide: the strip and its slips move to their places at once. Animated, they flickered on
+ his screen as the viewer's own open and close had (WebKitGTK on Hyprland). */
}
.px-slip {
position: absolute;
left: 0;
top: 2px;
- transition: transform 260ms var(--spring-smooth), width 260ms var(--spring-smooth), height 260ms var(--spring-smooth), top 260ms var(--spring-smooth), opacity 160ms ease;
width: 26px;
height: 40px;
padding: 0;
@@ -710,7 +716,6 @@
box-shadow: inset 0 0 0 2px var(--accent), inset 0 0 0 3px rgba(0, 0, 0, 0.35);
pointer-events: none;
}
-@media (prefers-reduced-motion: reduce) { .px-strip-run, .px-slip { transition: none; } }
/* Info's place and keywords. */
.px-place { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; font-variant-numeric: tabular-nums; }
@@ -988,5 +993,102 @@
.px-player-bar .px-scrub-fill, .px-player-bar .px-scrub-knob { background: #fff; }
.px-player-bar .px-scrub-tip { color: #fff; background: rgba(28, 28, 30, 0.9); }
-/* Behind an open photo the grid is kept but not drawn (see `leaving` in PhotosView). */
-.px-scroll[data-behind] { content-visibility: hidden; }
+/* Behind a photo at rest the grid is kept, laid out and decoded, but not painted (see
+ gridBehind in PhotosView) — never while a photo opens or closes. */
+.px-scroll[data-behind] { visibility: hidden; }
+
+/* What kind of photo it is, at the stage's corner, as Photos marks it: LIVE, BURST. */
+.px-mark {
+ position: absolute;
+ z-index: 3;
+ top: 62px;
+ left: 64px;
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ height: 24px;
+ padding: 0 10px;
+ border: 0;
+ border-radius: 12px;
+ font: 600 11px/1 var(--sf, system-ui);
+ letter-spacing: 0.04em;
+ color: #fff;
+ background: rgba(28, 28, 30, 0.62);
+ box-shadow: inset 0 0.5px 0 rgba(255, 255, 255, 0.14);
+ cursor: default;
+}
+.px-mark:hover, .px-mark.is-on { background: rgba(28, 28, 30, 0.82); }
+.px-mark-count { font-weight: 500; opacity: 0.7; letter-spacing: 0; }
+.px-mark.is-burst { letter-spacing: 0; font-weight: 600; padding-right: 4px; }
+.px-mark-done {
+ margin-left: 6px;
+ height: 18px;
+ padding: 0 9px;
+ border: 0;
+ border-radius: 9px;
+ font: 600 11px/1 var(--sf, system-ui);
+ color: #fff;
+ 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; }
+
+/* ---- going to a month: the years down the side, a year's months as tiles with a photo -- */
+.px-jump {
+ position: fixed;
+ z-index: 60;
+ display: grid;
+ grid-template-columns: 84px 1fr;
+ width: 400px;
+ max-height: min(460px, 70vh);
+ border-radius: 14px;
+ background: var(--sheet);
+ box-shadow: var(--glass-float);
+ overflow: hidden;
+ outline: none;
+ animation: px-jump-in 160ms cubic-bezier(0.32, 0.72, 0, 1) both;
+}
+@keyframes px-jump-in { from { opacity: 0; transform: translateY(-4px) scale(0.98); } }
+@media (prefers-reduced-motion: reduce) { .px-jump { animation: none; } }
+.px-jump-years { display: flex; flex-direction: column; gap: 2px; padding: 10px 8px; border-right: 1px solid var(--separator); overflow-y: auto; }
+.px-jump-year {
+ height: 30px;
+ border: 0;
+ border-radius: 8px;
+ font: 500 var(--t-13, 13px)/1 var(--sf, system-ui);
+ font-variant-numeric: tabular-nums;
+ color: var(--text);
+ background: transparent;
+}
+.px-jump-year:hover { background: color-mix(in srgb, var(--text) 7%, transparent); }
+.px-jump-year.is-on { background: color-mix(in srgb, var(--text) 12%, transparent); font-weight: 600; }
+.px-jump-body { padding: 12px 14px 14px; overflow-y: auto; }
+.px-jump-title { margin: 0 0 10px; font-size: var(--t-17, 17px); font-weight: 700; }
+.px-jump-months { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; }
+.px-jump-month {
+ position: relative;
+ aspect-ratio: 1.12;
+ padding: 0;
+ border: 0;
+ border-radius: 8px;
+ overflow: hidden;
+ background: color-mix(in srgb, var(--text) 8%, transparent);
+}
+.px-jump-month img { width: 100%; height: 100%; object-fit: cover; display: block; }
+.px-jump-month span {
+ position: absolute;
+ left: 7px;
+ bottom: 5px;
+ font: 600 12px/1 var(--sf, system-ui);
+ color: #fff;
+ text-shadow: 0 1px 3px rgba(0, 0, 0, 0.55);
+}
+.px-jump-month::after { content: ""; position: absolute; inset: 0; background: linear-gradient(transparent 55%, rgba(0, 0, 0, 0.38)); }
+.px-jump-month span { z-index: 1; }
+.px-jump-month:hover img { filter: brightness(1.08); }
+.px-jump-month.is-here { box-shadow: inset 0 0 0 2px var(--accent); }
+.px-jump-month:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+
+/* A picture that could not be had at all draws nothing — never the engine's broken box (a
+ white frame, a question mark, the file's name); what is under it shows. */
+img[data-failed] { content: url("data:image/gif;base64,R0lGODlhAQABAAAAACw="); }