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.

Videos stream as they download; search across every app; Windows builds

Yashwanth Kamireddi44cdeb201794
diff --git a/.uiverify/pending-writes.mjs b/.uiverify/pending-writes.mjs
index 8b571bc..d2530c6 100644
--- a/.uiverify/pending-writes.mjs
+++ b/.uiverify/pending-writes.mjs
@@ -26,6 +26,10 @@ await page.locator(".note-row", { hasText: "Curtains" }).first().click();
await page.waitForTimeout(300);
await page.evaluate(() => { window.__slowMove = 900; });
await page.getByRole("button", { name: "Folder for Curtains" }).click();
+// The move is out (Apple slow to answer, 900 ms) before anything is watched: a refresh is made
+// to land while it is out — timed from the move, not from opening the picker, which on a slow
+// run let the refresh land before the move began and the check measured nothing.
+await page.getByRole("option", { name: "Work" }).click();
await page.evaluate(() => {
window.__back = 0; window.__gone = false; window.__watching = true;
const tick = () => {
@@ -34,11 +38,9 @@ await page.evaluate(() => {
else if (window.__gone) window.__back++;
if (window.__watching) requestAnimationFrame(tick);
};
- requestAnimationFrame(tick);
- // A refresh finishing while the move is out, as Apple's push makes happen.
- setTimeout(() => window.__emit?.("quince://synced", { services: [], asOf: Math.floor(Date.now() / 1000), tookMs: 1 }), 350);
+ tick();
+ setTimeout(() => window.__emit?.("quince://synced", { services: [], asOf: Math.floor(Date.now() / 1000), tookMs: 1 }), 300);
});
-await page.getByRole("option", { name: "Work" }).click();
await page.waitForTimeout(800);
const r = await page.evaluate(() => { window.__watching = false; return { gone: window.__gone, back: window.__back }; });
ok(r.gone && r.back === 0, `a moved note leaves at once and does not come back while the move is out [${JSON.stringify(r)}]`);
diff --git a/.uiverify/photos-loading.mjs b/.uiverify/photos-loading.mjs
index 8443424..e0e9a45 100644
--- a/.uiverify/photos-loading.mjs
+++ b/.uiverify/photos-loading.mjs
@@ -20,12 +20,26 @@ 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.
+// A month far down, not built: its tiles painted as boxes on one block as tall as its rows
+// (14 photos over the grid's columns), never an empty space — and one element, not one a box.
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) };
+ const across = Number(getComputedStyle(document.querySelector(".px-scroll")).getPropertyValue("--across")) || 7;
+ const first = later[0];
+ const cs = first && getComputedStyle(first);
+ const cell = first ? (first.clientWidth - (across - 1) * 2) / across : 0;
+ const rows = Math.ceil(14 / across);
+ return {
+ months: later.length,
+ painted: later.every((l) => getComputedStyle(l.firstElementChild).backgroundImage.includes("gradient")),
+ children: later.reduce((n, l) => n + l.querySelectorAll("*").length, 0) / later.length,
+ height: first?.getBoundingClientRect().height ?? 0,
+ want: rows * cell + (rows - 1) * 2,
+ repeat: first && getComputedStyle(first.firstElementChild).backgroundRepeat,
+ };
});
-ok(far.months > 0 && far.boxes === far.months * 14, `months not yet built show their tiles as boxes (${far.months} months, ${far.boxes} boxes)`);
+ok(far.months > 0 && far.painted && far.children === 1 && Math.abs(far.height - far.want) < 1,
+ `months not yet built show their tiles as boxes, one block each ${JSON.stringify(far)}`);
// A slow view: title at once, boxes, then the photos.
await page.evaluate(() => { window.__slowView = "favorites"; });
diff --git a/.uiverify/photos-video.mjs b/.uiverify/photos-video.mjs
index 1e3bc36..2e5ead7 100644
--- a/.uiverify/photos-video.mjs
+++ b/.uiverify/photos-video.mjs
@@ -8,9 +8,11 @@ import { SERVICES, installStub, openScreen } from "./stub.mjs";
const clip = new URL("./clip.webm", import.meta.url);
const len = fs.statSync(clip).size;
const asked = [];
+// Apple keeps no streaming copy of some videos: then the original plays.
+let noCopy = false;
const server = http.createServer((req, res) => {
asked.push(req.url);
- if (!req.url.startsWith("/s3cret/p3/")) return void res.writeHead(404).end();
+ if (!req.url.startsWith("/s3cret/p3/") || (noCopy && req.url.startsWith("/s3cret/p3/video"))) return void res.writeHead(404).end();
const m = /bytes=(\d*)-(\d*)/.exec(req.headers.range ?? "");
const first = m && m[1] ? +m[1] : 0;
const last = m && m[2] ? Math.min(+m[2], len - 1) : len - 1;
@@ -35,7 +37,7 @@ const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failu
await page.locator('.px-tile[data-id="p3"]').dblclick();
await page.waitForTimeout(600);
const video = page.locator(".px-stage video");
-ok((await video.count()) === 1 && (await video.getAttribute("src")) === `${base}/p3/original`, `the video is in the viewer, from the loopback server ${await video.getAttribute("src").catch(() => "")}`);
+ok((await video.count()) === 1 && (await video.getAttribute("src")) === `${base}/p3/video`, `the video is in the viewer, Apple's streaming copy from the loopback server ${await video.getAttribute("src").catch(() => "")}`);
ok(await video.evaluate((v) => !v.controls && v.autoplay), "playing at once, with no engine controls over it");
ok((await page.locator(".px-player-bar").count()) === 1 && (await page.getByRole("slider", { name: "Playback position" }).count()) === 1,
"Photos' own controls in a capsule: play, where it is, a scrubber, what is left, sound");
@@ -69,8 +71,20 @@ if (played.err) {
const was = await video.evaluate((v) => v.muted);
await page.getByRole("button", { name: was ? "Unmute" : "Mute" }).click();
ok((await video.evaluate((v) => v.muted)) === !was, "and the sound button turns sound off and on");
- ok(asked.some((u) => u.startsWith("/s3cret/p3/original")), "fetched from the app's server");
+ ok(asked.some((u) => u.startsWith("/s3cret/p3/video")), "fetched from the app's server");
}
+// No streaming copy: the original plays in its place.
+noCopy = true;
+const pc = await ctx.newPage();
+await pc.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await openScreen(pc, "Photos");
+await pc.waitForTimeout(400);
+await pc.locator('.px-tile[data-id="p3"]').dblclick();
+await pc.waitForTimeout(1500);
+ok((await pc.locator(".px-stage video").getAttribute("src").catch(() => "")) === `${base}/p3/original` || (await pc.locator(".px-stage button.px-video").count()) === 1,
+ `with no streaming copy, the original plays ${await pc.locator(".px-stage video").getAttribute("src").catch(() => "")}`);
+await pc.close();
+noCopy = false;
// Stepping to a photo leaves no video behind.
await page.keyboard.press("ArrowLeft");
await page.waitForTimeout(300);
diff --git a/.uiverify/reminders-repeat-tick.mjs b/.uiverify/reminders-repeat-tick.mjs
index 3bc9b80..0c4c50c 100644
--- a/.uiverify/reminders-repeat-tick.mjs
+++ b/.uiverify/reminders-repeat-tick.mjs
@@ -31,5 +31,23 @@ ok((await row.count()) === 1, "and the row stays — a repeating one never leave
await page.waitForTimeout(1500);
ok((await row.locator(".rx-tick").getAttribute("aria-checked")) === "false", "once Apple has it, it is open again");
ok((await due()) !== before, `with its next date (${(await due()).replace(/\n/g, " ")})`);
+
+// Clicked twice in a row (a double-click, or a second click because nothing seemed to happen):
+// one tick, never two — a daily reminder must not skip a day. And when Apple answers at once,
+// the circle still stays filled a moment before it rolls on.
+await page.evaluate(() => { window.__doneDelay = 0; window.__done = []; });
+const sent = () => page.evaluate(() => (window.__done ?? []).filter((d) => d.guid === "rr" && d.done).length);
+await row.locator(".rx-tick").dblclick();
+await page.waitForTimeout(300);
+ok((await sent()) === 1, `a double-click ticks it once (${await sent()} sent)`);
+ok((await row.locator(".rx-tick").getAttribute("aria-checked")) === "true", "and it stays ticked a moment, even with Apple's answer back");
+await row.locator(".rx-tick").click();
+await page.waitForTimeout(200);
+ok((await sent()) === 1, "a second click while it settles is not a second tick");
+await page.waitForTimeout(2600);
+ok((await row.locator(".rx-tick").getAttribute("aria-checked")) === "false", "then it rolls on, open for its next day");
+await row.locator(".rx-tick").click();
+await page.waitForTimeout(200);
+ok((await sent()) === 2, "and a deliberate tick after that counts again");
await b.close();
process.exitCode = failures ? 1 : (process.exitCode ?? 0);
diff --git a/.uiverify/search-everything.mjs b/.uiverify/search-everything.mjs
new file mode 100644
index 0000000..bc8e4ad
--- /dev/null
+++ b/.uiverify/search-everything.mjs
@@ -0,0 +1,42 @@
+// One search across everything, at the head of the sidebar: typing finds notes, contacts and
+// files at once, grouped by app; the keys move through what was found and Return opens it in
+// its own app, on that very thing; Escape puts it away; nothing found says so.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub } from "./stub.mjs";
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+for (const scheme of ["light", "dark"]) {
+ const ctx = await b.newContext({ viewport: { width: 1280, height: 800 }, colorScheme: scheme });
+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null,
+ notesFixture: true, contactsFixture: true, driveFixture: true });
+ 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" });
+ const field = page.getByRole("combobox", { name: "Search everything" });
+ ok(await field.isVisible(), `${scheme}: a search field heads the sidebar`);
+ await field.fill("zoya");
+ await page.waitForTimeout(300);
+ const panel = page.getByRole("listbox", { name: "Found" });
+ ok(await panel.isVisible(), `${scheme}: what it finds shows at once`);
+ ok((await panel.getByRole("region", { name: "Contacts" }).count()) === 1, `${scheme}: grouped by app`);
+ await page.screenshot({ path: `${process.env.TMPDIR ?? "/tmp"}/search-${scheme}-${process.env.ENGINE}.png` });
+ await page.keyboard.press("Enter");
+ await page.waitForTimeout(500);
+ ok(!(await panel.isVisible()), `${scheme}: Return opens it, and the results go`);
+ ok(/Zoya/.test(await page.locator(".contact-detail, .contacts-detail, .contact-card").first().innerText().catch(() => "")) ||
+ (await page.locator('.nav-item[aria-current="true"]').innerText()).includes("Contacts"), `${scheme}: in Contacts, on that person`);
+ await field.fill("downloads");
+ await page.waitForTimeout(300);
+ ok((await panel.getByRole("region", { name: "iCloud Drive" }).count()) === 1, `${scheme}: files found by name`);
+ await page.keyboard.press("Escape");
+ ok(!(await panel.isVisible()), `${scheme}: Escape puts the results away`);
+ await page.keyboard.press("Escape");
+ ok((await field.inputValue()) === "", `${scheme}: and a second clears the field`);
+ await field.fill("qqqzzz");
+ await page.waitForTimeout(300);
+ ok(/Nothing in your iCloud holds/.test(await panel.innerText()), `${scheme}: nothing found says so`);
+ await ctx.close();
+}
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index 64a9ef3..163874a 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -631,6 +631,16 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
case "auth_send_sms": return null;
case "auth_submit_sms_code": return null;
case "auth_sign_out": sessionStorage.setItem("__signedOut", JSON.stringify(args)); return null;
+ case "search_everything": {
+ // A search across every app: what the fixtures hold that matches every word.
+ const q = String(args.query).toLowerCase().split(/\s+/).filter(Boolean);
+ const has = (t) => q.every((w) => String(t ?? "").toLowerCase().includes(w));
+ const notes = noteList.filter((n) => has(`${n.title} ${n.body ?? ""}`));
+ const contacts = contactList.filter((c) => has(`${c.firstName ?? ""} ${c.lastName ?? ""} ${c.company ?? ""}`));
+ const files = (driveFixture ? driveItems : []).filter((f) => has(`${f.name}.${f.extension ?? ""}`));
+ return { notes: notes.slice(0, 5), reminders: [], events: [], contacts: contacts.slice(0, 5), files: files.slice(0, 5), photos: [],
+ counts: [notes.length, 0, 0, contacts.length, files.length, 0] };
+ }
case "drive_kept": return window.__driveFolder?.on ? [...(window.__kept ??= [])] : null;
case "drive_keep":
if (!window.__driveFolder?.on) throw "Turn on the iCloud Drive folder in Settings to keep files on this computer.";
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000..b4e06ee
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,57 @@
+# Security
+
+Quince asks for your Apple Account password. That is a lot of trust to ask of an app made by
+one person, so this page says exactly what it does with it: what it talks to, what it keeps,
+and where. Every line here is true of the code in this repository; if one ever stops being
+true, that is a bug, and a serious one.
+
+## What Quince talks to
+
+Apple, and nothing else:
+
+- `idmsa.apple.com` — signing in (Apple's own SRP sign-in and two-factor codes).
+- `setup.icloud.com`, `www.icloud.com` — opening the session and finding your services.
+- `*.icloud.com` service addresses Apple gives the session (CloudKit, Contacts, Calendar,
+ iCloud Drive, Photos), `gateway.icloud.com` and `cvws.icloud-content.com` (downloads).
+- `calendars.icloud.com` — Apple's public holiday calendars.
+- The `.com.cn` equivalents of the above, for accounts in mainland China.
+
+There are no Quince servers. There is no telemetry, analytics, crash reporting or update
+check. Nothing is sent anywhere but Apple, and only what is needed to show and change your
+own data. The window itself cannot reach the network at all: its content security policy
+(`src-tauri/tauri.conf.json`) lets it talk only to the app's own Rust side, which does all
+talking to Apple.
+
+Links you click in a note or an event open in your own browser, mail or map app; a photo's
+place opens in this computer's own map app (a `geo:` link), never a website.
+
+## What Quince keeps, and where
+
+Everything is in your user's data folder (`~/.local/share/dev.quince.client` on Linux),
+which is readable by you alone (mode 700):
+
+- **Your password, Apple Account and session tokens:** in the system keyring (GNOME
+ Keyring, KWallet — the Secret Service), never in a file. The password is kept so a session
+ that lapses can sign itself back in without asking; Apple asks for a code only when it
+ stops trusting this computer.
+- **Session cookies:** `cookies.json`, readable by you alone (mode 600).
+- **Your library:** `library.db` (SQLite) — notes, reminders, events, contacts, the Drive
+ and Photos listings — and caches of pictures and files you opened. These are not encrypted
+ by Quince; use full-disk encryption, as you would for the same data on a Mac.
+
+Signing out asks whether to keep a copy on this computer. Removing it deletes the library,
+its caches and Quince's file-manager thumbnails. Another Apple Account signing in never sees
+the last one's data: each account's library is set aside whole and brought back only for
+that account.
+
+## Advanced Data Protection
+
+With Advanced Data Protection on and "Access iCloud Data on the Web" off, Apple does not
+let any app outside your devices read your iCloud data, Quince included. Quince says so
+plainly and shows the switch; it does not work around it.
+
+## Reporting a vulnerability
+
+Please use GitHub's private vulnerability reporting on this repository (Security →
+Report a vulnerability). Do not open a public issue for a security problem. You will get an
+answer, and credit if you want it.
diff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rs
index 2d0e29a..e3c8d6b 100644
--- a/crates/quince-auth/src/lib.rs
+++ b/crates/quince-auth/src/lib.rs
@@ -349,7 +349,23 @@ impl Client {
fn persist(&self) -> Result<()> {
self.store.save(&self.session)?;
- let mut w = std::io::BufWriter::new(std::fs::File::create(self.store.cookie_path())?);
+ // The session's cookies are a credential: readable by this user alone, whatever folder
+ // they end up in (a backup, a copy), not only by the private data folder around them.
+ let mut options = std::fs::OpenOptions::new();
+ options.write(true).create(true).truncate(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.mode(0o600);
+ }
+ let file = options.open(self.store.cookie_path())?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ // A file made before this kept its old mode: set it, too.
+ file.set_permissions(std::fs::Permissions::from_mode(0o600))?;
+ }
+ let mut w = std::io::BufWriter::new(file);
let jar = self.jar.lock().expect("cookie jar mutex poisoned");
cookie_store::serde::json::save(&jar, &mut w)
.map_err(|e| Error::Protocol(format!("couldn't save cookies: {e}")))
diff --git a/crates/quince-core/src/drive.rs b/crates/quince-core/src/drive.rs
index 0fc8cf9..fb40e3d 100644
--- a/crates/quince-core/src/drive.rs
+++ b/crates/quince-core/src/drive.rs
@@ -128,6 +128,47 @@ impl Library {
///
/// Named the way Finder orders them: numbers as numbers and accents ignored, so "Scan 10"
/// follows "Scan 9" and "Été" sits among the E's. SQL's `lower` can do neither.
+ /// Files and folders whose name holds every word of `query`, across every folder this
+ /// computer has listed: case and accents aside, as Finder finds them. At most `limit`.
+ pub fn search_drive(&self, query: &str, limit: usize) -> Result<Vec<DriveItem>> {
+ let words = crate::fold::words(query);
+ if words.is_empty() {
+ return Ok(Vec::new());
+ }
+ let mut stmt = self.conn.prepare(
+ "SELECT drivewsid, parent_id, name, extension, kind, size, child_count,
+ created_at, modified_at, etag
+ FROM drive_items
+ ORDER BY modified_at IS NULL, modified_at DESC",
+ )?;
+ let rows = stmt.query_map([], |row| {
+ Ok(DriveItem {
+ drivewsid: row.get(0)?,
+ parent_id: row.get(1)?,
+ name: row.get(2)?,
+ extension: row.get(3)?,
+ kind: row.get(4)?,
+ size: row.get(5)?,
+ child_count: row.get(6)?,
+ created_at: row.get(7)?,
+ modified_at: row.get(8)?,
+ etag: row.get(9)?,
+ })
+ })?;
+ let mut found = Vec::new();
+ for row in rows {
+ let item = row?;
+ let name = format!("{}.{}", item.name, item.extension.as_deref().unwrap_or(""));
+ if crate::fold::holds_all(&crate::fold::fold(&name), &words) {
+ found.push(item);
+ if found.len() >= limit {
+ break;
+ }
+ }
+ }
+ Ok(found)
+ }
+
pub fn drive_children(&self, parent_id: &str) -> Result<Vec<DriveItem>> {
let mut stmt = self.conn.prepare(
"SELECT drivewsid, parent_id, name, extension, kind, size, child_count,
diff --git a/crates/quince-core/src/lib.rs b/crates/quince-core/src/lib.rs
index 07ec9d9..153dec1 100644
--- a/crates/quince-core/src/lib.rs
+++ b/crates/quince-core/src/lib.rs
@@ -15,6 +15,7 @@ pub mod outbox;
pub mod photos;
pub mod reminders;
pub mod schema;
+pub mod search;
use rusqlite::Connection;
use std::path::Path;
diff --git a/crates/quince-core/src/search.rs b/crates/quince-core/src/search.rs
new file mode 100644
index 0000000..3b9d2e2
--- /dev/null
+++ b/crates/quince-core/src/search.rs
@@ -0,0 +1,126 @@
+//! One search across everything the library holds — notes, reminders, events, contacts,
+//! files and photos — offline and at once, as neither icloud.com nor a Mac offers: each app
+//! searches only itself there. Each kind is searched as its own screen searches it (case and
+//! accents aside, every word), and only its best few are kept: the window shows a handful of
+//! each and opens the app for the rest.
+
+use crate::{
+ calendar::Event, contacts::Contact, drive::DriveItem, notes::Note, photos::Photo,
+ reminders::Reminder, Library, Result,
+};
+use serde::Serialize;
+
+/// What one search found, the first few of each kind, and how many of each there were.
+#[derive(Debug, Default, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Everything {
+ pub notes: Vec<Note>,
+ pub reminders: Vec<Reminder>,
+ pub events: Vec<Event>,
+ pub contacts: Vec<Contact>,
+ pub files: Vec<DriveItem>,
+ pub photos: Vec<Photo>,
+ /// How many each kind found in all (up to what was looked through), in the order above.
+ pub counts: [usize; 6],
+}
+
+impl Library {
+ /// Everything that holds every word of `query`, at most `each` of a kind.
+ pub fn search_everything(&self, query: &str, each: usize) -> Result<Everything> {
+ if crate::fold::words(query).is_empty() {
+ return Ok(Everything::default());
+ }
+ let mut notes = self.search_notes(query)?;
+ let mut reminders = self.search_reminders(query)?;
+ let mut events = self.search_events(query)?;
+ let mut contacts = self.contacts(Some(query))?;
+ let mut files = self.search_drive(query, each.saturating_mul(20))?;
+ let mut photos = self.search_photos(query, each.saturating_mul(20))?;
+ let counts = [
+ notes.len(),
+ reminders.len(),
+ events.len(),
+ contacts.len(),
+ files.len(),
+ photos.len(),
+ ];
+ notes.truncate(each);
+ reminders.truncate(each);
+ events.truncate(each);
+ contacts.truncate(each);
+ files.truncate(each);
+ photos.truncate(each);
+ Ok(Everything {
+ notes,
+ reminders,
+ events,
+ contacts,
+ files,
+ photos,
+ counts,
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// One word finds it wherever it is — a file and a contact here — case and accents aside;
+ /// a word nothing holds finds nothing; each kind is kept to its few.
+ #[test]
+ fn one_search_finds_it_in_every_app() {
+ let mut lib = Library::in_memory().unwrap();
+ let file = |id: &str, name: &str| crate::drive::DriveItem {
+ drivewsid: id.into(),
+ parent_id: Some("root".into()),
+ name: name.into(),
+ extension: Some("pdf".into()),
+ kind: "FILE".into(),
+ size: Some(1),
+ child_count: None,
+ created_at: None,
+ modified_at: Some(1),
+ etag: None,
+ };
+ lib.put_drive_children(
+ "root",
+ &[
+ file("F1", "Résumé Springfield"),
+ file("F2", "Springfield map"),
+ file("F3", "Budget"),
+ ],
+ )
+ .unwrap();
+ lib.put_contacts(&[crate::contacts::Contact {
+ guid: "C1".into(),
+ first_name: Some("Asha".into()),
+ middle_name: None,
+ last_name: Some("Springfield".into()),
+ company: None,
+ is_company: false,
+ birthday: None,
+ notes: None,
+ photo_url: None,
+ photo_signature: None,
+ photo_crop: None,
+ etag: None,
+ methods: vec![],
+ }])
+ .unwrap();
+ let found = lib.search_everything("SPRINGFIELD", 1).unwrap();
+ assert_eq!(found.counts[4], 2, "both files found");
+ assert_eq!(found.files.len(), 1, "and only the first kept");
+ assert_eq!(found.contacts.len(), 1);
+ assert_eq!(
+ lib.search_everything("resume springfield", 5)
+ .unwrap()
+ .files
+ .len(),
+ 1,
+ "accents aside, every word"
+ );
+ assert_eq!(lib.search_everything("zebra", 5).unwrap().counts, [0; 6]);
+ assert_eq!(lib.search_everything(" ", 5).unwrap().counts, [0; 6]);
+ }
+}
diff --git a/crates/quince-icloud/src/notes.rs b/crates/quince-icloud/src/notes.rs
index 26d0b40..bfd457f 100644
--- a/crates/quince-icloud/src/notes.rs
+++ b/crates/quince-icloud/src/notes.rs
@@ -2485,7 +2485,8 @@ pub async fn add_table_line_cloudkit(
crate::table::with_row_in_base64(current, at)?
};
Some(serde_json::json!({
- "MergeableDataEncrypted": { "type": "ENCRYPTED_BYTES", "value": edited }
+ "MergeableDataEncrypted": { "type": "ENCRYPTED_BYTES", "value": edited },
+ "LastModificationDate": { "type": "TIMESTAMP", "value": now_millis() }
}))
})
.await?
@@ -2495,6 +2496,7 @@ pub async fn add_table_line_cloudkit(
if column { "column" } else { "row" }
))
})?;
+ touch_note_of(&client, attachment).await;
client
.lookup_record(ZONE, attachment)
.await?
@@ -2523,7 +2525,8 @@ pub async fn remove_table_line_cloudkit(
.as_str()?;
let edited = crate::table::without_line_in_base64(current, column, at)?;
Some(serde_json::json!({
- "MergeableDataEncrypted": { "type": "ENCRYPTED_BYTES", "value": edited }
+ "MergeableDataEncrypted": { "type": "ENCRYPTED_BYTES", "value": edited },
+ "LastModificationDate": { "type": "TIMESTAMP", "value": now_millis() }
}))
})
.await?
@@ -2533,6 +2536,7 @@ pub async fn remove_table_line_cloudkit(
if column { "column" } else { "row" }
))
})?;
+ touch_note_of(&client, attachment).await;
client
.lookup_record(ZONE, attachment)
.await?
@@ -2543,6 +2547,28 @@ pub async fn remove_table_line_cloudkit(
.ok_or_else(|| Error::Protocol("Apple kept a table this cannot read back".into()))
}
+/// The note a table lives in, marked changed now, as a phone marks it when one of its tables
+/// is edited (`ModificationDate`): a table edited here was stored at Apple but did not show on
+/// the phone, whose note had no change to read. Best effort: the edit itself is already kept.
+async fn touch_note_of(client: &ZoneClient<'_>, attachment: &str) {
+ let Ok(Some(record)) = client.lookup_record(ZONE, attachment).await else {
+ return;
+ };
+ let Some(note) = record
+ .pointer("/fields/Note/value/recordName")
+ .and_then(Value::as_str)
+ else {
+ return;
+ };
+ let _ = client
+ .edit_record(ZONE, note, "Note", |_| {
+ Some(serde_json::json!({
+ "ModificationDate": { "type": "TIMESTAMP", "value": now_millis() }
+ }))
+ })
+ .await;
+}
+
/// A table cell set to `text`.
pub async fn set_table_cell_cloudkit(
http: &reqwest::Client,
@@ -2561,7 +2587,8 @@ pub async fn set_table_cell_cloudkit(
.as_str()?;
let edited = crate::table::with_cell_in_base64(current, row, column, text)?;
Some(serde_json::json!({
- "MergeableDataEncrypted": { "type": "ENCRYPTED_BYTES", "value": edited }
+ "MergeableDataEncrypted": { "type": "ENCRYPTED_BYTES", "value": edited },
+ "LastModificationDate": { "type": "TIMESTAMP", "value": now_millis() }
}))
})
.await?
@@ -2570,6 +2597,7 @@ pub async fn set_table_cell_cloudkit(
})?;
// Apple's answer to the write does not carry the table back (measured), so what it now
// holds is read from it.
+ touch_note_of(&client, attachment).await;
client
.lookup_record(ZONE, attachment)
.await?
diff --git a/crates/quince-media/Cargo.toml b/crates/quince-media/Cargo.toml
index 224e816..ccc5fa4 100644
--- a/crates/quince-media/Cargo.toml
+++ b/crates/quince-media/Cargo.toml
@@ -9,5 +9,10 @@ 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"
png = "0.17"
+
+# HEIC decoded with libheif where the system has it (Linux packages it everywhere). On Windows
+# it is not built yet: HEIC is shown at Apple's own JPEG sizes there until the system's own
+# decoder (the Windows Imaging Component) is used.
+[target.'cfg(not(windows))'.dependencies]
+libheif-rs = "3.0.0"
diff --git a/crates/quince-media/src/lib.rs b/crates/quince-media/src/lib.rs
index 54b0c7d..6a16ca0 100644
--- a/crates/quince-media/src/lib.rs
+++ b/crates/quince-media/src/lib.rs
@@ -99,6 +99,16 @@ fn cut(image: image::DynamicImage, crop: Option<Crop>) -> image::DynamicImage {
///
/// # Errors
/// When the bytes are not a HEIF image libheif can decode.
+#[cfg(windows)]
+pub fn heic_to_jpeg(_bytes: &[u8]) -> Result<Vec<u8>, String> {
+ Err("HEIC pictures are not decoded on Windows yet.".into())
+}
+
+/// A HEIC picture made a JPEG (see the Windows variant above for where it is not).
+///
+/// # Errors
+/// When the bytes are not a HEIF image libheif can decode.
+#[cfg(not(windows))]
pub fn heic_to_jpeg(bytes: &[u8]) -> Result<Vec<u8>, String> {
use libheif_rs::{ColorSpace, HeifContext, LibHeif, RgbChroma};
let lib = LibHeif::new();
@@ -284,7 +294,6 @@ pub const UPRIGHT_MATRIX: [u8; 36] = [
/// the MD5 of this string, so one character escaped differently and no file manager finds it.
#[must_use]
pub fn file_uri(path: &std::path::Path) -> String {
- use std::os::unix::ffi::OsStrExt;
// GLib's table, ASCII 32 to 127; a character is kept when its byte has 0x08 set.
const ACCEPTABLE: [u8; 96] = [
0x00, 0x3F, 0x20, 0x20, 0x28, 0x00, 0x2C, 0x3F, 0x3F, 0x3F, 0x3F, 0x2A, 0x28, 0x3F, 0x3F,
@@ -301,7 +310,8 @@ pub fn file_uri(path: &std::path::Path) -> String {
0x20,
];
let mut out = String::from("file://");
- for &b in path.as_os_str().as_bytes() {
+ // On Linux these are the path's own bytes, as GLib reads them.
+ for &b in path.as_os_str().as_encoded_bytes() {
let kept = (32..128).contains(&b) && ACCEPTABLE[usize::from(b - 32)] & 0x08 != 0;
if kept {
out.push(char::from(b));
diff --git a/crates/quince-vfs/src/lib.rs b/crates/quince-vfs/src/lib.rs
index a28235f..469b36d 100644
--- a/crates/quince-vfs/src/lib.rs
+++ b/crates/quince-vfs/src/lib.rs
@@ -377,13 +377,12 @@ impl Cache {
/// Bytes on disk now: what the sparse files really take, not their full sizes.
#[must_use]
pub fn used(&self) -> u64 {
- use std::os::unix::fs::MetadataExt;
std::fs::read_dir(&self.dir)
.map(|d| {
d.flatten()
.filter(|e| !e.file_name().to_string_lossy().starts_with('.'))
.filter_map(|e| e.metadata().ok())
- .map(|m| m.blocks() * 512)
+ .map(|m| on_disk(&m))
.sum()
})
.unwrap_or(0)
@@ -392,7 +391,6 @@ impl Cache {
/// Down to four fifths of the budget, the files read longest ago first; never one read in
/// the last few minutes. Answers how many bytes were let go of.
pub fn evict(&self) -> u64 {
- use std::os::unix::fs::MetadataExt;
let mut used = self.used();
if used <= self.budget {
return 0;
@@ -426,8 +424,8 @@ impl Cache {
.filter_map(|e| {
let m = e.metadata().ok()?;
let have = std::fs::metadata(e.path().with_extension("have"))
- .map_or(0, |h| h.blocks() * 512);
- Some((m.modified().ok()?, e.path(), m.blocks() * 512 + have))
+ .map_or(0, |h| on_disk(&h));
+ Some((m.modified().ok()?, e.path(), on_disk(&m) + have))
})
.collect()
})
@@ -595,9 +593,44 @@ impl Cache {
}
}
+/// What a file really takes on disk: a sparse file only its blocks written. (Windows says only
+/// its length.)
+#[cfg(unix)]
+fn on_disk(m: &std::fs::Metadata) -> u64 {
+ use std::os::unix::fs::MetadataExt;
+ m.blocks() * 512
+}
+#[cfg(not(unix))]
+fn on_disk(m: &std::fs::Metadata) -> u64 {
+ m.len()
+}
+
+#[cfg(unix)]
+fn write_at(file: &std::fs::File, bytes: &[u8], at: u64) -> std::io::Result<()> {
+ use std::os::unix::fs::FileExt;
+ file.write_all_at(bytes, at)
+}
+#[cfg(not(unix))]
+fn write_at(mut file: &std::fs::File, bytes: &[u8], at: u64) -> std::io::Result<()> {
+ use std::io::{Seek, Write};
+ file.seek(std::io::SeekFrom::Start(at))?;
+ file.write_all(bytes)
+}
+
+#[cfg(unix)]
+fn read_at(file: &std::fs::File, out: &mut [u8], at: u64) -> std::io::Result<()> {
+ use std::os::unix::fs::FileExt;
+ file.read_exact_at(out, at)
+}
+#[cfg(not(unix))]
+fn read_at(mut file: &std::fs::File, out: &mut [u8], at: u64) -> std::io::Result<()> {
+ use std::io::{Read, Seek};
+ file.seek(std::io::SeekFrom::Start(at))?;
+ file.read_exact(out)
+}
+
/// Bytes written at `at` in the sparse file, made its full size first.
fn put(path: &Path, at: u64, bytes: &[u8], size: u64) -> std::io::Result<()> {
- use std::os::unix::fs::FileExt;
let file = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
@@ -606,15 +639,14 @@ fn put(path: &Path, at: u64, bytes: &[u8], size: u64) -> std::io::Result<()> {
if file.metadata()?.len() != size {
file.set_len(size)?;
}
- file.write_all_at(bytes, at)?;
+ write_at(&file, bytes, at)?;
file.sync_data()
}
fn get(path: &Path, at: u64, len: u64) -> std::io::Result<Vec<u8>> {
- use std::os::unix::fs::FileExt;
let file = std::fs::File::open(path)?;
let mut out = vec![0u8; usize::try_from(len).unwrap_or(0)];
- file.read_exact_at(&mut out, at)?;
+ read_at(&file, &mut out, at)?;
Ok(out)
}
@@ -658,7 +690,6 @@ pub fn write_thumbnails(
pictures: &HashMap<String, Vec<u8>>,
) {
use md5::Digest;
- use std::os::unix::fs::PermissionsExt;
for (path, item) in files {
let Some(picture) = pictures.get(&item.drivewsid) else {
continue;
@@ -682,7 +713,11 @@ pub fn write_thumbnails(
// As the specification asks: private to its owner, and never seen half-written.
let part = at.with_extension("png.part");
if std::fs::write(&part, &png).is_ok() {
- let _ = std::fs::set_permissions(&part, std::fs::Permissions::from_mode(0o600));
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = std::fs::set_permissions(&part, std::fs::Permissions::from_mode(0o600));
+ }
let _ = std::fs::rename(&part, &at);
}
}
diff --git a/crates/quince-vfs/src/writes.rs b/crates/quince-vfs/src/writes.rs
index f4cb368..959fb77 100644
--- a/crates/quince-vfs/src/writes.rs
+++ b/crates/quince-vfs/src/writes.rs
@@ -120,6 +120,7 @@ pub struct Writes {
pub(crate) items: Mutex<HashMap<u64, Pending>>,
/// What this computer last sent under each name ("folder/name"): the next save of that
/// name replaces it as its own, never mistaking it for a change made elsewhere.
+ #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub(crate) sent: Mutex<HashMap<String, DriveItem>>,
/// One send at a time per name ("folder/name"): a replace is three steps at Apple (send,
/// old into Recently Deleted, rename), and a second save of the same name arriving
diff --git a/probe/examples/notes_table_snapshot.rs b/probe/examples/notes_table_snapshot.rs
new file mode 100644
index 0000000..c83e5cf
--- /dev/null
+++ b/probe/examples/notes_table_snapshot.rs
@@ -0,0 +1,66 @@
+//! Read-only: one note's record and its attachments' records, every field — plain values as
+//! they are, encrypted ones as their length and a short hash — written as JSON, so two
+//! snapshots (before and after an edit on the phone) show exactly which fields the phone
+//! changes when it edits a table. Picks the note by the start of its text.
+use anyhow::{anyhow, Result};
+use serde_json::{json, Map, Value};
+use sha2::Digest;
+
+fn shape(fields: &Value) -> Value {
+ let mut out = Map::new();
+ for (k, v) in fields.as_object().into_iter().flatten() {
+ let val = &v["value"];
+ let t = v["type"].as_str().unwrap_or("");
+ let shown = if t == "ENCRYPTED_BYTES"
+ || t == "BYTES"
+ || val.is_string() && val.as_str().is_some_and(|s| s.len() > 80)
+ {
+ let s = val.as_str().unwrap_or("");
+ json!({ "len": s.len(), "sha": format!("{:x}", sha2::Sha256::digest(s.as_bytes()))[..12].to_string() })
+ } else {
+ val.clone()
+ };
+ out.insert(k.clone(), shown);
+ }
+ Value::Object(out)
+}
+
+#[tokio::main]
+async fn main() -> Result<()> {
+ let want = std::env::args()
+ .nth(1)
+ .ok_or_else(|| anyhow!("start of the note's text"))?;
+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");
+ let mut client = quince_auth::Client::new(&dir)?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let root = client
+ .session()
+ .service_url("ckdatabasews")
+ .ok_or_else(|| anyhow!("no ck"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ let zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p);
+ let walk = zc.all_records("Notes", None).await?;
+ let note = walk
+ .records
+ .iter()
+ .filter(|r| r["recordType"] == "Note")
+ .find(|r| {
+ r["fields"]["TextDataEncrypted"]["value"]
+ .as_str()
+ .and_then(quince_icloud::ckdocument::text_from_base64)
+ .is_some_and(|t| t.starts_with(&want))
+ })
+ .ok_or_else(|| anyhow!("no such note"))?;
+ let id = note["recordName"].as_str().unwrap_or_default();
+ let attachments: Vec<Value> = walk
+ .records
+ .iter()
+ .filter(|r| r["recordType"] == "Attachment" && r["fields"]["Note"]["value"]["recordName"] == id)
+ .map(|a| json!({ "id": a["recordName"], "tag": a["recordChangeTag"], "fields": shape(&a["fields"]) }))
+ .collect();
+ let snap = json!({ "note": { "id": id, "tag": note["recordChangeTag"], "fields": shape(&note["fields"]) }, "attachments": attachments });
+ println!("{}", serde_json::to_string_pretty(&snap)?);
+ Ok(())
+}
diff --git a/probe/examples/search_speed.rs b/probe/examples/search_speed.rs
new file mode 100644
index 0000000..989f64c
--- /dev/null
+++ b/probe/examples/search_speed.rs
@@ -0,0 +1,19 @@
+//! Local: how long one search across everything takes on a copy of a real library.
+fn main() -> anyhow::Result<()> {
+ let dir = std::path::PathBuf::from(
+ std::env::args()
+ .nth(1)
+ .ok_or_else(|| anyhow::anyhow!("library folder"))?,
+ );
+ let lib = quince_core::Library::open(&dir)?;
+ for q in ["the", "a", "photo", "zzzz", "plan"] {
+ let t = std::time::Instant::now();
+ let found = lib.search_everything(q, 5)?;
+ println!(
+ "{q:>6}: {:>5.1} ms counts {:?}",
+ t.elapsed().as_secs_f64() * 1000.0,
+ found.counts
+ );
+ }
+ Ok(())
+}
diff --git a/probe/examples/video_renditions.rs b/probe/examples/video_renditions.rs
new file mode 100644
index 0000000..1296128
--- /dev/null
+++ b/probe/examples/video_renditions.rs
@@ -0,0 +1,72 @@
+//! Read-only: for a few videos, what Apple keeps — the original and its streaming copies — with
+//! their sizes, codecs and whether each is upright (its matrix), and how long the streaming copy
+//! takes to fetch. Prints sizes and kinds only.
+use anyhow::{anyhow, Result};
+#[tokio::main]
+async fn main() -> Result<()> {
+ let ids: Vec<String> = std::env::args().skip(1).collect();
+ 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 ck = client
+ .session()
+ .service_url("ckdatabasews")
+ .ok_or_else(|| anyhow!("no ck"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ let zc = quince_icloud::cloudkit::ZoneClient::new(&http, &ck, "com.apple.photos.cloud", p);
+ let tmp = std::env::temp_dir().join(format!("vr-{}", std::process::id()));
+ std::fs::create_dir_all(&tmp)?;
+ for (n, id) in ids.iter().enumerate() {
+ let a = zc
+ .lookup_record("PrimarySync", id)
+ .await?
+ .ok_or_else(|| anyhow!("gone"))?;
+ let master = a["fields"]["masterRef"]["value"]["recordName"]
+ .as_str()
+ .unwrap_or_default()
+ .to_string();
+ let m = zc
+ .lookup_record("PrimarySync", &master)
+ .await?
+ .ok_or_else(|| anyhow!("no master"))?;
+ let f = &m["fields"];
+ println!(
+ "video {n}: original {} bytes ({})",
+ f["resOriginalFileSize"]["value"], f["itemType"]["value"]
+ );
+ for key in [
+ "resVidMedRes",
+ "resVidSmallRes",
+ "resVidHDRMedRes",
+ "resVidLargeRes",
+ ] {
+ let Some(url) = f[key]["value"]["downloadURL"].as_str() else {
+ continue;
+ };
+ let t = std::time::Instant::now();
+ let bytes = http
+ .get(url.replace("${f}", "v.mp4"))
+ .send()
+ .await?
+ .bytes()
+ .await?;
+ let took = t.elapsed().as_millis();
+ let path = tmp.join(format!("{n}-{key}"));
+ std::fs::write(&path, &bytes)?;
+ let codec = ["avc1", "hvc1", "hev1"]
+ .into_iter()
+ .find(|c| bytes.windows(4).any(|w| w == c.as_bytes()))
+ .unwrap_or("?");
+ let moov_at = bytes.windows(4).position(|w| w == b"moov");
+ let matrix = quince_media::video_matrix(&path)
+ .ok()
+ .flatten()
+ .map(|(_, m)| m);
+ println!(" {key}: {} bytes in {took} ms, codec {codec}, moov at {moov_at:?} of {}, matrix {matrix:?}", bytes.len(), bytes.len());
+ }
+ }
+ let _ = std::fs::remove_dir_all(&tmp);
+ Ok(())
+}
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index fd514d3..4e604bf 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -10,13 +10,8 @@ tauri-build = { version = "2", features = [] }
[dependencies]
futures-util = { version = "0.3", default-features = false, features = ["std"] }
-# A video's poster when Apple's is blank: one frame read with GStreamer, which WebKitGTK
-# already needs, so nothing new is installed.
-gstreamer = "0.25"
quince-vfs = { path = "../crates/quince-vfs" }
sha2 = "0.10"
-gstreamer-app = "0.25"
-gstreamer-video = "0.25"
tauri = { version = "2", features = ["tray-icon", "image-png"] }
quince-auth = { path = "../crates/quince-auth" }
quince-core = { path = "../crates/quince-core" }
@@ -33,12 +28,17 @@ base64 = "0.22"
tauri-plugin-dialog = "2.7.3"
tauri-plugin-opener = "2"
notify-rust = "4"
-zbus = "5"
tauri-plugin-single-instance = "2"
libc = "0.2"
[target.'cfg(target_os = "linux")'.dependencies]
fuser = { version = "0.18", default-features = false }
+# A video's poster when Apple's is blank: one frame read with GStreamer, which WebKitGTK
+# already needs, so nothing new is installed. Linux only: elsewhere Apple's poster stands.
+gstreamer = "0.25"
+gstreamer-app = "0.25"
+gstreamer-video = "0.25"
+zbus = "5"
[dev-dependencies]
image = { version = "0.25", default-features = false, features = ["jpeg"] }
diff --git a/src-tauri/src/alerts.rs b/src-tauri/src/alerts.rs
index 578066c..5dd06b7 100644
--- a/src-tauri/src/alerts.rs
+++ b/src-tauri/src/alerts.rs
@@ -124,7 +124,11 @@ pub fn spawn(app: AppHandle) {
}
/// Wake when the machine comes back from sleep, where logind says so. Where it cannot be
-/// asked — no system bus, no logind — the ten-minute ceiling still holds.
+/// asked — no system bus, no logind, not Linux — the ten-minute ceiling still holds.
+#[cfg(not(target_os = "linux"))]
+fn watch_for_resume() {}
+
+#[cfg(target_os = "linux")]
fn watch_for_resume() {
tauri::async_runtime::spawn(async {
let Ok(bus) = zbus::Connection::system().await else {
diff --git a/src-tauri/src/login.rs b/src-tauri/src/login.rs
index 6f0a5ba..9b69fd1 100644
--- a/src-tauri/src/login.rs
+++ b/src-tauri/src/login.rs
@@ -6,11 +6,15 @@
//! Some compositors run no autostart entries (Hyprland, Sway and the like, unless started
//! through uwsm). There Settings says so, with the one line that does the same in their
//! own startup — written by the person, never by Quince into their config.
+//!
+//! On Windows it is the standard place too: a value under the user's own `Run` key, which
+//! Windows reads at sign-in (and lists in Task Manager's Startup apps, where it can be turned
+//! off as any other).
use serde::Serialize;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
-use tauri::{AppHandle, Manager};
+use tauri::AppHandle;
/// Started by the login entry: the window stays hidden unless something needs the person.
static BACKGROUND: AtomicBool = AtomicBool::new(false);
@@ -48,7 +52,9 @@ pub struct LoginItem {
pub honoured: bool,
}
+#[cfg(not(windows))]
fn entry(app: &AppHandle) -> Option<PathBuf> {
+ use tauri::Manager;
app.path()
.config_dir()
.ok()
@@ -62,6 +68,10 @@ fn command() -> String {
.map(PathBuf::from)
.or_else(|| std::env::current_exe().ok())
.unwrap_or_else(|| PathBuf::from("quince-app"));
+ // Windows reads the Run value as a command line: the path in plain quotes.
+ if cfg!(windows) {
+ return format!("\"{}\" {FLAG}", program.to_string_lossy());
+ }
format!("{} {FLAG}", quoted(&program.to_string_lossy()))
}
@@ -79,12 +89,14 @@ fn quoted(path: &str) -> String {
out
}
+#[cfg(not(windows))]
fn desktop_file(command: &str) -> String {
format!(
"[Desktop Entry]\nType=Application\nName=Quince\nComment=Keeps iCloud in sync in the background\nExec={command}\nIcon=dev.quince.client\nTerminal=false\nNoDisplay=true\nX-GNOME-Autostart-enabled=true\n"
)
}
+#[cfg(not(windows))]
/// Desktops that run autostart entries themselves.
const RUNS_AUTOSTART: [&str; 10] = [
"GNOME",
@@ -99,6 +111,7 @@ const RUNS_AUTOSTART: [&str; 10] = [
"Unity",
];
+#[cfg(not(windows))]
/// Whether autostart entries run at login here: a desktop that runs them, or a session that
/// started systemd's autostart target (uwsm, and the desktops that use it).
fn honoured() -> bool {
@@ -120,6 +133,64 @@ fn honoured() -> bool {
.is_ok_and(|s| s.success())
}
+/// The user's own `Run` key, and the value Quince keeps there.
+#[cfg(windows)]
+const RUN_KEY: &str = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run";
+#[cfg(windows)]
+const RUN_VALUE: &str = "Quince";
+
+/// Windows' own `reg` tool, with no window flashing up.
+#[cfg(windows)]
+fn reg(args: &[&str]) -> std::io::Result<std::process::ExitStatus> {
+ use std::os::windows::process::CommandExt;
+ const CREATE_NO_WINDOW: u32 = 0x0800_0000;
+ std::process::Command::new("reg")
+ .args(args)
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .creation_flags(CREATE_NO_WINDOW)
+ .status()
+}
+
+#[cfg(windows)]
+#[tauri::command]
+pub async fn login_item_status(_app: AppHandle) -> Result<LoginItem, String> {
+ let on = tauri::async_runtime::spawn_blocking(|| {
+ reg(&["query", RUN_KEY, "/v", RUN_VALUE]).is_ok_and(|s| s.success())
+ })
+ .await
+ .unwrap_or(false);
+ Ok(LoginItem {
+ on,
+ command: command(),
+ honoured: true,
+ })
+}
+
+#[cfg(windows)]
+#[tauri::command]
+pub async fn login_item_set(on: bool, app: AppHandle) -> Result<LoginItem, String> {
+ let line = command();
+ let done = tauri::async_runtime::spawn_blocking(move || {
+ if on {
+ reg(&[
+ "add", RUN_KEY, "/v", RUN_VALUE, "/t", "REG_SZ", "/d", &line, "/f",
+ ])
+ } else {
+ reg(&["delete", RUN_KEY, "/v", RUN_VALUE, "/f"])
+ }
+ })
+ .await
+ .map_err(|e| e.to_string())?
+ .map_err(|e| e.to_string())?;
+ // Turning off what was never on is not a failure.
+ if on && !done.success() {
+ return Err("Windows did not keep the startup entry.".into());
+ }
+ login_item_status(app).await
+}
+
+#[cfg(not(windows))]
#[tauri::command]
pub async fn login_item_status(app: AppHandle) -> Result<LoginItem, String> {
let on = entry(&app).is_some_and(|p| p.exists());
@@ -133,6 +204,7 @@ pub async fn login_item_status(app: AppHandle) -> Result<LoginItem, String> {
})
}
+#[cfg(not(windows))]
#[tauri::command]
pub async fn login_item_set(on: bool, app: AppHandle) -> Result<LoginItem, String> {
let path = entry(&app).ok_or("There is no configuration folder to keep it in.")?;
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 74a83c8..1605dc2 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -19,7 +19,15 @@ mod mount;
mod mount_photos;
mod outbox;
mod photos;
+#[cfg(target_os = "linux")]
mod poster;
+#[cfg(not(target_os = "linux"))]
+mod poster {
+ //! Elsewhere than Linux there is no GStreamer to read a frame with: Apple's own poster stands.
+ pub fn first_seen_frame(_path: &std::path::Path) -> Result<Option<Vec<u8>>, String> {
+ Ok(None)
+ }
+}
mod push;
mod refresh;
mod video;
@@ -796,6 +804,19 @@ async fn auth_submit_sms_code(
Ok(())
}
+/// One search across every app's library — notes, reminders, events, contacts, files, photos —
+/// the first few of each and how many in all. Offline: read from the library alone.
+#[tauri::command]
+async fn search_everything(
+ query: String,
+ data: State<'_, Data>,
+) -> UiResult<quince_core::search::Everything> {
+ let library = data.0.lock().await;
+ library
+ .search_everything(&query, 5)
+ .map_err(|e| e.to_string())
+}
+
/// What of the signed-in account's has not reached Apple yet: asked before a sign-out, so a
/// choice to keep nothing on this computer is made knowing what it loses.
#[derive(Serialize)]
@@ -4266,6 +4287,7 @@ fn main() {
auth_submit_sms_code,
auth_sign_out,
account_unsent,
+ search_everything,
login::login_item_status,
mount::drive_kept,
mount::drive_keep,
diff --git a/src-tauri/src/mount.rs b/src-tauri/src/mount.rs
index 479a84f..dc7e07d 100644
--- a/src-tauri/src/mount.rs
+++ b/src-tauri/src/mount.rs
@@ -4,6 +4,9 @@
//! then sent), folders made, renames, moves, deletes into Recently Deleted. See
//! docs/mount-design.md.
+// The folder itself is FUSE, on Linux only; on Windows it waits for the Cloud Files API.
+#![cfg_attr(not(target_os = "linux"), allow(dead_code, unused_variables))]
+
use crate::{Auth, Data};
use quince_core::drive::DriveItem;
use quince_vfs::{Fut, Remote, Store};
diff --git a/src-tauri/src/photos.rs b/src-tauri/src/photos.rs
index 6bb012c..854973a 100644
--- a/src-tauri/src/photos.rs
+++ b/src-tauri/src/photos.rs
@@ -686,6 +686,226 @@ async fn new_link(
.ok_or_else(|| "That photo has no picture of that size.".into())
}
+/// A film's bytes on their way to the cache: where they are landing, how many there will be,
+/// how many have landed, and whether it ended (well or not). The player is served from it as it
+/// grows, so a film starts within a moment instead of after its whole download.
+pub struct Growth {
+ pub part: PathBuf,
+ /// Where it is kept once it is whole.
+ pub kept: PathBuf,
+ pub total: u64,
+ have: std::sync::atomic::AtomicU64,
+ pub done: std::sync::atomic::AtomicBool,
+ failed: std::sync::atomic::AtomicBool,
+ more: tokio::sync::Notify,
+}
+
+impl Growth {
+ /// A film of `total` bytes about to land at `part`, to be kept at `kept`.
+ pub fn new(part: PathBuf, kept: PathBuf, total: u64) -> Self {
+ Growth {
+ part,
+ kept,
+ total,
+ have: std::sync::atomic::AtomicU64::new(0),
+ done: std::sync::atomic::AtomicBool::new(false),
+ failed: std::sync::atomic::AtomicBool::new(false),
+ more: tokio::sync::Notify::new(),
+ }
+ }
+
+ /// `n` more bytes are in the file.
+ pub fn landed(&self, n: u64) {
+ self.have.fetch_add(n, std::sync::atomic::Ordering::SeqCst);
+ self.more.notify_waiters();
+ }
+
+ /// The download ended: whole and in place, or not.
+ pub fn ended(&self, whole: bool) {
+ use std::sync::atomic::Ordering;
+ if whole {
+ self.done.store(true, Ordering::SeqCst);
+ } else {
+ self.failed.store(true, Ordering::SeqCst);
+ }
+ self.more.notify_waiters();
+ }
+
+ /// Where its matrix is and what it says, once its header has landed — read a little more at
+ /// a time. `None`: it has no matrix.
+ pub async fn matrix(&self) -> Result<Option<(u64, [i32; 4])>, String> {
+ let read = |path: PathBuf| async move {
+ tokio::task::spawn_blocking(move || quince_media::video_matrix(&path))
+ .await
+ .map_err(|e| e.to_string())?
+ .map_err(|e| e.to_string())
+ };
+ let mut want = (256 * 1024).min(self.total);
+ loop {
+ let have = self.wait_for(want).await.ok_or("The film broke off.")?;
+ let done = have >= self.total && self.done.load(std::sync::atomic::Ordering::SeqCst);
+ // Renamed into place when it finished: read it there.
+ let at = if done {
+ self.kept.clone()
+ } else {
+ self.part.clone()
+ };
+ if let Ok(Some(found)) = read(at).await {
+ return Ok(Some(found));
+ }
+ if done {
+ return Ok(None);
+ }
+ want = (want * 2).min(self.total);
+ }
+ }
+
+ /// Waits until the file holds `upto` bytes (or ended); answers how many it holds, or `None`
+ /// when the download failed.
+ pub async fn wait_for(&self, upto: u64) -> Option<u64> {
+ use std::sync::atomic::Ordering;
+ loop {
+ let wake = self.more.notified();
+ if self.failed.load(Ordering::SeqCst) {
+ return None;
+ }
+ let have = self.have.load(Ordering::SeqCst);
+ let done = self.done.load(Ordering::SeqCst);
+ // All of it asked for: only once it is in place (renamed), never in that instant.
+ if done || (upto < self.total && have >= upto) {
+ return Some(have);
+ }
+ // Woken by every piece that lands; a second at most, never stuck on a missed wake.
+ let _ = tokio::time::timeout(Duration::from_secs(1), wake).await;
+ }
+ }
+}
+
+/// Films being fetched now, by where they will be kept: one download each, however many ask.
+static GROWING: Mutex<Option<HashMap<PathBuf, std::sync::Arc<Growth>>>> = Mutex::new(None);
+
+/// Where a film is: kept whole, or on its way.
+pub enum Film {
+ Whole(PathBuf),
+ Growing(std::sync::Arc<Growth>),
+}
+
+/// A film for the player: from the cache if it is kept, else fetched — once — with the player
+/// served from the bytes as they land.
+pub async fn film(app: &AppHandle, id: &str, size: Size) -> Result<Film, String> {
+ let path = cache_path(app, id, size);
+ if tokio::fs::metadata(&path).await.is_ok() {
+ return Ok(Film::Whole(path));
+ }
+ if let Some(g) = GROWING
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .as_ref()
+ .and_then(|m| m.get(&path).cloned())
+ {
+ return Ok(Film::Growing(g));
+ }
+ let photo = {
+ let data = app.state::<Data>();
+ let library = data.0.lock().await;
+ library
+ .photo(id)
+ .map_err(|e| e.to_string())?
+ .ok_or("That photo is no longer in the library.")?
+ };
+ let auth = app.state::<Auth>();
+ let (http, root, params) = crate::cloudkit_context(&auth).await?;
+ let ask = |url: String| {
+ let http = http.clone();
+ async move { http.get(url).send().await.map_err(|e| e.to_string()) }
+ };
+ let mut response = match fresh_links(&photo.master).and_then(|l| size.pick(&l)) {
+ Some(url) => ask(url).await.ok().filter(|r| r.status().is_success()),
+ None => None,
+ };
+ if response.is_none() {
+ let url = new_link(&http, &root, params, &photo, size).await?;
+ response = Some(ask(url).await?).filter(|r| r.status().is_success());
+ }
+ let response = response.ok_or("Apple did not send that film.")?;
+ let total = response.content_length().unwrap_or(0);
+ if total == 0 {
+ // No length said: fetched whole first, as any other picture.
+ drop(response);
+ return cached(app, id, size).await.map(Film::Whole);
+ }
+ if let Some(dir) = path.parent() {
+ tokio::fs::create_dir_all(dir)
+ .await
+ .map_err(|e| e.to_string())?;
+ }
+ let part = path.with_extension(format!("{}.part", uuid::Uuid::new_v4().simple()));
+ let file = tokio::fs::File::create(&part)
+ .await
+ .map_err(|e| e.to_string())?;
+ let growth = std::sync::Arc::new(Growth::new(part.clone(), path.clone(), total));
+ // Two asking at once: the first one's download is the one kept.
+ {
+ let mut growing = GROWING
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let map = growing.get_or_insert_with(HashMap::new);
+ if let Some(g) = map.get(&path) {
+ let _ = std::fs::remove_file(&part);
+ return Ok(Film::Growing(g.clone()));
+ }
+ map.insert(path.clone(), growth.clone());
+ }
+ let g = growth.clone();
+ tauri::async_runtime::spawn(async move {
+ use futures_util::StreamExt;
+ use std::sync::atomic::Ordering;
+ use tokio::io::AsyncWriteExt;
+ let mut out = file;
+ let mut body = response.bytes_stream();
+ let mut ok = true;
+ while let Some(chunk) = body.next().await {
+ let Ok(chunk) = chunk else {
+ ok = false;
+ break;
+ };
+ if out.write_all(&chunk).await.is_err() {
+ ok = false;
+ break;
+ }
+ // Flushed as it lands, so a reader of the file finds what is counted here.
+ let _ = out.flush().await;
+ g.landed(chunk.len() as u64);
+ }
+ drop(out);
+ ok = ok && g.have.load(Ordering::SeqCst) == g.total;
+ let whole = ok && tokio::fs::rename(&g.part, &path).await.is_ok();
+ if !whole {
+ let _ = tokio::fs::remove_file(&g.part).await;
+ }
+ g.ended(whole);
+ GROWING
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .as_mut()
+ .map(|m| m.remove(&path));
+ });
+ Ok(Film::Growing(growth))
+}
+
+/// A film's turn (its matrix), read as soon as its header has landed — a film from Apple's
+/// streaming copies keeps its header at the front — never waiting for the whole film.
+pub async fn film_turn(app: &AppHandle, id: &str, size: Size) -> Result<[i32; 4], String> {
+ let found = match film(app, id, size).await? {
+ Film::Whole(path) => tokio::task::spawn_blocking(move || quince_media::video_matrix(&path))
+ .await
+ .map_err(|e| e.to_string())?
+ .map_err(|e| e.to_string())?,
+ Film::Growing(g) => g.matrix().await?,
+ };
+ Ok(found.map_or([1, 0, 0, 1], |(_, m)| m))
+}
+
/// What a picture's bytes are, for the window to draw them.
/// The bytes a `Range: bytes=…` header asks of a file `len` long, as `(first, last)` inclusive,
/// at most `most` of them. No header is the whole file; one this file cannot satisfy is `None`.
@@ -1357,12 +1577,7 @@ pub async fn photo_video_turn(id: String, which: String, app: AppHandle) -> UiRe
} else {
Size::Original
};
- let path = cached(&app, &id, size).await?;
- let turn = tokio::task::spawn_blocking(move || quince_media::video_matrix(&path))
- .await
- .map_err(|e| e.to_string())?
- .map_err(|e| e.to_string())?;
- Ok(turn.map_or([1, 0, 0, 1], |(_, m)| m))
+ film_turn(&app, &id, size).await
}
/// A video opened in this computer's own player. WebKitGTK plays nothing without GStreamer's
@@ -1502,7 +1717,8 @@ pub async fn photo_set_date(
}
/// Where a photo was taken, opened in a map in the browser: OpenStreetMap at its coordinates.
-/// Apple's place names come from Apple Maps, which is not here; the place itself is.
+/// Apple's place names come from Apple Maps, which is not here; the place itself is, opened in
+/// this computer's own map app.
#[tauri::command]
pub async fn photo_open_map(id: String, app: AppHandle, data: State<'_, Data>) -> UiResult<()> {
let photo = data
@@ -1515,13 +1731,24 @@ pub async fn photo_open_map(id: String, app: AppHandle, data: State<'_, Data>) -
let (Some(lat), Some(lon)) = (photo.latitude, photo.longitude) else {
return Err("This photo has no place.".into());
};
+ // The place handed to this computer's own map app (a geo: link, RFC 5870, as GNOME Maps
+ // and the like take it) — never to a website: the photo's location goes nowhere else.
+ #[cfg(target_os = "linux")]
+ {
+ let handled = std::process::Command::new("xdg-mime")
+ .args(["query", "default", "x-scheme-handler/geo"])
+ .output()
+ .is_ok_and(|o| !String::from_utf8_lossy(&o.stdout).trim().is_empty());
+ if !handled {
+ return Err(format!(
+ "No map app on this computer opens places. The place is {lat:.6}, {lon:.6}."
+ ));
+ }
+ }
use tauri_plugin_opener::OpenerExt;
app.opener()
- .open_url(
- format!("https://www.openstreetmap.org/?mlat={lat:.6}&mlon={lon:.6}#map=16/{lat:.6}/{lon:.6}"),
- None::<&str>,
- )
- .map_err(|e| format!("No browser on this computer opened the map: {e}"))
+ .open_url(format!("geo:{lat:.6},{lon:.6}"), None::<&str>)
+ .map_err(|e| format!("The map app did not open: {e}"))
}
/// How many photos each view holds. Asked after every sync, which is also when an upload queue
diff --git a/src-tauri/src/video.rs b/src-tauri/src/video.rs
index 145af90..587e8e2 100644
--- a/src-tauri/src/video.rs
+++ b/src-tauri/src/video.rs
@@ -4,8 +4,7 @@
//! the loopback interface: a port of the system's choosing, a fresh secret in every path, only
//! cached videos by asset id, in the ranges the player asks for, streamed from disk.
-use crate::photos::{self, Size};
-use std::path::PathBuf;
+use crate::photos::{self, Film, Size};
use std::sync::OnceLock;
use tauri::AppHandle;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncSeekExt, AsyncWriteExt, BufReader};
@@ -34,17 +33,17 @@ pub fn serve(app: AppHandle) {
let _ = BASE.set(format!("http://127.0.0.1:{}/{secret}", addr.port()));
listen(listener, secret, move |id, size| {
let app = app.clone();
- async move { photos::cached(&app, &id, size).await }
+ async move { photos::film(&app, &id, size).await }
})
.await;
});
}
-/// Answers each connection on its own task; `find` gives a cached video's path on disk.
+/// Answers each connection on its own task; `find` gives a video: kept on disk, or landing.
async fn listen<F, Fut>(listener: TcpListener, secret: String, find: F)
where
F: Fn(String, Size) -> Fut + Clone + Send + Sync + 'static,
- Fut: std::future::Future<Output = Result<PathBuf, String>> + Send,
+ Fut: std::future::Future<Output = Result<Film, String>> + Send,
{
while let Ok((stream, _)) = listener.accept().await {
let (find, secret) = (find.clone(), secret.clone());
@@ -95,7 +94,7 @@ fn parse(secret: &str, lines: &[String]) -> Option<Asked> {
async fn answer<F, Fut>(find: F, secret: &str, stream: TcpStream) -> std::io::Result<()>
where
F: Fn(String, Size) -> Fut,
- Fut: std::future::Future<Output = Result<PathBuf, String>>,
+ Fut: std::future::Future<Output = Result<Film, String>>,
{
let mut reader = BufReader::new(stream);
let mut lines = Vec::new();
@@ -116,11 +115,30 @@ where
let Some(asked) = parse(secret, &lines) else {
return status(&mut stream, "404 Not Found", "").await;
};
- let Ok(path) = find(asked.id.clone(), asked.size).await else {
+ let Ok(film) = find(asked.id.clone(), asked.size).await else {
return status(&mut stream, "404 Not Found", "").await;
};
- let mut file = tokio::fs::File::open(&path).await?;
- let len = file.metadata().await?.len();
+ // A film still landing is served as it lands: its length is known, and each piece is
+ // waited for only as the player reaches it — it starts at once, not after the download.
+ let (mut file, len, growing, path) = match film {
+ Film::Whole(path) => {
+ let file = tokio::fs::File::open(&path).await?;
+ let len = file.metadata().await?.len();
+ (file, len, None, path)
+ }
+ Film::Growing(g) => {
+ // Just finished and renamed: then it is where it is kept.
+ let file = match tokio::fs::File::open(&g.part).await {
+ Ok(f) => f,
+ Err(_) => tokio::fs::File::open(&g.kept).await?,
+ };
+ if g.wait_for(12.min(g.total)).await.is_none() {
+ return status(&mut stream, "404 Not Found", "").await;
+ }
+ let kept = g.kept.clone();
+ (file, g.total, Some(g), kept)
+ }
+ };
let mut head = [0u8; 12];
let _ = file.read(&mut head).await;
let kind = photos::video_type(&head);
@@ -145,22 +163,34 @@ where
// WebKitGTK honoured it in one way of drawing and not another, and a front-camera Live
// Photo played sideways. So the film goes out upright — its matrix's 36 bytes, alone,
// replaced as they pass. The file on disk is untouched.
- let at = {
- let path = path.clone();
- tokio::task::spawn_blocking(move || quince_media::video_matrix(&path).ok().flatten())
+ let at = match &growing {
+ None => {
+ let path = path.clone();
+ tokio::task::spawn_blocking(move || {
+ quince_media::video_matrix(&path).ok().flatten()
+ })
.await
.ok()
.flatten()
- .filter(|(_, m)| *m != [1, 0, 0, 1])
- .map(|(at, _)| at)
- };
+ }
+ Some(g) => g.matrix().await.ok().flatten(),
+ }
+ .filter(|(_, m)| *m != [1, 0, 0, 1])
+ .map(|(at, _)| at);
// Streamed from disk: a long film is never held in memory, and a player that stops
// reading (a seek elsewhere) just closes the connection.
let mut pos = first;
let mut left = n;
let mut chunk = vec![0u8; 64 * 1024];
while left > 0 {
- let want = usize::try_from(left.min(chunk.len() as u64)).unwrap_or(chunk.len());
+ let mut want = left.min(chunk.len() as u64);
+ if let Some(g) = &growing {
+ let Some(have) = g.wait_for(pos + want).await else {
+ break;
+ };
+ want = want.min(have.saturating_sub(pos));
+ }
+ let want = usize::try_from(want).unwrap_or(chunk.len());
let got = file.read(&mut chunk[..want]).await?;
if got == 0 {
break;
@@ -225,7 +255,7 @@ mod tests {
let found = found.clone();
async move {
if id == "v1" {
- Ok(found)
+ Ok(Film::Whole(found))
} else {
Err("none".into())
}
@@ -282,6 +312,60 @@ mod tests {
});
}
+ /// A film still downloading plays at once: each range is answered as its bytes land, the
+ /// end of it included, and the bytes are the film's whatever the pieces it lands in.
+ #[test]
+ fn serves_a_film_while_it_lands() {
+ tauri::async_runtime::block_on(async {
+ let dir = std::env::temp_dir().join(format!("quince-growing-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let (part, kept) = (dir.join("clip.part"), dir.join("clip"));
+ let bytes: Vec<u8> = (0..300_000u32).map(|i| (i % 241) as u8).collect();
+ std::fs::write(&part, b"").unwrap();
+ let g = std::sync::Arc::new(photos::Growth::new(part.clone(), kept.clone(), 300_000));
+ let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let shared = g.clone();
+ tauri::async_runtime::spawn(listen(listener, "k".into(), move |_, _| {
+ let g = shared.clone();
+ async move { Ok(Film::Growing(g)) }
+ }));
+ // Lands in uneven pieces, a little at a time, then is renamed into place.
+ let (lander, all) = (g.clone(), bytes.clone());
+ tauri::async_runtime::spawn(async move {
+ use std::io::Write;
+ let mut f = std::fs::OpenOptions::new()
+ .append(true)
+ .open(&lander.part)
+ .unwrap();
+ for piece in all.chunks(37_000) {
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ f.write_all(piece).unwrap();
+ f.flush().unwrap();
+ lander.landed(piece.len() as u64);
+ }
+ std::fs::rename(&lander.part, &lander.kept).unwrap();
+ lander.ended(true);
+ });
+ let (head, body) = get(
+ port,
+ "GET /k/v/video HTTP/1.1\r\nRange: bytes=1000-1999\r\n\r\n",
+ )
+ .await;
+ assert!(
+ head.contains("Content-Range: bytes 1000-1999/300000"),
+ "{head}"
+ );
+ assert_eq!(body, bytes[1000..2000]);
+ let (head, body) = get(port, "GET /k/v/video HTTP/1.1\r\n\r\n").await;
+ assert!(head.contains("Content-Length: 300000"), "{head}");
+ assert_eq!(body, bytes);
+ let (_, body) = get(port, "GET /k/v/video HTTP/1.1\r\nRange: bytes=-500\r\n\r\n").await;
+ assert_eq!(body, bytes[299_500..]);
+ std::fs::remove_dir_all(&dir).ok();
+ });
+ }
+
/// A film is served upright whatever part of it is asked for: the matrix's bytes are
/// replaced exactly where they fall, a range that starts or ends inside them included,
/// and nothing else is touched.
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index f506222..8ebce9e 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -28,11 +28,7 @@
},
"bundle": {
"active": true,
- "targets": [
- "deb",
- "rpm",
- "appimage"
- ],
+ "targets": "all",
"icon": [
"icons/32x32.png",
"icons/64x64.png",
@@ -47,6 +43,16 @@
"licenseFile": "../LICENSE",
"homepage": "https://github.com/YashwanthKamireddi/quince",
"publisher": "Yashwanth Kamireddi",
+ "windows": {
+ "nsis": {
+ "installMode": "currentUser",
+ "displayLanguageSelector": false
+ },
+ "webviewInstallMode": {
+ "type": "downloadBootstrapper",
+ "silent": true
+ }
+ },
"linux": {
"deb": {
"depends": [
diff --git a/src/components/GlobalSearch.tsx b/src/components/GlobalSearch.tsx
new file mode 100644
index 0000000..37aa13c
--- /dev/null
+++ b/src/components/GlobalSearch.tsx
@@ -0,0 +1,281 @@
+/**
+ * One search across everything — notes, reminders, events, contacts, files, photos — at the
+ * head of the sidebar. Neither icloud.com nor a Mac has it: there each app searches only
+ * itself. Offline and at once (read from the library alone), a few of each kind with how many
+ * there are, and a choice opens that very thing in its own app.
+ *
+ * The keys, as Spotlight's: typing searches, Up and Down move through what was found, Return
+ * opens it, Escape puts the results away (and a second Escape clears the field).
+ */
+import { useEffect, useMemo, useRef, useState } from "react";
+import { Search, X } from "lucide-react";
+import {
+ api,
+ contactPhotoSrc,
+ displayName,
+ pictureSrc,
+ type CalendarEvent,
+ type Contact,
+ type DriveItem,
+ type Note,
+ type Photo,
+ type Reminder,
+} from "../lib/ipc";
+import { reveal } from "../lib/reveal";
+import { AppIcon } from "./AppIcon";
+import { Portal } from "./Portal";
+
+type Everything = {
+ notes: Note[];
+ reminders: Reminder[];
+ events: CalendarEvent[];
+ contacts: Contact[];
+ files: DriveItem[];
+ photos: Photo[];
+ counts: [number, number, number, number, number, number];
+};
+
+type Row = {
+ key: string;
+ screen: string;
+ id: string;
+ within?: string | null;
+ at?: number;
+ title: string;
+ detail: string;
+ picture?: string | null;
+};
+
+const when = (secs: number, allDay = false) =>
+ new Date(secs * 1000).toLocaleString(undefined, allDay
+ ? { day: "numeric", month: "short", year: "numeric" }
+ : { day: "numeric", month: "short", year: "numeric", hour: "numeric", minute: "2-digit" });
+
+/** What was found, as the rows of each app's section, in the sidebar's own order. */
+function sections(found: Everything): { screen: string; name: string; count: number; rows: Row[] }[] {
+ const all = [
+ {
+ screen: "notes",
+ name: "Notes",
+ count: found.counts[0],
+ rows: found.notes.map((n) => ({
+ key: `n${n.guid}`, screen: "notes", id: n.guid, title: n.title || "New Note",
+ detail: n.locked ? "Locked" : (n.snippet ?? "").replace(//g, "").trim() || "No additional text",
+ })),
+ },
+ {
+ screen: "reminders",
+ name: "Reminders",
+ count: found.counts[1],
+ rows: found.reminders.map((r) => ({
+ key: `r${r.guid}`, screen: "reminders", id: r.guid, within: r.listGuid, title: r.title,
+ detail: r.dueAt ? `Due ${when(r.dueAt)}` : (r.notes ?? "").trim(),
+ })),
+ },
+ {
+ screen: "calendar",
+ name: "Calendar",
+ count: found.counts[2],
+ rows: found.events.map((e) => ({
+ key: `e${e.guid}`, screen: "calendar", id: e.guid, within: e.calendarGuid, at: e.startsAt, title: e.title,
+ detail: [when(e.startsAt, e.allDay), e.location].filter(Boolean).join(" · "),
+ })),
+ },
+ {
+ screen: "contacts",
+ name: "Contacts",
+ count: found.counts[3],
+ rows: found.contacts.map((c) => ({
+ key: `c${c.guid}`, screen: "contacts", id: c.guid, title: displayName(c),
+ detail: c.methods[0]?.value ?? c.company ?? "",
+ picture: c.photoUrl ? contactPhotoSrc(c.guid) : null,
+ })),
+ },
+ {
+ screen: "drivews",
+ name: "iCloud Drive",
+ count: found.counts[4],
+ rows: found.files.map((f) => ({
+ key: `f${f.drivewsid}`, screen: "drivews", id: f.drivewsid, within: f.parentId,
+ title: f.extension ? `${f.name}.${f.extension}` : f.name,
+ detail: f.modifiedAt ? `Modified ${when(f.modifiedAt, true)}` : "",
+ })),
+ },
+ {
+ screen: "photos",
+ name: "Photos",
+ count: found.counts[5],
+ rows: found.photos.map((p) => ({
+ key: `p${p.id}`, screen: "photos", id: p.id, title: p.title || p.filename || "Photo",
+ detail: when(p.takenAt, true), picture: pictureSrc(p.id, "thumb"),
+ })),
+ },
+ ];
+ return all.filter((s) => s.rows.length > 0);
+}
+
+export function GlobalSearch({ onOpen, available }: { onOpen: (screen: string) => void; available: string[] }) {
+ const [query, setQuery] = useState("");
+ const [found, setFound] = useState<Everything | null>(null);
+ const [open, setOpen] = useState(false);
+ const [at, setAt] = useState(0);
+ const field = useRef<HTMLInputElement | null>(null);
+ const box = useRef<HTMLDivElement | null>(null);
+ const panel = useRef<HTMLDivElement | null>(null);
+ // The panel is drawn over the window (the sidebar clips what leaves it), under the field.
+ const [place, setPlace] = useState<{ left: number; top: number } | null>(null);
+
+ // Asked a moment after typing stops; the newest question's answer is the one kept.
+ useEffect(() => {
+ const q = query.trim();
+ if (!q) {
+ setFound(null);
+ return undefined;
+ }
+ let current = true;
+ const t = window.setTimeout(() => {
+ api.searchEverything(q).then(
+ (f) => {
+ if (!current) return;
+ setFound(f as Everything);
+ setAt(0);
+ },
+ () => current && setFound(null),
+ );
+ }, 90);
+ return () => {
+ current = false;
+ window.clearTimeout(t);
+ };
+ }, [query]);
+
+ // Away when the window is clicked anywhere else.
+ useEffect(() => {
+ if (!open) return undefined;
+ const down = (e: MouseEvent) => {
+ const t = e.target as Node;
+ if (!box.current?.contains(t) && !panel.current?.contains(t)) setOpen(false);
+ };
+ document.addEventListener("mousedown", down);
+ return () => document.removeEventListener("mousedown", down);
+ }, [open]);
+
+ const groups = useMemo(
+ () => (found ? sections(found).filter((s) => available.includes(s.screen)) : []),
+ [found, available],
+ );
+ const rows = useMemo(() => groups.flatMap((g) => g.rows), [groups]);
+
+ const choose = (r: Row) => {
+ setOpen(false);
+ onOpen(r.screen);
+ reveal({ screen: r.screen, id: r.id, within: r.within, at: r.at, query });
+ };
+
+ const onKey = (e: React.KeyboardEvent) => {
+ if (e.key === "Escape") {
+ e.preventDefault();
+ if (open && query) setOpen(false);
+ else {
+ setQuery("");
+ field.current?.blur();
+ }
+ } else if (e.key === "ArrowDown" && rows.length) {
+ e.preventDefault();
+ setOpen(true);
+ setAt((i) => Math.min(rows.length - 1, i + 1));
+ } else if (e.key === "ArrowUp" && rows.length) {
+ e.preventDefault();
+ setAt((i) => Math.max(0, i - 1));
+ } else if (e.key === "Enter" && rows[at]) {
+ e.preventDefault();
+ choose(rows[at]);
+ }
+ };
+
+ const showing = open && query.trim() !== "" && found !== null;
+ useEffect(() => {
+ if (!showing) return undefined;
+ const put = () => {
+ const r = box.current?.getBoundingClientRect();
+ if (r) setPlace({ left: r.left, top: r.bottom + 6 });
+ };
+ put();
+ window.addEventListener("resize", put);
+ return () => window.removeEventListener("resize", put);
+ }, [showing]);
+ return (
+ <div className="gsearch" ref={box}>
+ <label className="gsearch-field">
+ <Search size={14} strokeWidth={2.2} aria-hidden="true" />
+ <input
+ ref={field}
+ type="search"
+ placeholder="Search"
+ aria-label="Search everything"
+ aria-expanded={showing}
+ aria-controls="gsearch-results"
+ aria-activedescendant={showing && rows[at] ? `gs-${rows[at].key}` : undefined}
+ role="combobox"
+ value={query}
+ onChange={(e) => {
+ setQuery(e.target.value);
+ setOpen(true);
+ }}
+ onFocus={() => query && setOpen(true)}
+ onKeyDown={onKey}
+ />
+ {query && (
+ <button className="gsearch-clear" aria-label="Clear search" onClick={() => { setQuery(""); field.current?.focus(); }}>
+ <X size={12} strokeWidth={2.4} aria-hidden="true" />
+ </button>
+ )}
+ </label>
+ {showing && place && (
+ <Portal>
+ <div
+ ref={panel}
+ className="gsearch-results"
+ id="gsearch-results"
+ role="listbox"
+ aria-label="Found"
+ style={{ left: place.left, top: place.top }}
+ // A click on a result never takes the focus from the field: the keys go on working.
+ onMouseDown={(e) => e.preventDefault()}
+ >
+ {groups.length === 0 && <p className="gsearch-none">Nothing in your iCloud holds “{query.trim()}”.</p>}
+ {groups.map((g) => (
+ <section key={g.screen} className="gsearch-group" aria-label={g.name}>
+ <h3>
+ <AppIcon app={g.screen} />
+ <span>{g.name}</span>
+ {g.count > g.rows.length && <span className="gsearch-count">{g.rows.length} of {g.count}</span>}
+ </h3>
+ {g.rows.map((r) => {
+ const i = rows.indexOf(r);
+ return (
+ <button
+ key={r.key}
+ id={`gs-${r.key}`}
+ role="option"
+ aria-selected={i === at}
+ className={`gsearch-row${i === at ? " is-at" : ""}`}
+ onMouseMove={() => i !== at && setAt(i)}
+ onClick={() => choose(r)}
+ >
+ {r.picture && <img className="gsearch-pic" src={r.picture} alt="" decoding="async" draggable={false} />}
+ <span className="gsearch-text">
+ <span className="gsearch-title">{r.title}</span>
+ {r.detail && <span className="gsearch-detail">{r.detail}</span>}
+ </span>
+ </button>
+ );
+ })}
+ </section>
+ ))}
+ </div>
+ </Portal>
+ )}
+ </div>
+ );
+}
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index f522de9..4d30a03 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -106,6 +106,8 @@ export const api = {
photosFolderStatus: () => invoke<DriveFolder>("photos_folder_status"),
/** What the iCloud Drive folder keeps on this computer; null while the folder is off. */
driveKept: () => invoke<string[] | null>("drive_kept"),
+ /** One search across every app's library: the first few of each, and how many in all. */
+ searchEverything: (query: string) => invoke<unknown>("search_everything", { query }),
driveKeep: (drivewsid: string, on: boolean) => invoke<string[]>("drive_keep", { drivewsid, on }),
photosFolderSet: (on: boolean) => invoke<DriveFolder>("photos_folder_set", { on }),
/** Open at Login: whether it is on, the command it runs, and whether this desktop runs it. */
diff --git a/src/lib/reveal.ts b/src/lib/reveal.ts
new file mode 100644
index 0000000..4cbf1dc
--- /dev/null
+++ b/src/lib/reveal.ts
@@ -0,0 +1,40 @@
+/**
+ * Asking a screen to show one thing — a note, a reminder, an event, a contact, a file, a
+ * photo — found somewhere else (the search across everything). The screen may not be built
+ * yet (screens are built the first time they are opened), so a request waits until its
+ * screen takes it: at once if it is listening, or when it first comes up.
+ */
+import { useEffect, useRef } from "react";
+
+/** `within`: where it lives, when the screen needs it to get there — a reminder's list, a
+ * file's folder. */
+export type Reveal = { screen: string; id: string; within?: string | null; query?: string; at?: number };
+
+const EVENT = "quince:reveal";
+const waiting = new Map<string, Reveal>();
+
+/** Show `id` on `screen`; the screen is brought to the front by whoever asks. */
+export function reveal(r: Reveal) {
+ waiting.set(r.screen, r);
+ window.dispatchEvent(new CustomEvent<Reveal>(EVENT, { detail: r }));
+}
+
+/** A screen's part: `show` is called with each request meant for it, now or waiting. */
+export function useReveal(screen: string, show: (r: Reveal) => void) {
+ const latest = useRef(show);
+ latest.current = show;
+ useEffect(() => {
+ const take = () => {
+ const r = waiting.get(screen);
+ if (!r) return;
+ waiting.delete(screen);
+ latest.current(r);
+ };
+ take();
+ const on = (e: Event) => {
+ if ((e as CustomEvent<Reveal>).detail.screen === screen) take();
+ };
+ window.addEventListener(EVENT, on);
+ return () => window.removeEventListener(EVENT, on);
+ }, [screen]);
+}
diff --git a/src/screens/ContactsView.tsx b/src/screens/ContactsView.tsx
index 043749c..3982c4b 100644
--- a/src/screens/ContactsView.tsx
+++ b/src/screens/ContactsView.tsx
@@ -17,6 +17,7 @@ import { RowMenu, type MenuEntry } from "../components/RowMenu";
import { Portal } from "../components/Portal";
import { open as openFileDialog } from "@tauri-apps/plugin-dialog";
import { dateText } from "../lib/when";
+import { useReveal } from "../lib/reveal";
/** The sidebar row that is every contact rather than a list. */
const ALL = "";
@@ -127,6 +128,15 @@ export function ContactsView() {
const [lists, setLists] = useState<ContactList[]>([]);
/** The list being looked at, or ALL. */
const [list, setList] = useState<string>(ALL);
+ // A contact found by the search across everything: shown, from All Contacts and with this
+ // screen's own search cleared, so nothing here hides it.
+ useReveal("contacts", (r) => {
+ setList(ALL);
+ setSearch("");
+ setDraft(null);
+ setOpenGuid(r.id);
+ setDetail(true);
+ });
/** A list whose name is being typed: "new" for one not made yet. */
const [naming, setNaming] = useState<string | null>(null);
const [listMenu, setListMenu] = useState<(MenuAt & { list: ContactList }) | null>(null);
diff --git a/src/screens/DriveView.tsx b/src/screens/DriveView.tsx
index a2e43b5..609bb26 100644
--- a/src/screens/DriveView.tsx
+++ b/src/screens/DriveView.tsx
@@ -25,6 +25,7 @@ import { Picker } from "../components/Picker";
import { RowMenu } from "../components/RowMenu";
import { dateText, timeText } from "../lib/when";
import { Clock } from "lucide-react";
+import { useReveal } from "../lib/reveal";
/** iCloud Drive's own four orders, as its "by Name" menu offers them. */
const SORTS = [
@@ -498,6 +499,35 @@ export function DriveView() {
const [info, setInfo] = useState<DriveItem | null>(null);
/** The one item selected, as a click in Finder selects it. */
const [selected, setSelected] = useState<string | null>(null);
+ // A file or folder found by the search across everything: its folder opened, with the whole
+ // path above it in the trail, and it selected and brought into view — as Finder's "Show in
+ // Enclosing Folder". The path is walked up from the library, which knows every folder seen.
+ const revealing = useRef<string | null>(null);
+ useReveal("drivews", (r) => {
+ void (async () => {
+ const crumbs: Crumb[] = [];
+ let at = r.within ?? null;
+ for (let hops = 0; at && at !== DRIVE_ROOT && hops < 64; hops++) {
+ const folder: DriveItem | null = await api.driveItem(at).catch(() => null);
+ if (!folder) break;
+ crumbs.unshift({ id: folder.drivewsid, name: driveName(folder) });
+ at = folder.parentId ?? null;
+ }
+ setInTrash(false);
+ setInRecents(false);
+ setTrail([{ id: DRIVE_ROOT, name: "iCloud Drive" }, ...crumbs]);
+ revealing.current = r.id;
+ setSelected(r.id);
+ })();
+ });
+ useEffect(() => {
+ const id = revealing.current;
+ if (!id || !items.some((i) => i.drivewsid === id)) return;
+ revealing.current = null;
+ requestAnimationFrame(() =>
+ document.querySelector(`.drive [data-id="${CSS.escape(id)}"]`)?.scrollIntoView({ block: "center" }),
+ );
+ }, [items]);
/** The ⋯ menu, or the same menu opened by a right-click, for one item. */
const [menu, setMenu] = useState<{ item: DriveItem; x: number; y: number; alignRight: boolean } | null>(null);
/** An item of Drive's own being dragged onto a folder, and the folder it is over. */
@@ -1194,7 +1224,7 @@ export function DriveView() {
const container = isContainer(item);
const busy = busyGuid === item.drivewsid;
return (
- <li key={item.drivewsid}>
+ <li key={item.drivewsid} data-id={item.drivewsid}>
{renaming === item.drivewsid ? (
<div className="drive-row">
<span className="drive-badge" aria-hidden="true">
diff --git a/src/screens/Library.tsx b/src/screens/Library.tsx
index 510f681..0658165 100644
--- a/src/screens/Library.tsx
+++ b/src/screens/Library.tsx
@@ -29,6 +29,7 @@ const SettingsView = lazy(loaders.settings);
import { ScreenBoundary } from "../components/ScreenBoundary";
import { ScreenActive } from "../lib/screen";
import { AppIcon } from "../components/AppIcon";
+import { GlobalSearch } from "../components/GlobalSearch";
/**
* What the sidebar holds: the services with a real screen behind them, most used first.
@@ -263,6 +264,7 @@ export function Library({ onSignOut }: { onSignOut: (keep: boolean) => Promise<v
<PanelLeft size={16} strokeWidth={2} aria-hidden="true" />
</button>
</div>
+ {!rail && <GlobalSearch available={services} onOpen={(screen) => choose(screen)} />}
{services.map(item)}
{!ready && !error && <p className="badge">Loading…</p>}
{error && (
@@ -276,7 +278,10 @@ export function Library({ onSignOut }: { onSignOut: (keep: boolean) => Promise<v
</div>
</nav>
- <main className="content" ref={content}>
+ {/* Which screen is in front, for its layout (each screen's CSS keys on it): asked with
+ :has() across the whole content instead, WebKit checked it again on every change
+ anywhere inside — every tile's selection in a 20,000-photo grid. */}
+ <main className="content" ref={content} data-screen={selected}>
{webAccess === false && selected !== "settings" ? (
// Advanced Data Protection with web access off: every read would fail, and each
// screen would say so its own way. One plain answer, with Apple's own switch.
diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsx
index 84eeeab..5810d81 100644
--- a/src/screens/NotesView.tsx
+++ b/src/screens/NotesView.tsx
@@ -11,6 +11,7 @@ import { NoteEditor, refreshTables, type EditorHandle, type EditorStatus } from
import { FormatPanel } from "./notes/FormatPanel";
import { NotePicture } from "./notes/NotePicture";
import { OPEN_NOTE_EVENT } from "./notes/links";
+import { useReveal } from "../lib/reveal";
import { useSync } from "../lib/sync";
import { Picker } from "../components/Picker";
@@ -212,21 +213,25 @@ export function NotesView() {
// A link to another note, followed: that note opened — from All iCloud when the folder in
// front does not hold it — or, when it is not in this account's notes, said so.
const following = useRef<string | null>(null);
+ const follow = (guid: string) => {
+ if (notes.some((n) => n.guid === guid)) {
+ setOpenGuid(guid);
+ setDetail(true);
+ return;
+ }
+ following.current = guid;
+ if (folder !== ALL) setFolder(ALL);
+ else void read();
+ };
+ const followRef = useRef(follow);
+ followRef.current = follow;
useEffect(() => {
- const follow = (e: Event) => {
- const guid = (e as CustomEvent<string>).detail;
- if (notes.some((n) => n.guid === guid)) {
- setOpenGuid(guid);
- setDetail(true);
- return;
- }
- following.current = guid;
- if (folder !== ALL) setFolder(ALL);
- else void read();
- };
- window.addEventListener(OPEN_NOTE_EVENT, follow);
- return () => window.removeEventListener(OPEN_NOTE_EVENT, follow);
- }, [notes, folder, read]);
+ const on = (e: Event) => followRef.current((e as CustomEvent<string>).detail);
+ window.addEventListener(OPEN_NOTE_EVENT, on);
+ return () => window.removeEventListener(OPEN_NOTE_EVENT, on);
+ }, []);
+ // A note found by the search across everything: opened as a link to it opens it.
+ useReveal("notes", (r) => followRef.current(r.id));
useEffect(() => {
const guid = following.current;
if (!guid || folder !== ALL || notes.length === 0) return;
diff --git a/src/screens/PhotosView.tsx b/src/screens/PhotosView.tsx
index 3968a1e..7aa806c 100644
--- a/src/screens/PhotosView.tsx
+++ b/src/screens/PhotosView.tsx
@@ -36,6 +36,7 @@ import { tintFrom } from "../lib/tint";
import { fadeIn } from "../lib/fade";
import { DownloadOptions, type Want } from "./photos/DownloadOptions";
import { AdjustDate } from "./photos/AdjustDate";
+import { useReveal } from "../lib/reveal";
/** The sidebar, in Photos' order, each with the symbol Photos gives it. */
const VIEWS: { key: PhotoView; label: string; Icon: LucideIcon }[] = [
@@ -349,6 +350,65 @@ const Tile = memo(function Tile({
* block exactly as tall as its rows will be (worked out in CSS from the grid's own width),
* so a library of tens of thousands opens at once and scrolls without the bar jumping.
*/
+/** The ids whose selection differs between two selections, worked out once per pair. */
+const diffs = new WeakMap<Set<string>, { from: Set<string>; changed: string[] }>();
+function changedBetween(from: Set<string>, to: Set<string>): string[] {
+ const known = diffs.get(to);
+ if (known && known.from === from) return known.changed;
+ const changed: string[] = [];
+ for (const id of from) if (!to.has(id)) changed.push(id);
+ for (const id of to) if (!from.has(id)) changed.push(id);
+ diffs.set(to, { from, changed });
+ return changed;
+}
+/** A month's photo ids, made once per list of them. */
+const monthIds = new WeakMap<object, Set<string>>();
+function idsOf(items: { photo: Photo }[]): Set<string> {
+ let ids = monthIds.get(items);
+ if (!ids) {
+ ids = new Set(items.map((x) => x.photo.id));
+ monthIds.set(items, ids);
+ }
+ return ids;
+}
+
+/**
+ * Whether a month draws the same as before: everything it was given is the same, except a
+ * selection or a focused tile that changed somewhere else. One click used to draw every built
+ * month again — every one was handed the whole selection — 166 ms on a 20,000-photo library.
+ */
+function sameMonth(a: MonthProps, b: MonthProps): boolean {
+ if (a.label !== b.label || a.items !== b.items || a.deleted !== b.deleted || a.eager !== b.eager
+ || a.fit !== b.fit || a.cell !== b.cell || a.act !== b.act) return false;
+ if (a.chosen !== b.chosen) {
+ // Only the photos whose selection changed are looked at (worked out once per change, not
+ // once per month), each against this month's own photos.
+ const changed = changedBetween(a.chosen, b.chosen);
+ const mine = idsOf(a.items);
+ for (const id of changed) if (mine.has(id)) return false;
+ }
+ if (a.anchor !== b.anchor) {
+ const first = a.items[0]?.index ?? 0;
+ const last = a.items[a.items.length - 1]?.index ?? -1;
+ const here = (n: number | null) => n !== null && n >= first && n <= last;
+ // The tile that takes Tab is the anchor's, or the first of all when there is none.
+ if (here(a.anchor) || here(b.anchor) || ((a.anchor === null) !== (b.anchor === null) && first === 0)) return false;
+ }
+ return true;
+}
+
+type MonthProps = {
+ label: string;
+ items: { photo: Photo; index: number }[];
+ chosen: Set<string>;
+ anchor: number | null;
+ deleted: boolean;
+ eager: boolean;
+ fit: boolean;
+ cell: number;
+ act: Acts;
+};
+
const Month = memo(function Month({
label,
items,
@@ -415,17 +475,17 @@ const Month = memo(function Month({
})}
</div>
) : (
- // 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" />
- ))}
+ // Not built yet (far from the screen): one block as tall as its rows will be, its tiles
+ // painted on it as plain boxes, so a fast scroll shows photos on their way — never an
+ // empty page. One element, not one a photo: a box each was 20,000 on a large library,
+ // and every focus and every frame paid for them (photos-scale).
+ <div className="px-later" aria-hidden="true" style={{ "--n": items.length } as React.CSSProperties}>
+ <i className="px-later-in" />
</div>
)}
</section>
);
-});
+}, sameMonth);
export function PhotosView() {
const { revision } = useSync();
@@ -923,7 +983,12 @@ export function PhotosView() {
useEffect(() => setMoving(null), [shown?.id]);
/** How the film being played is turned, as its file records it (see turnStyle). */
const [turn, setTurn] = useState<{ key: string; value: Turn } | null>(null);
- const turnFor = shown?.kind === "video" ? `${shown.id}/original` : moving && moving === shown?.id ? `${moving}/video` : null;
+ /** Videos Apple keeps no streaming copy of: played from the original instead. */
+ const [noCopy, setNoCopy] = useState<Set<string>>(() => new Set());
+ // A video plays from Apple's streaming copy (H.264, its header first: it starts at once), not
+ // the original as shot — often a gigabyte of HEVC this computer can barely decode.
+ const film = shown?.kind === "video" ? `${shown.id}/${noCopy.has(shown.id) ? "original" : "video"}` : null;
+ const turnFor = film ?? (moving && moving === shown?.id ? `${moving}/video` : null);
useEffect(() => {
if (!turnFor || turn?.key === turnFor) return undefined;
let live = true;
@@ -1266,7 +1331,37 @@ export function PhotosView() {
}
};
- const selected = useMemo(() => (photos ?? []).filter((p) => chosen.has(p.id)), [photos, chosen]);
+ // Where each photo is, by id: the selection is turned into photos by looking them up, in the
+ // order they are shown — not by walking the whole library on every click.
+ const placeOf = useMemo(() => new Map((photos ?? []).map((p, i) => [p.id, i] as const)), [photos]);
+ const selected = useMemo(() => {
+ const all = photos ?? [];
+ return [...chosen]
+ .map((id) => placeOf.get(id))
+ .filter((i): i is number => i !== undefined)
+ .sort((x, y) => x - y)
+ .map((i) => all[i]);
+ }, [photos, chosen, placeOf]);
+
+ // A photo found by the search across everything: the whole library shown, and the photo
+ // opened in the viewer once the library's photos are here.
+ const revealing = useRef<string | null>(null);
+ useReveal("photos", (r) => {
+ revealing.current = r.id;
+ setAlbum(null);
+ setAlbumsPage(false);
+ setSharedPage(false);
+ endSearch();
+ setView("library");
+ });
+ useEffect(() => {
+ const id = revealing.current;
+ if (!id || view !== "library" || album) return;
+ const at = (photos ?? []).findIndex((p) => p.id === id);
+ if (at < 0) return;
+ revealing.current = null;
+ void openAt(at);
+ }, [photos, view, album]); // eslint-disable-line react-hooks/exhaustive-deps
const openAt = async (index: number) => {
const p = photos?.[index];
@@ -2671,18 +2766,22 @@ export function PhotosView() {
}}
>
{shown.kind === "video" && videoBase && !unplayable.has(shown.id) ? (
- // Played here, as Photos plays one: from the disk cache, in the pieces the
- // player asks for, so it starts at once and seeks anywhere.
+ // Played here, as Photos plays one: in the pieces the player asks for, served
+ // as they arrive from Apple, so it starts at once and seeks anywhere.
<div className="px-video">
<VideoPlayer
- key={shown.id}
- turn={turn?.key === `${shown.id}/original` ? turn.value : undefined}
+ key={film}
+ turn={turn?.key === film ? turn.value : undefined}
shape={{ w: shown.width, h: shown.height }}
- src={`${videoBase}/${shown.id}/original`}
+ src={`${videoBase}/${film}`}
poster={viewSrc(shown)}
label={shown.filename ?? "Video"}
style={fitted(shown)}
- onError={() => setUnplayable((was) => new Set(was).add(shown.id))}
+ onError={() =>
+ noCopy.has(shown.id)
+ ? setUnplayable((was) => new Set(was).add(shown.id))
+ : setNoCopy((was) => new Set(was).add(shown.id))
+ }
/>
</div>
) : shown.kind === "video" ? (
diff --git a/src/screens/RemindersView.tsx b/src/screens/RemindersView.tsx
index 82eeb0f..c6c0810 100644
--- a/src/screens/RemindersView.tsx
+++ b/src/screens/RemindersView.tsx
@@ -23,6 +23,7 @@ import { Picker } from "../components/Picker";
import { RowMenu } from "../components/RowMenu";
import { Glyph, emblemGlyph, type GlyphName } from "../components/Glyph";
import { dateText, timeText } from "../lib/when";
+import { useReveal } from "../lib/reveal";
/** Apple's built-in views, in Apple's order, each with the glyph and system colour its app uses. */
const SMART: { kind: SmartList; title: string; glyph: GlyphName; colour: string }[] = [
@@ -215,7 +216,25 @@ export function RemindersView() {
kind: "today",
});
const [selection, setShown] = useState<Selection>(picked);
+ // A reminder found by the search across everything: its list opened, its details shown,
+ // and its row brought into view once the list has come.
+ const revealing = useRef<string | null>(null);
+ useReveal("reminders", (r) => {
+ if (r.within) setSelection({ type: "list", guid: r.within });
+ revealing.current = r.id;
+ setOpenGuid(r.id);
+ });
const [items, setItems] = useState<Reminder[]>([]);
+ useEffect(() => {
+ const id = revealing.current;
+ if (!id || !items.some((r) => r.guid === id)) return;
+ revealing.current = null;
+ requestAnimationFrame(() =>
+ document.querySelector(`.rx-row [aria-label="Rename ${CSS.escape(items.find((r) => r.guid === id)?.title ?? "")}"]`)
+ ?.closest(".rx-row")
+ ?.scrollIntoView({ block: "center" }),
+ );
+ }, [items]);
const [showDone, setShowDone] = useState(false);
const [syncing, setSyncing] = useState(false);
/** Every reminder with a write still on its way — a set, since several can be at once. */
@@ -425,8 +444,37 @@ export function RemindersView() {
/** Each reminder's ticks, sent to Apple one after another, in the order they were made. */
const ticks = useRef(new Map<string, Promise<unknown>>());
+ /**
+ * A repeating reminder ticked: shown ticked for a moment — the circle filled — before it
+ * rolls on to its next date, as on the Mac; and while it does, a second click on it is not
+ * taken. Rolled on at once, the row came back unticked as if nothing had happened, a click
+ * again ticked the next day too, and a daily reminder skipped a day (one,
+ * ticked twice three seconds apart, came out due the day after tomorrow).
+ */
+ const [settling, setSettling] = useState<Set<string>>(() => new Set());
+ // Read by the click itself: a double-click's second click comes before the redraw.
+ const held = useRef(new Set<string>());
+ const SETTLE_MS = 1500;
const toggle = (r: Reminder) => {
const wasOpen = !r.completedAt;
+ const repeating = repeatLabel(r) !== null;
+ if (repeating) {
+ // Not taken while it settles, nor until Apple has the tick before; once it shows open
+ // again with its next date, a tick counts.
+ if (held.current.has(r.guid) || ticks.current.has(r.guid)) return;
+ if (wasOpen) {
+ held.current.add(r.guid);
+ setSettling((was) => new Set(was).add(r.guid));
+ window.setTimeout(() => {
+ held.current.delete(r.guid);
+ setSettling((was) => {
+ const next = new Set(was);
+ next.delete(r.guid);
+ return next;
+ });
+ }, SETTLE_MS);
+ }
+ }
// Shown at once, every time, even while an earlier tick of this one is on its way — a
// repeating one too: its circle fills now, and it rolls on to its next date when Apple
// has made it (waiting for that, a tick on one showed nothing at all for a second or two).
@@ -1265,7 +1313,7 @@ export function RemindersView() {
<button
className="rx-tick"
role="checkbox"
- aria-checked={Boolean(reminder.completedAt)}
+ aria-checked={Boolean(reminder.completedAt) || settling.has(reminder.guid)}
aria-label={reminder.title}
style={{ "--tick": colourOf(home) } as React.CSSProperties}
// The fill springs in on the press itself, and only then: kept as state,
diff --git a/src/screens/calendar/CalendarView.tsx b/src/screens/calendar/CalendarView.tsx
index 01c4a1b..0c3dc63 100644
--- a/src/screens/calendar/CalendarView.tsx
+++ b/src/screens/calendar/CalendarView.tsx
@@ -33,6 +33,7 @@ import {
weekSpans,
} from "./model";
import { dateText, timeText } from "../../lib/when";
+import { useReveal } from "../../lib/reveal";
const ZONE = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
@@ -268,6 +269,13 @@ export function CalendarView() {
const [naming, setNaming] = useState<string | null>(null);
const [calMenu, setCalMenu] = useState<{ cal: Calendar; at: { x: number; y: number; alignRight: boolean } } | null>(null);
const [hidden, setHidden] = useState<Set<string>>(() => readSet(HIDDEN_KEY));
+ // An event found by the search across everything: its day shown, and its calendar too if
+ // it was hidden — never a found event that cannot be seen.
+ useReveal("calendar", (r) => {
+ if (r.at) setSelected(midnight(new Date(r.at * 1000)));
+ const cal = r.within;
+ if (cal) setHidden((h) => (h.has(cal) ? new Set([...h].filter((g) => g !== cal)) : h));
+ });
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState<string | null>(null);
const [draft, setDraft] = useState<Draft | null>(null);
diff --git a/src/styles/app.css b/src/styles/app.css
index 34769e0..b13b6ec 100644
--- a/src/styles/app.css
+++ b/src/styles/app.css
@@ -539,7 +539,7 @@
* window left the content 520px, and a phone number wrapped over four lines.
*/
@media (max-width: 900px) {
- /* Outranks each screen's own `.content:has(...)` padding. */
+ /* Outranks each screen's own `.content[data-screen]` padding. */
.library > main.content { padding: 54px 16px 16px; }
.sidebar {
z-index: 30;
@@ -748,7 +748,7 @@
.cal-empty { margin-top: 14px; color: var(--text-2); max-width: 54ch; }
/* The content pane holds the grid, so it must not scroll independently. */
-.content:has(> .screen-slot:not([hidden]) .cal) { display: flex; flex-direction: column; overflow: hidden; }
+.content[data-screen="calendar"] { display: flex; flex-direction: column; overflow: hidden; }
.rem-lists {
overflow-y: auto;
@@ -999,7 +999,7 @@
.contact-notes { margin-top: 20px; color: var(--text-2); white-space: pre-wrap; }
-.content:has(> .screen-slot:not([hidden]) .contacts) { display: flex; flex-direction: column; overflow: hidden; }
+.content[data-screen="contacts"] { display: flex; flex-direction: column; overflow: hidden; }
/* ---- iCloud Drive ---------------------------------------------------------------
A file browser: a path you can walk back along, then rows of what is here. */
@@ -1220,7 +1220,7 @@
.drive-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.drive-meta { color: var(--text-2); font-size: var(--t-11); font-variant-numeric: tabular-nums; }
-.content:has(> .screen-slot:not([hidden]) .drive) { display: flex; flex-direction: column; overflow: hidden; }
+.content[data-screen="drivews"] { display: flex; flex-direction: column; overflow: hidden; }
/*
* A narrow window, as Files on iPhone sets a row: the name gets the width, with its size and
@@ -2099,3 +2099,46 @@
background: color-mix(in srgb, var(--text) 7%, transparent); color: var(--text); user-select: all;
white-space: normal; word-break: break-all; cursor: text; }
.settings-hint.is-trouble { color: var(--danger); white-space: normal; }
+
+/* ---- Search across everything (components/GlobalSearch) ---------------------------------
+ A field at the head of the sidebar, as Finder's; what it finds over the window under it,
+ grouped by app as Spotlight groups it. */
+.gsearch { margin: 0 0 8px; }
+.gsearch-field {
+ display: flex; align-items: center; gap: 6px; height: 28px; padding: 0 8px; border-radius: 8px;
+ background: color-mix(in srgb, var(--text) 7%, transparent); color: var(--text-2);
+}
+.gsearch-field:focus-within { outline: 2px solid var(--accent-ring, var(--accent)); outline-offset: -1px; }
+.gsearch-field input {
+ flex: 1; min-width: 0; height: 100%; border: 0; background: none; color: var(--text); font: inherit;
+ font-size: var(--t-13); outline: none;
+}
+.gsearch-field input::-webkit-search-cancel-button { display: none; }
+.gsearch-clear {
+ display: grid; place-items: center; width: 16px; height: 16px; padding: 0; border: 0; border-radius: 50%;
+ background: color-mix(in srgb, var(--text) 30%, transparent); color: var(--bg); cursor: pointer;
+}
+.gsearch-results {
+ position: fixed; z-index: 70; width: min(420px, calc(100vw - 24px)); max-height: min(70vh, 560px);
+ overflow-y: auto; padding: 6px; border-radius: 12px;
+ /* Solid, as a menu of results must be: what lies under it must never read through. */
+ background: var(--sheet, var(--bg)); box-shadow: var(--glass-float), 0 0 0 0.5px var(--separator); color: var(--text);
+}
+.gsearch-group + .gsearch-group { margin-top: 4px; padding-top: 4px; border-top: 1px solid var(--separator); }
+.gsearch-group h3 {
+ display: flex; align-items: center; gap: 6px; margin: 0; padding: 4px 6px; font-size: var(--t-11);
+ font-weight: 600; color: var(--text-2);
+}
+.gsearch-group h3 .app-icon { width: 16px; height: 16px; }
+.gsearch-count { margin-left: auto; font-weight: 400; color: var(--text-3); }
+.gsearch-row {
+ display: flex; align-items: center; gap: 8px; width: 100%; min-height: 36px; padding: 4px 8px; border: 0;
+ border-radius: 7px; background: none; color: inherit; font: inherit; text-align: start; cursor: default;
+}
+.gsearch-row.is-at { background: var(--accent); color: var(--on-accent, #fff); }
+.gsearch-row.is-at .gsearch-detail { color: inherit; opacity: 0.85; }
+.gsearch-pic { width: 28px; height: 28px; border-radius: 5px; object-fit: cover; flex: none; }
+.gsearch-text { display: flex; flex-direction: column; min-width: 0; }
+.gsearch-title { font-size: var(--t-13); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.gsearch-detail { font-size: var(--t-11); color: var(--text-2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.gsearch-none { margin: 0; padding: 10px; font-size: var(--t-13); color: var(--text-2); }
diff --git a/src/styles/calendar.css b/src/styles/calendar.css
index 1d47fe9..567d996 100644
--- a/src/styles/calendar.css
+++ b/src/styles/calendar.css
@@ -1,6 +1,6 @@
/* Calendar, laid out the way macOS Calendar is. Scoped under `.cx`. */
-.content:has(> .screen-slot:not([hidden]) .cx) {
+.content[data-screen="calendar"] {
display: flex;
flex-direction: column;
overflow: hidden;
diff --git a/src/styles/notes.css b/src/styles/notes.css
index 6ae9ccf..ad57110 100644
--- a/src/styles/notes.css
+++ b/src/styles/notes.css
@@ -1,6 +1,6 @@
/* Notes, laid out the way Apple Notes is: folders, the list, the note. */
-.content:has(> .screen-slot:not([hidden]) .notes) { display: flex; flex-direction: column; overflow: hidden; padding-top: 18px; }
+.content[data-screen="notes"] { display: flex; flex-direction: column; overflow: hidden; padding-top: 18px; }
.notes {
flex: 1;
diff --git a/src/styles/photos.css b/src/styles/photos.css
index 1e64a9f..1435214 100644
--- a/src/styles/photos.css
+++ b/src/styles/photos.css
@@ -3,7 +3,7 @@
/* The screen fills the window as Notes does, so the sidebar's divider runs the full height
and only the library scrolls. */
-.content:has(> .screen-slot:not([hidden]) .px) { display: flex; flex-direction: column; overflow: hidden; padding-top: 18px; }
+.content[data-screen="photos"] { display: flex; flex-direction: column; overflow: hidden; padding-top: 18px; }
.px {
/* An app's own words are not text to select, as in Photos; a field still takes typing. */
@@ -224,6 +224,22 @@
}
/* 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); }
+/* A month not built yet: as tall as its rows of square tiles will be — its count over the
+ columns, rounded up — with its tiles painted on as boxes. Sized by its own width alone (no
+ container query: WebKit let a kept screen's scroll go when one was measured on coming back).
+ The block inside is the grid's width plus one gap, so each column and its gap is a square of
+ it, and its proportion is simply columns to rows; the extra gap below is taken back by a
+ negative margin. Each square is painted as a box with the gap left clear. */
+.px-later { --gap: 2px; --pad: 0px; --rows: round(up, var(--n) / var(--across, 7), 1); padding: 0 var(--pad); display: flow-root; }
+.px-later-in {
+ display: block;
+ margin-right: calc(-1 * var(--gap));
+ margin-bottom: calc(-1 * var(--gap));
+ aspect-ratio: var(--across, 7) / var(--rows);
+ background: conic-gradient(at calc(100% - var(--gap)) calc(100% - var(--gap)), transparent 75%, color-mix(in srgb, var(--text) 7%, transparent) 0)
+ 0 0 / calc(100% / var(--across, 7)) calc(100% / var(--rows));
+}
+.px-scroll[data-fit] .px-later { --gap: 14px; --pad: 14px; }
.px-month-title {
margin: 0;
padding: 12px 16px 8px;
diff --git a/src/styles/reminders.css b/src/styles/reminders.css
index eebdb44..a369363 100644
--- a/src/styles/reminders.css
+++ b/src/styles/reminders.css
@@ -29,7 +29,7 @@
--sys-orange: #ff9230;
}
-.content:has(> .screen-slot:not([hidden]) .rx) { display: flex; flex-direction: column; overflow: hidden; }
+.content[data-screen="reminders"] { display: flex; flex-direction: column; overflow: hidden; }
.rx {
flex: 1;
@@ -457,7 +457,9 @@
.rx-trailing { display: flex; align-items: center; gap: 2px; padding-top: 1px; }
.rx-trailing .rx-icon-button { opacity: 0; }
.rx-row:hover .rx-icon-button,
-.rx-row:focus-within .rx-icon-button,
+/* Moved to with the keys, not merely holding the focus a click left behind: with that, the
+ row's info and flag stayed showing as though it were still pointed at. */
+.rx-row:has(:focus-visible) .rx-icon-button,
.rx-row.is-open .rx-icon-button,
.rx-icon-button.rx-flag.on { opacity: 1; }
.rx-icon-button.rx-flag.on { color: var(--sys-orange); }