Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
Calendar: make, rename, recolour and delete calendars; Go to Date. Drive: icloud.com's name rules
Yashwanth Kamireddide2c30e3ddaa
diff --git a/.uiverify/assert.mjs b/.uiverify/assert.mjsindex aa1a672..40144be 100644--- a/.uiverify/assert.mjs+++ b/.uiverify/assert.mjs@@ -346,7 +346,7 @@ let failures = 0;await page.waitForTimeout(400);const creates = await page.evaluate(() => window.__folderCreates ?? 0);const said = await page.locator(".drive .error, [role=alert]").allInnerTexts();- const refused = creates === 0 && said.some((t) => /already something called/.test(t));+ const refused = creates === 0 && said.some((t) => /already taken/.test(t));console.log(refused? "PASS a name already in the folder is refused, and says so"diff --git a/.uiverify/calendar-collections.mjs b/.uiverify/calendar-collections.mjsnew file mode 100644index 0000000..69ba68f--- /dev/null+++ b/.uiverify/calendar-collections.mjs@@ -0,0 +1,56 @@+// Calendars made, renamed, recoloured and deleted from the sidebar, as on icloud.com: + makes+// one; a name in use is refused with Apple's words; right-click renames, recolours, deletes;+// the default calendar offers no Delete.+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";+const b = await engine.launch();+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, calendarFixture: true });+const page = await ctx.newPage();+page.on("dialog", (d) => void d.accept());+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });+await openScreen(page, "Calendar");+await page.waitForTimeout(400);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };+const names = () => page.locator(".cx-cal-name").allInnerTexts();++await page.getByRole("button", { name: "New Calendar" }).click();+await page.getByLabel("New calendar name").fill("Trips");+await page.keyboard.press("Enter");+await page.waitForTimeout(400);+ok((await names()).includes("Trips"), "+ makes a calendar, named as typed");++await page.getByRole("button", { name: "New Calendar" }).click();+await page.getByLabel("New calendar name").fill("Work");+await page.keyboard.press("Enter");+await page.waitForTimeout(400);+const notice = await page.locator(".notice, [role=alert]").allInnerTexts();+ok(notice.some((t) => /already exists/.test(t)) && (await names()).filter((n) => n === "Work").length === 1, `a name already in use is refused, in Apple's words ${JSON.stringify(notice)}`);++const work = page.locator(".cx-cal", { hasText: "Work" });+await work.click({ button: "right" });+await page.getByRole("menuitem", { name: "Rename" }).click();+await page.getByLabel("Rename Work").fill("Office");+await page.keyboard.press("Enter");+await page.waitForTimeout(400);+ok((await names()).includes("Office") && !(await names()).includes("Work"), "Rename renames it in place");++await page.locator(".cx-cal", { hasText: "Office" }).click({ button: "right" });+await page.getByRole("menuitem", { name: "Colour" }).hover();+await page.getByRole("menuitem", { name: "Brown" }).click();+await page.waitForTimeout(300);+const writes = await page.evaluate(() => window.__calWrites);+ok(writes.some((w) => w.update?.colour === "#a2845e"), `Colour sets Apple's brown ${JSON.stringify(writes.at(-1))}`);++await page.locator(".cx-cal", { hasText: "Home" }).click({ button: "right" });+const homeMenu = await page.getByRole("menuitem").allInnerTexts();+ok(!homeMenu.some((t) => /Delete/.test(t)), `the default calendar offers no Delete ${JSON.stringify(homeMenu)}`);+await page.keyboard.press("Escape");++await page.locator(".cx-cal", { hasText: "Trips" }).click({ button: "right" });+await page.getByRole("menuitem", { name: /Delete Calendar/ }).click();+await page.waitForTimeout(400);+ok(!(await names()).includes("Trips"), "Delete Calendar…, once confirmed, removes it");+await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/calendar-goto.mjs b/.uiverify/calendar-goto.mjsnew file mode 100644index 0000000..152f773--- /dev/null+++ b/.uiverify/calendar-goto.mjs@@ -0,0 +1,30 @@+// Go to Date…, as in Calendar's View menu: Shift-Ctrl-T opens a date field, Return goes there,+// Escape closes it without moving.+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";+const b = await engine.launch();+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, calendarFixture: true });+const page = await ctx.newPage();+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });+await openScreen(page, "Calendar");+await page.waitForTimeout(400);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };+const title = () => page.locator(".cx-title").innerText();+const before = await title();++await page.keyboard.press("Shift+Control+T");+const field = page.getByRole("dialog", { name: "Go to Date" }).getByLabel("Date");+ok((await field.count()) === 1, "Shift-Ctrl-T opens Go to Date");+await page.keyboard.press("Escape");+ok((await field.count()) === 0 && (await title()) === before, "Escape closes it without moving");++await page.keyboard.press("Shift+Control+T");+await field.fill("2031-02-14");+await page.keyboard.press("Enter");+await page.waitForTimeout(200);+const after = await title();+ok((await field.count()) === 0 && /February/.test(after) && /2031/.test(after), `Return goes to that day ${before.replace(/\s+/g, " ")} → ${after.replace(/\s+/g, " ")}`);+await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/drive-names.mjs b/.uiverify/drive-names.mjsnew file mode 100644index 0000000..3f12345--- /dev/null+++ b/.uiverify/drive-names.mjs@@ -0,0 +1,46 @@+// Names iCloud Drive won't take are refused before anything is sent, in icloud.com's words:+// a leading dot (hidden), ":" or a line break, and a name already used in the folder.+import { engine } from "./engine.mjs";+import { SERVICES, installStub } from "./stub.mjs";+const b = await engine.launch();+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null,+ calendarFixture: false, notesFixture: false, contactsFixture: false, driveFixture: true, remindersFixture: false });+const page = await ctx.newPage();+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });+await page.locator(".nav-item", { hasText: "Drive" }).click();+await page.waitForTimeout(500);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };+const notice = () => page.locator(".notice").allInnerTexts();+const sent = () => page.evaluate(() => (window.__driveNames ?? []).length);++await page.getByRole("button", { name: "New Folder" }).click();+await page.keyboard.type(".hidden");+await page.keyboard.press("Enter");+await page.waitForTimeout(300);+ok((await notice()).some((t) => /shouldn.t begin with a .\..* \(dot\)/.test(t)) && (await sent()) === 0, `a folder named ".hidden" is refused, nothing sent ${JSON.stringify(await notice())}`);++await page.getByRole("button", { name: "New Folder" }).click();+await page.keyboard.type("downloads");+await page.keyboard.press("Enter");+await page.waitForTimeout(300);+ok((await notice()).some((t) => /already taken/.test(t)) && (await sent()) === 0, "a name already in the folder, in any case, is refused");++const row = page.locator(".drive-row-hit", { hasText: "Downloads" }).first();+await row.click({ button: "right" });+await page.getByRole("menuitem", { name: "Rename" }).click();+const field = page.getByLabel("Rename Downloads");+await field.fill("a:b");+await page.keyboard.press("Enter");+await page.waitForTimeout(300);+ok((await notice()).some((t) => /can.t be used/.test(t)) && (await sent()) === 0 && (await page.locator(".drive-name", { hasText: "Downloads" }).count()) > 0,+ "a rename to \"a:b\" is refused and the name stays");++await page.getByRole("button", { name: "New Folder" }).click();+await page.keyboard.type("Trips 2026");+await page.keyboard.press("Enter");+await page.waitForTimeout(300);+ok((await sent()) === 1, "an ordinary name still goes to iCloud");+await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjsindex dfb9a69..20a8fc5 100644--- a/.uiverify/stub.mjs+++ b/.uiverify/stub.mjs@@ -159,7 +159,26 @@ export function installStub({ screen, services, twoFactor, calendarFixture, notereturn events.filter((e) => words.every((w) => `${e.title} ${e.location ?? ""}`.toLowerCase().includes(w))).sort((a, b) => a.startsAt - b.startsAt);}- case "calendar_list": return calendars;+ case "calendar_list": return (window.__cals ??= calendars.map((c) => ({ ...c }))).map((c) => ({ ...c }));+ case "calendar_create": {+ const cals = (window.__cals ??= calendars.map((c) => ({ ...c })));+ if (cals.some((c) => c.title === args.title)) throw `A calendar with the name \u201c${args.title}\u201d already exists.`;+ (window.__calWrites ??= []).push({ create: args.title });+ cals.push({ guid: `cal-${cals.length + 1}`, title: args.title, colour: "#ff2d55", ctag: null, sortOrder: 9, enabled: true, writable: true, isDefault: false });+ return `cal-${cals.length}`;+ }+ case "calendar_update": {+ (window.__calWrites ??= []).push({ update: args });+ const c = (window.__cals ??= calendars.map((c) => ({ ...c }))).find((c) => c.guid === args.guid);+ if (c && args.title) c.title = args.title;+ if (c && args.colour) c.colour = args.colour;+ return null;+ }+ case "calendar_delete": {+ (window.__calWrites ??= []).push({ delete: args.guid });+ window.__cals = (window.__cals ?? calendars.map((c) => ({ ...c }))).filter((c) => c.guid !== args.guid);+ return null;+ }case "event_repeat": return String(args.guid).startsWith("SERIES__") ? { freq: "weekly", interval: 1, count: null } : null;case "event_alerts": return args.guid === "e2" ? [15] : [];case "event_save": (window.__eventSaves ??= []).push(args.draft); return "E-new";@@ -367,7 +386,8 @@ export function installStub({ screen, services, twoFactor, calendarFixture, notereturn driveItems.length;case "drive_download": return "/home/user/Downloads/file.pdf";case "drive_move": (window.__moves ??= []).push(args); await new Promise((r) => setTimeout(r, 600)); return null;- case "drive_create_folder": case "drive_rename": case "drive_delete": return null;+ case "drive_create_folder": case "drive_rename": (window.__driveNames ??= []).push(args); return null;+ case "drive_delete": return null;case "drive_item": return null;case "auth_two_factor_options": return twoFactor;case "auth_resend_code": return null;diff --git a/check.sh b/check.shindex 52ab7bd..a13bbca 100755--- a/check.sh+++ b/check.sh@@ -49,6 +49,9 @@ step "birthdays, holidays" node .uiverify/occasions.mjsstep "drive folders" node .uiverify/drive-nav.mjsstep "birthdays in contacts" node .uiverify/contact-birthday.mjsstep "contact labels" node .uiverify/contacts-labels.mjs+step "calendar go to date" node .uiverify/calendar-goto.mjs+step "calendar calendars" node .uiverify/calendar-collections.mjs+step "drive names" node .uiverify/drive-names.mjsstep "empty today" node .uiverify/reminders-empty.mjsstep "calendar keys" node .uiverify/calendar-keys.mjsstep "reminders instant" node .uiverify/reminders-instant.mjs@@ -80,6 +83,9 @@ step "reminder menu" node .uiverify/reminders-context.mjsstep "notes media" node .uiverify/notes-media.mjsstep "webkit: tables" env ENGINE=webkit node .uiverify/notes-table.mjsstep "webkit: labels" env ENGINE=webkit node .uiverify/contacts-labels.mjs+step "webkit: go to date" env ENGINE=webkit node .uiverify/calendar-goto.mjs+step "webkit: calendars" env ENGINE=webkit node .uiverify/calendar-collections.mjs+step "webkit: drive names" env ENGINE=webkit node .uiverify/drive-names.mjsstep "webkit: row hover" env ENGINE=webkit node .uiverify/row-hover.mjsstep "webkit: fold" env ENGINE=webkit node .uiverify/sidebar-fold.mjsstep "reminder colours" node .uiverify/calendar-reminder-colour.mjsdiff --git a/crates/quince-icloud/src/calendar.rs b/crates/quince-icloud/src/calendar.rsindex ec93abe..7f56e4b 100644--- a/crates/quince-icloud/src/calendar.rs+++ b/crates/quince-icloud/src/calendar.rs@@ -212,6 +212,64 @@ fn client_state(calendar_guid: &str, ctag: Option<&str>) -> Value {})}+/// Apple's calendar palette, in the order icloud.com offers it (calendar bundle `r2`).+pub const PALETTE: [(&str, &str); 7] = [+ ("#ff2d55", "red"),+ ("#ff9500", "orange"),+ ("#ffcc00", "yellow"),+ ("#65db39", "green"),+ ("#34aadc", "blue"),+ ("#cc73e1", "purple"),+ ("#a2845e", "brown"),+];++/// The first palette colour no calendar uses yet, as icloud.com picks one for a new+/// calendar; the first again when all seven are taken.+#[must_use]+pub fn next_colour(existing: &[Calendar]) -> (&'static str, &'static str) {+ let used: Vec<String> = existing+ .iter()+ .filter_map(|c| c.colour.as_deref())+ .map(|c| c.to_lowercase().chars().take(7).collect())+ .collect();+ PALETTE+ .iter()+ .find(|(hex, _)| !used.iter().any(|u| u == hex))+ .copied()+ .unwrap_or(PALETTE[0])+}++/// A colour's name in Apple's palette, or "custom" for any other.+#[must_use]+pub fn symbolic_of(colour: &str) -> &'static str {+ let c = colour.to_lowercase();+ PALETTE+ .iter()+ .find(|(hex, _)| c.starts_with(hex))+ .map_or("custom", |(_, name)| name)+}++/// The one collection with this guid in a `ca/collectiondetail` (or similar) answer.+fn collection_of(body: &Value, guid: &str) -> Option<Value> {+ let list = body.get("Collection")?;+ let found = match list {+ Value::Array(items) => items+ .iter()+ .find(|c| c.get("guid").and_then(Value::as_str) == Some(guid)),+ Value::Object(_) => {+ (list.get("guid").and_then(Value::as_str) == Some(guid)).then_some(list)+ }+ _ => None,+ };+ found.cloned()+}++fn now_seconds() -> i64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(0))+}+/// What to tell someone when Apple's calendar turns a request down.////// The screen showed what Apple sent — `/ca/events/work/4186… returned 404 Not Found:@@ -864,6 +922,189 @@ impl<'a> CalendarClient<'a> {Ok(changed_collections(&answer))}+ /// One calendar exactly as Apple holds it (`ca/collectiondetail`), etag and all, or+ /// `None` for one it has never heard of. Read-only.+ pub async fn collection_detail(&self, guid: &str) -> Result<Option<Value>> {+ let today = day_of(now_seconds(), None);+ match self+ .get(+ &format!("/ca/collectiondetail/{guid}"),+ &today,+ &today,+ "UTC",+ )+ .await+ {+ Ok(body) => Ok(collection_of(&body, guid)),+ Err(Error::NotFound) => Ok(None),+ Err(e) => Err(e),+ }+ }++ /// Make a calendar, as icloud.com's "New Calendar" does. The id is a fresh lowercase+ /// UUID, and the colour is the first of Apple's seven that no calendar uses yet.+ /// A title already in use is refused, as icloud.com refuses it, because two calendars+ /// with one name cannot be told apart anywhere. Answers the new calendar's guid once+ /// Apple's own record shows it.+ pub async fn create_calendar(&self, title: &str, existing: &[Calendar]) -> Result<String> {+ let title = title.trim();+ if title.is_empty() {+ return Err(Error::Refused("A calendar needs a name.".into()));+ }+ if existing.iter().any(|c| c.title.trim() == title) {+ return Err(Error::Refused(format!(+ "A calendar with the name \u{201c}{title}\u{201d} already exists."+ )));+ }+ let (color, symbolic) = next_colour(existing);+ let guid = uuid::Uuid::new_v4().to_string();+ let order = existing.iter().map(|c| c.sort_order).max().unwrap_or(0) + 1;+ let collection = serde_json::json!({+ "guid": guid, "title": title, "color": color, "symbolicColor": symbolic,+ "order": order, "visible": true, "shareTitle": "", "supportedType": "Event",+ "objectType": "personal", "extendedDetailsAreIncluded": false, "readOnly": false,+ });+ self.save_collection(&guid, collection, None, None).await?;+ match self.collection_detail(&guid).await? {+ Some(_) => Ok(guid),+ None => Err(Error::Refused(+ "iCloud took the new calendar but does not show it, so nothing is assumed made."+ .into(),+ )),+ }+ }++ /// Rename or recolour a calendar: Apple's own record of it, with only what changed set,+ /// sent with its etag, so a change made elsewhere meanwhile is refused rather than overwritten.+ pub async fn update_calendar(+ &self,+ guid: &str,+ title: Option<&str>,+ colour: Option<&str>,+ existing: &[Calendar],+ ) -> Result<()> {+ let Some(mut collection) = self.collection_detail(guid).await? else {+ return Err(Error::NotFound);+ };+ if collection.get("readOnly").and_then(Value::as_bool) == Some(true) {+ return Err(Error::Refused(+ "That calendar can't be changed from here.".into(),+ ));+ }+ if let Some(title) = title.map(str::trim) {+ if title.is_empty() {+ return Err(Error::Refused("A calendar needs a name.".into()));+ }+ if existing+ .iter()+ .any(|c| c.guid != guid && c.title.trim() == title)+ {+ return Err(Error::Refused(format!(+ "A calendar with the name \u{201c}{title}\u{201d} already exists."+ )));+ }+ collection["title"] = title.into();+ }+ if let Some(colour) = colour {+ collection["color"] = colour.into();+ collection["symbolicColor"] = symbolic_of(colour).into();+ }+ let etag = collection+ .get("etag")+ .and_then(Value::as_str)+ .map(str::to_string);+ let ctag = collection+ .get("ctag")+ .and_then(Value::as_str)+ .map(str::to_string);+ self.save_collection(+ guid,+ collection.clone(),+ Some("PUT"),+ etag.as_deref().zip(Some(ctag.as_deref())),+ )+ .await?;+ let after = self.collection_detail(guid).await?.ok_or(Error::NotFound)?;+ let took = title+ .is_none_or(|t| after.get("title").and_then(Value::as_str) == Some(t.trim()))+ && colour.is_none_or(|c| {+ after+ .get("color")+ .and_then(Value::as_str)+ .map(str::to_lowercase)+ == Some(c.to_lowercase())+ });+ if took {+ Ok(())+ } else {+ Err(Error::Refused("iCloud did not keep that change.".into()))+ }+ }++ /// Delete a calendar and every event in it, as icloud.com does. The default calendar and+ /// one shared to this account are refused here; Apple would refuse them in any case.+ pub async fn delete_calendar(&self, calendar: &Calendar) -> Result<()> {+ if calendar.is_default {+ return Err(Error::Refused(+ "This is the calendar new events go in. Choose another default on an Apple device first.".into(),+ ));+ }+ if !calendar.writable {+ return Err(Error::Refused(+ "That calendar can't be deleted from here.".into(),+ ));+ }+ let today = day_of(now_seconds(), None);+ match self+ .post(+ &format!("/ca/collections/{}", calendar.guid),+ &serde_json::json!({}),+ &today,+ &today,+ None,+ Some("DELETE"),+ )+ .await+ {+ Ok(_) | Err(Error::NotFound) => {}+ Err(e) => return Err(e),+ }+ // Gone only once Apple's own record says so.+ match self.collection_detail(&calendar.guid).await? {+ None => Ok(()),+ Some(_) => Err(Error::Refused("iCloud still has that calendar.".into())),+ }+ }++ async fn save_collection(+ &self,+ guid: &str,+ collection: Value,+ method: Option<&str>,+ tags: Option<(&str, Option<&str>)>,+ ) -> Result<Value> {+ let today = day_of(now_seconds(), None);+ let body = serde_json::json!({+ "Collection": collection,+ "ClientState": { "Collection": [{ "guid": guid, "ctag": tags.and_then(|t| t.1) }], "fullState": false },+ });+ // icloud.com sends the etag as `ifMatch`, beside methodOverride, in the query.+ let extra: Vec<(&str, &str)> = tags+ .map(|(etag, _)| ("ifMatch", etag))+ .into_iter()+ .collect();+ self.post_with(+ &format!("/ca/collections/{guid}"),+ &body,+ &today,+ &today,+ None,+ method,+ &extra,+ )+ .await+ }+async fn post(&self,path: &str,@@ -872,8 +1113,28 @@ impl<'a> CalendarClient<'a> {to: &str,tz: Option<&str>,method_override: Option<&str>,+ ) -> Result<Value> {+ self.post_with(path, body, from, to, tz, method_override, &[])+ .await+ }++ #[allow(clippy::too_many_arguments)]+ async fn post_with(+ &self,+ path: &str,+ body: &Value,+ from: &str,+ to: &str,+ tz: Option<&str>,+ method_override: Option<&str>,+ extra: &[(&str, &str)],) -> Result<Value> {let mut query = self.params.clone();+ query.extend(+ extra+ .iter()+ .map(|(k, v)| ((*k).to_string(), (*v).to_string())),+ );query.push(("clientVersion".into(), "5.1".into()));query.push(("requestID".into(), "4".into()));query.push(("startDate".into(), from.into()));@@ -973,6 +1234,32 @@ mod tests {use super::*;use serde_json::json;+ fn coloured(colour: &str) -> Calendar {+ Calendar {+ guid: colour.into(),+ title: colour.into(),+ colour: Some(colour.into()),+ ctag: None,+ sort_order: 0,+ enabled: true,+ writable: true,+ is_default: false,+ }+ }++ /// A new calendar takes the first of Apple's colours no calendar has, as icloud.com does,+ /// matching Apple's colours whatever their case or alpha; and red again when all are used.+ #[test]+ fn a_new_calendar_takes_the_first_unused_colour() {+ assert_eq!(next_colour(&[]), ("#ff2d55", "red"));+ let some = [coloured("#FF2D55FF"), coloured("#ff9500")];+ assert_eq!(next_colour(&some), ("#ffcc00", "yellow"));+ let all: Vec<Calendar> = PALETTE.iter().map(|(hex, _)| coloured(hex)).collect();+ assert_eq!(next_colour(&all), ("#ff2d55", "red"));+ assert_eq!(symbolic_of("#34AADC"), "blue");+ assert_eq!(symbolic_of("#123456"), "custom");+ }+/// The shapes `/ca/idle` was measured answering with: nothing, a calendar it was not told/// of, a calendar whose tag moved; and a calendar gone.#[test]diff --git a/crates/quince-icloud/src/drive.rs b/crates/quince-icloud/src/drive.rsindex 61c5bac..5535a06 100644--- a/crates/quince-icloud/src/drive.rs+++ b/crates/quince-icloud/src/drive.rs@@ -290,6 +290,27 @@ fn created_folder(body: &Value, name: &str) -> Result<DriveItem> {/// folder of 256 folders (a git repository's `objects`) is one round trip, not 256. Each name/// answers with its new folder's id, or why it was not made; the answer is matched by the/// `clientId` each was sent with.+/// A name iCloud Drive won't take, refused here in icloud.com's words: empty, hidden (a+/// leading dot, which a Mac would never show), or holding ":" or a line break.+pub fn unusable_name(name: &str) -> Result<()> {+ if name.is_empty() {+ return Err(Error::Refused(+ "A name can't be empty. Please choose a different name.".into(),+ ));+ }+ if name.starts_with('.') {+ return Err(Error::Refused(+ "A name shouldn\u{2019}t begin with a \u{201c}.\u{201d} (dot). Please choose a different name.".into(),+ ));+ }+ if name.contains([':', '\n', '\r']) {+ return Err(Error::Refused(format!(+ "The name \u{201c}{name}\u{201d} can\u{2019}t be used. Try using a name with fewer characters, or with no punctuation marks."+ )));+ }+ Ok(())+}+pub async fn create_folders(http: &reqwest::Client,root: &str,@@ -355,9 +376,7 @@ pub async fn create_folder(name: &str,) -> Result<DriveItem> {let name = name.trim();- if name.is_empty() {- return Err(Error::Protocol("a folder needs a name".into()));- }+ unusable_name(name)?;let url = format!("{}/createFolders", root.trim_end_matches('/'));let body = json!({@@ -440,9 +459,7 @@ pub async fn rename(name: &str,) -> Result<()> {let name = name.trim();- if name.is_empty() {- return Err(Error::Protocol("a name can't be empty".into()));- }+ unusable_name(name)?;let parent = parent_of(item);let current = folder_listing(http, root, ¶ms, parent).await?;@@ -1193,6 +1210,17 @@ mod created_folder_tests {mod tests {use super::*;+ /// Names icloud.com refuses are refused here too, before anything is sent.+ #[test]+ fn hidden_empty_and_colon_names_are_refused() {+ assert!(unusable_name("").is_err());+ assert!(unusable_name(".env").is_err());+ assert!(unusable_name("a:b").is_err());+ assert!(unusable_name("two\nlines").is_err());+ assert!(unusable_name("Semester Plan.pdf").is_ok());+ assert!(unusable_name("v1.2 notes").is_ok());+ }+fn response() -> Value {json!([{"drivewsid": "FOLDER::com.apple.CloudDocs::root",diff --git a/probe/examples/calendar_collection_roundtrip.rs b/probe/examples/calendar_collection_roundtrip.rsnew file mode 100644index 0000000..fbc192b--- /dev/null+++ b/probe/examples/calendar_collection_roundtrip.rs@@ -0,0 +1,107 @@+//! Live: a throwaway calendar made, renamed, recoloured and deleted, each step checked against+//! Apple's own record. Only the calendar this makes is ever written to; one of his calendars is+//! only read, to see the shape `ca/collectiondetail` answers with.+use anyhow::{anyhow, Result};+use quince_icloud::calendar::CalendarClient;++#[tokio::main]+async fn main() -> Result<()> {+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");+ let mut client = quince_auth::Client::new(&dir)?;+ if !client.resume().await? {+ return Err(anyhow!("no session"));+ }+ let root = client+ .session()+ .service_url("calendar")+ .ok_or_else(|| anyhow!("no calendar service"))?;+ let http = client.http().clone();+ let cal = CalendarClient::new(&http, &root, client.service_params());+ let snap = cal.startup("2026-10-01", "2026-10-31", "UTC").await?;+ let mine = snap.calendars.clone();+ println!(+ "{} calendars: {:?}",+ mine.len(),+ mine.iter()+ .map(|c| (&c.title, &c.colour))+ .collect::<Vec<_>>()+ );++ // Read-only: the shape of one of his.+ if let Some(c) = mine.iter().find(|c| c.writable) {+ let detail = cal.collection_detail(&c.guid).await?;+ let keys: Vec<String> = detail+ .as_ref()+ .and_then(|d| d.as_object())+ .map(|o| o.keys().cloned().collect())+ .unwrap_or_default();+ println!("collectiondetail keys of {:?}: {keys:?}", c.title);+ println!(+ " etag present: {}",+ detail.as_ref().is_some_and(|d| d.get("etag").is_some())+ );+ }++ // The throwaway, made, changed and removed.+ let name = "Quince calendar test";+ if let Some(left) = mine.iter().find(|c| c.title.starts_with(name)) {+ println!("a test calendar was left from before; removing it first");+ cal.delete_calendar(left).await?;+ }+ let guid = cal.create_calendar(name, &mine).await?;+ let made = cal+ .collection_detail(&guid)+ .await?+ .ok_or_else(|| anyhow!("not made"))?;+ println!(+ "made {guid}: title {:?} color {:?}",+ made["title"], made["color"]+ );+ let dup = cal+ .create_calendar(+ name,+ &cal.startup("2026-10-01", "2026-10-31", "UTC")+ .await?+ .calendars,+ )+ .await;+ println!("same name again refused: {}", dup.is_err());++ let now = cal+ .startup("2026-10-01", "2026-10-31", "UTC")+ .await?+ .calendars;+ cal.update_calendar(&guid, Some("Quince calendar test renamed"), None, &now)+ .await?;+ println!(+ "renamed: {:?}",+ cal.collection_detail(&guid)+ .await?+ .map(|c| c["title"].clone())+ );+ cal.update_calendar(&guid, None, Some("#a2845e"), &now)+ .await?;+ println!(+ "recoloured: {:?}",+ cal.collection_detail(&guid)+ .await?+ .map(|c| (c["color"].clone(), c["symbolicColor"].clone()))+ );++ let made_cal = cal+ .startup("2026-10-01", "2026-10-31", "UTC")+ .await?+ .calendars+ .into_iter()+ .find(|c| c.guid == guid)+ .ok_or_else(|| anyhow!("not listed"))?;+ cal.delete_calendar(&made_cal).await?;+ let still = cal+ .startup("2026-10-01", "2026-10-31", "UTC")+ .await?+ .calendars+ .iter()+ .any(|c| c.guid == guid);+ println!("deleted; still listed: {still}");+ Ok(())+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex c289f77..811199f 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -960,6 +960,93 @@ fn spawn_holidays(app: tauri::AppHandle) {});}+/// After a calendar was made, changed or removed: Apple's own list of calendars, kept here,+/// so the sidebar shows what iCloud now holds rather than what was asked for.+async fn calendars_from_apple(+ client: &quince_icloud::calendar::CalendarClient<'_>,+ data: &Data,+) -> UiResult<()> {+ let today = jiff::Zoned::now().date().to_string();+ let snap = client+ .startup(&today, &today, "UTC")+ .await+ .map_err(|e| e.to_string())?;+ if snap.calendars.is_empty() {+ // An empty answer is never taken as "every calendar is gone".+ return Ok(());+ }+ data.0+ .lock()+ .await+ .put_calendars(&snap.calendars)+ .map_err(|e| e.to_string())+}++/// New Calendar, as on icloud.com: Apple's next unused colour, a name no other calendar has.+#[tauri::command]+async fn calendar_create(+ title: String,+ auth: State<'_, Auth>,+ data: State<'_, Data>,+) -> UiResult<String> {+ let _one = CALENDAR_PASS.lock().await;+ let (http, root, params) = calendar_context(&auth).await?;+ let client = quince_icloud::calendar::CalendarClient::new(&http, &root, params);+ let existing = data.0.lock().await.calendars().map_err(|e| e.to_string())?;+ let guid = client+ .create_calendar(&title, &existing)+ .await+ .map_err(|e| e.to_string())?;+ calendars_from_apple(&client, &data).await?;+ Ok(guid)+}++/// Rename or recolour a calendar.+#[tauri::command]+async fn calendar_update(+ guid: String,+ title: Option<String>,+ colour: Option<String>,+ auth: State<'_, Auth>,+ data: State<'_, Data>,+) -> UiResult<()> {+ let _one = CALENDAR_PASS.lock().await;+ let (http, root, params) = calendar_context(&auth).await?;+ let client = quince_icloud::calendar::CalendarClient::new(&http, &root, params);+ let existing = data.0.lock().await.calendars().map_err(|e| e.to_string())?;+ client+ .update_calendar(&guid, title.as_deref(), colour.as_deref(), &existing)+ .await+ .map_err(|e| e.to_string())?;+ calendars_from_apple(&client, &data).await+}++/// Delete a calendar and its events, once the person has confirmed it in the window.+#[tauri::command]+async fn calendar_delete(+ guid: String,+ auth: State<'_, Auth>,+ data: State<'_, Data>,+) -> UiResult<()> {+ let _one = CALENDAR_PASS.lock().await;+ let (http, root, params) = calendar_context(&auth).await?;+ let client = quince_icloud::calendar::CalendarClient::new(&http, &root, params);+ let calendar = data+ .0+ .lock()+ .await+ .calendars()+ .map_err(|e| e.to_string())?+ .into_iter()+ .find(|c| c.guid == guid)+ .ok_or("That calendar is no longer here.")?;+ client+ .delete_calendar(&calendar)+ .await+ .map_err(|e| e.to_string())?;+ calendars_from_apple(&client, &data).await+}+#[tauri::command]async fn calendar_list(data: State<'_, Data>,@@ -3496,6 +3583,9 @@ fn main() {event_alerts,event_repeat,event_delete,+ calendar_create,+ calendar_update,+ calendar_delete,calendar_list,calendar_search,reminder_lists,diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex 63757da..f7919e2 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -86,6 +86,11 @@ export const api = {calendarEvents: (from: number, to: number) =>invoke<CalendarEvent[]>("calendar_events", { from, to }),calendarList: () => invoke<Calendar[]>("calendar_list"),+ /** New Calendar: Apple's next unused colour; a name already in use is refused. */+ calendarCreate: (title: string) => invoke<string>("calendar_create", { title }),+ calendarUpdate: (guid: string, change: { title?: string; colour?: string }) =>+ invoke<void>("calendar_update", { guid, title: change.title ?? null, colour: change.colour ?? null }),+ calendarDelete: (guid: string) => invoke<void>("calendar_delete", { guid }),reminderCounts: (until: number) => invoke<ReminderCounts>("reminder_counts", { until }),reminderLists: () => invoke<ReminderList[]>("reminder_lists"),diff --git a/src/screens/DriveView.tsx b/src/screens/DriveView.tsxindex 34b8951..3ae0b6b 100644--- a/src/screens/DriveView.tsx+++ b/src/screens/DriveView.tsx@@ -396,6 +396,23 @@ function daysLeft(expiresAt: number | null): number | null {if (expiresAt === null) return null;return Math.max(0, Math.ceil((expiresAt * 1000 - Date.now()) / 86_400_000));}+/**+ * Why a name can't be used, in icloud.com's own words (iclouddrive bundle, createFolder chunk),+ * or null: not empty, not hidden (a leading dot), no ":" or line break, and not already taken+ * in this folder, whatever the case.+ */+export function nameProblem(full: string, isFile: boolean, siblings: DriveItem[], self?: DriveItem): string | null {+ const kind = isFile ? "file" : "folder";+ if (!full.trim()) return `The name \u201c${full}\u201d is invalid. Please choose a different name.`;+ if (full.startsWith(".")) return `The name of your ${kind} shouldn\u2019t begin with a \u201c.\u201d (dot). Please choose a different name.`;+ if (/[:\n\r]/.test(full)) {+ return `The name \u201c${full}\u201d can\u2019t be used. Try using a name with fewer characters, or with no punctuation marks.`;+ }+ const lower = full.toLocaleLowerCase();+ const taken = siblings.some((i) => i !== self && i.drivewsid !== self?.drivewsid && driveName(i).toLocaleLowerCase() === lower);+ return taken ? `The name \u201c${full}\u201d is already taken. Please choose a different name.` : null;+}+/** "21 days", "1 day", "Today" — icloud.com's Time Left. */function timeLeft(expiresAt: number | null): string {const d = daysLeft(expiresAt);@@ -610,7 +627,12 @@ export function DriveView() {async (item: DriveItem, name: string) => {setRenaming(null);const trimmed = name.trim();- if (!trimmed || trimmed === driveName(item)) return;+ if (trimmed === driveName(item)) return;+ const problem = nameProblem(trimmed, item.kind === "FILE", items, item);+ if (problem) {+ setError(problem);+ return;+ }setBusyGuid(item.drivewsid);setError(null);// The new name shows the moment Return is pressed; Apple's answer confirms or undoes it.@@ -629,7 +651,7 @@ export function DriveView() {setBusyGuid(null);}},- [refresh]+ [refresh, items]);/**@@ -890,9 +912,10 @@ export function DriveView() {setCreatingFolder(false);setNewFolderName("");if (!name) return;- // Finder will not put two things of one name in a folder; neither will iCloud.- if (items.some((i) => i.name.toLocaleLowerCase() === name.toLocaleLowerCase())) {- setError(`There's already something called \u201c${name}\u201d here.`);+ // Finder will not put two things of one name in a folder, nor a hidden or unusable one; neither will iCloud.+ const problem = nameProblem(name, false, items);+ if (problem) {+ setError(problem);return;}folderPending.current = true;diff --git a/src/screens/calendar/CalendarView.tsx b/src/screens/calendar/CalendarView.tsxindex cea9d04..a7cb509 100644--- a/src/screens/calendar/CalendarView.tsx+++ b/src/screens/calendar/CalendarView.tsx@@ -14,6 +14,7 @@ import {type Reminder, type EventScope } from "../../lib/ipc";import { useSync } from "../../lib/sync";import { Picker } from "../../components/Picker";+import { RowMenu } from "../../components/RowMenu";import {addDays,clock,@@ -262,6 +263,9 @@ export function CalendarView() {},}), [ticked, listColours]);const [calendars, setCalendars] = useState<Calendar[]>([]);+ /** A calendar being named: "new" for New Calendar, or the guid of one being renamed. */+ 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));const [loaded, setLoaded] = useState(false);const [error, setError] = useState<string | null>(null);@@ -426,6 +430,24 @@ export function CalendarView() {[read, hold]);+ /** Calendars made, renamed, recoloured and removed — shown at once, put back if Apple refuses. */+ const createCalendar = (title: string) => {+ setNaming(null);+ if (title.trim()) void write(async () => { await api.calendarCreate(title.trim()); });+ };+ const updateCalendar = (c: Calendar, change: { title?: string; colour?: string }) => {+ setNaming(null);+ if (change.title !== undefined && (!change.title.trim() || change.title.trim() === c.title)) return;+ setCalendars((cs) => cs.map((x) => (x.guid === c.guid ? { ...x, ...change } : x)));+ void write(async () => { await api.calendarUpdate(c.guid, change); });+ };+ const deleteCalendar = (c: Calendar) => {+ // icloud.com's own warning: the events go with it, on every device.+ if (!window.confirm(`Delete \u201c${c.title}\u201d?\n\nAll events in this calendar will be deleted from every device.`)) return;+ setCalendars((cs) => cs.filter((x) => x.guid !== c.guid));+ void write(async () => { await api.calendarDelete(c.guid); });+ };+/*** One occurrence of a repeating event is changed only once the person has said it is for* that occurrence alone, as Calendar asks — sent as though it were an event, Apple took it@@ -587,6 +609,15 @@ export function CalendarView() {return new Date(d.getFullYear() + by, d.getMonth(), 1);});+ /** Go to Date…: a day typed in, shown in the view as it is. */+ const [goingTo, setGoingTo] = useState(false);+ const goTo = (value: string) => {+ const [y, m, d] = value.split("-").map(Number);+ if (!y || !m || !d) return;+ setSelected(new Date(y, m - 1, d));+ setGoingTo(false);+ };+// Keyboard, as in Calendar on a Mac (Ctrl here): arrows page, T today, 1–4 the views, N an event.useEffect(() => {const onKey = (e: KeyboardEvent) => {@@ -600,6 +631,12 @@ export function CalendarView() {if (typing || draft) return;const command = (e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey;const k = e.key.toLowerCase();+ // ⇧⌘T, Go to Date…, as in Calendar's View menu.+ if ((e.metaKey || e.ctrlKey) && e.shiftKey && !e.altKey && k === "t") {+ e.preventDefault();+ setGoingTo(true);+ return;+ }if (command && e.key === "ArrowLeft") shift(-1);else if (command && e.key === "ArrowRight") shift(1);// ⌘T, and the bare T this screen always had.@@ -688,18 +725,46 @@ export function CalendarView() {.filter((g) => g.list.length > 0).map((group) => (<Fragment key={group.heading}>- <p className="cx-side-heading">{group.heading}</p>- {group.list.map((c) => (- <label className="cx-cal" key={c.guid}>- <input- type="checkbox"- checked={!hidden.has(c.guid)}- onChange={() => toggleCalendar(c.guid)}- style={{ "--cal": tint(c) } as React.CSSProperties}- />- <span className="cx-cal-name">{c.title}</span>- </label>- ))}+ <p className="cx-side-heading">+ {group.heading}+ {group.heading === "iCloud" && (+ <button className="cx-side-add" aria-label="New Calendar" title="New Calendar" onClick={() => setNaming("new")}>+ ++ </button>+ )}+ </p>+ {group.list.map((c) =>+ naming === c.guid ? (+ <CalendarName key={c.guid} initial={c.title} label={`Rename ${c.title}`} onDone={(t) => updateCalendar(c, { title: t })} onCancel={() => setNaming(null)} />+ ) : (+ <label+ className="cx-cal"+ key={c.guid}+ onContextMenu={(e) => {+ // A calendar of this account can be renamed, recoloured or removed, as on icloud.com.+ if (!c.writable) return;+ e.preventDefault();+ setCalMenu({ cal: c, at: { x: e.clientX, y: e.clientY, alignRight: false } });+ }}+ onDoubleClick={(e) => {+ if (!c.writable) return;+ e.preventDefault();+ setNaming(c.guid);+ }}+ >+ <input+ type="checkbox"+ checked={!hidden.has(c.guid)}+ onChange={() => toggleCalendar(c.guid)}+ style={{ "--cal": tint(c) } as React.CSSProperties}+ />+ <span className="cx-cal-name">{c.title}</span>+ </label>+ ),+ )}+ {group.heading === "iCloud" && naming === "new" && (+ <CalendarName initial="Untitled" label="New calendar name" onDone={createCalendar} onCancel={() => setNaming(null)} />+ )}</Fragment>))}{loaded && calendars.length === 0 && (@@ -746,9 +811,38 @@ export function CalendarView() {<button className="cx-icon" aria-label="Previous" onClick={() => shift(-1)}>‹</button>- <button className="cx-today" onClick={() => setSelected(midnight(new Date()))}>+ <button className="cx-today" title="Today · Shift-Ctrl-T to go to a date" onClick={() => setSelected(midnight(new Date()))}>Today</button>+ {goingTo && (+ <form+ className="cx-goto"+ role="dialog"+ aria-label="Go to Date"+ onSubmit={(e) => {+ e.preventDefault();+ goTo(new FormData(e.currentTarget).get("day") as string);+ }}+ onKeyDown={(e) => {+ if (e.key === "Escape") {+ e.stopPropagation();+ setGoingTo(false);+ }+ }}+ onBlur={(e) => {+ if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setGoingTo(false);+ }}+ >+ <input+ name="day"+ type="date"+ aria-label="Date"+ autoFocus+ defaultValue={`${selected.getFullYear()}-${String(selected.getMonth() + 1).padStart(2, "0")}-${String(selected.getDate()).padStart(2, "0")}`}+ />+ <button type="submit">Go</button>+ </form>+ )}<button className="cx-icon" aria-label="Next" onClick={() => shift(1)}>›</button>@@ -800,6 +894,21 @@ export function CalendarView() {{error && (<Notice message={error} onDismiss={() => setError(null)} />)}+ {calMenu && (+ <RowMenu+ at={calMenu.at}+ onClose={() => setCalMenu(null)}+ entries={[+ { label: "Rename", run: () => setNaming(calMenu.cal.guid) },+ {+ label: "Colour",+ submenu: CALENDAR_COLOURS.map(([hex, name]) => ({ label: name, run: () => updateCalendar(calMenu.cal, { colour: hex }) })),+ },+ null,+ ...(calMenu.cal.isDefault ? [] : [{ label: "Delete Calendar\u2026", danger: true, run: () => deleteCalendar(calMenu.cal) }]),+ ]}+ />+ )}{view === "month" && (<MonthView@@ -2076,3 +2185,45 @@ function DayPane({</aside>);}++/** Apple's calendar colours, in icloud.com's order (calendar bundle `r2`). */+const CALENDAR_COLOURS: [string, string][] = [+ ["#ff2d55", "Red"],+ ["#ff9500", "Orange"],+ ["#ffcc00", "Yellow"],+ ["#65db39", "Green"],+ ["#34aadc", "Blue"],+ ["#cc73e1", "Purple"],+ ["#a2845e", "Brown"],+];++/** A calendar's name being typed: Return or leaving keeps it, Escape leaves it as it was. */+function CalendarName({ initial, label, onDone, onCancel }: {+ initial: string;+ label: string;+ onDone: (name: string) => void;+ onCancel: () => void;+}) {+ const settled = useRef(false);+ return (+ <input+ className="cx-cal-rename"+ defaultValue={initial}+ aria-label={label}+ autoFocus+ onFocus={(e) => e.currentTarget.select()}+ onBlur={(e) => {+ if (settled.current) return;+ settled.current = true;+ onDone(e.currentTarget.value);+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter") e.currentTarget.blur();+ if (e.key === "Escape") {+ settled.current = true;+ onCancel();+ }+ }}+ />+ );+}diff --git a/src/styles/calendar.css b/src/styles/calendar.cssindex c37e395..44944d9 100644--- a/src/styles/calendar.css+++ b/src/styles/calendar.css@@ -793,3 +793,37 @@.cx-step .cx-today:hover { background: color-mix(in srgb, var(--text) 8%, transparent); }.cx-tools > .cx-icon { min-width: 32px; padding: 0; color: var(--text); }.cx-search { padding: 0 12px; }++/* Go to Date… (⇧⌘T): a small date field under Today. Opaque and drawn at once, as the other+ popovers are, because a blurred or animated layer flickers in WebKitGTK. */+.cx-step { position: relative; }+.cx-goto {+ position: absolute;+ top: calc(100% + 6px);+ left: 50%;+ transform: translateX(-50%);+ z-index: 30;+ display: flex;+ gap: 6px;+ padding: 8px;+ border-radius: 12px;+ background: var(--glass-thick);+ box-shadow: var(--glass-specular), var(--glass-lift);+}+.cx-goto input { font: inherit; }+.cx-goto button { padding: 0 12px; border-radius: var(--r-pill); }++/* New Calendar: a quiet + at the end of the iCloud heading, as the Mac's sidebar has. */+.cx-side-heading { display: flex; align-items: center; justify-content: space-between; }+.cx-side-add {+ width: 20px; height: 20px; padding: 0; border: 0; border-radius: 6px;+ background: none; box-shadow: none; color: var(--text-2);+ font-size: 15px; line-height: 1; cursor: pointer;+}+.cx-side-add:hover { background: color-mix(in srgb, var(--text) 8%, transparent); color: var(--text); }+.cx-side-add:focus-visible { outline: 3px solid var(--accent-ring); }+/* A calendar's name being typed, in the row it will take. */+.cx-cal-rename {+ width: 100%; height: 26px; margin: 0; padding: 0 6px;+ border-radius: 6px; font: inherit; font-size: var(--t-13);+}