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
The calendar stops guessing what Apple already tells it
Yashwanth Kamireddi68f3ed7e8e11
diff --git a/.uiverify/assert.mjs b/.uiverify/assert.mjsindex adab303..c96f6a1 100644--- a/.uiverify/assert.mjs+++ b/.uiverify/assert.mjs@@ -21,7 +21,15 @@ await ctx.addInitScript(({ services }) => {if (cmd === "auth_resume") return true;if (cmd === "account_services") return services;if (cmd === "calendar_events") return [];- if (cmd === "calendar_list") return [];+ if (cmd === "calendar_list")+ return [+ { guid: "work", title: "Work", colour: null, ctag: null, sortOrder: 0, enabled: true,+ writable: true, isDefault: false },+ { guid: "home", title: "Home", colour: null, ctag: null, sortOrder: 1, enabled: true,+ writable: true, isDefault: true },+ { guid: "holidays", title: "Holidays in India", colour: null, ctag: null, sortOrder: 2,+ enabled: true, writable: false, isDefault: false },+ ];if (cmd === "event_save") return "E-new";if (cmd === "event_delete") return null;if (cmd === "calendar_sync") return { calendars: 0, events: 0 };@@ -264,6 +272,40 @@ let failures = 0;await page.close();}+// ── A new event goes where Apple says, not where the list happens to start ────────────+// Apple names the default calendar outright. Taking the first of the list instead is the same+// mistake that put every new reminder in whichever list sorted first — and the first calendar+// can also be a subscribed feed that nothing may be written to.+{+ const page = await ctx.newPage();+ await page.goto("http://localhost:4173", { waitUntil: "networkidle" });+ await page.getByRole("button", { name: "Calendar", exact: true }).click();+ await page.waitForTimeout(300);+ await page.getByRole("button", { name: "New event" }).click();+ await page.waitForTimeout(250);++ const chosen = await page.locator(".cal-field .picker-button").first().innerText();+ const right = chosen.includes("Home");+ console.log(+ right+ ? `PASS a new event starts in the default calendar [${chosen.split("\n")[0]}]`+ : `FAIL a new event started in "${chosen.split("\n")[0]}" rather than the default`+ );+ if (!right) failures++;++ await page.locator(".cal-field .picker-button").first().click();+ await page.waitForTimeout(200);+ const offered = await page.locator('[role="option"], .picker-option').allInnerTexts();+ const readOnlyOffered = offered.some((o) => o.includes("Holidays"));+ console.log(+ readOnlyOffered+ ? `FAIL a read-only calendar is offered to put an event in [${offered.join(", ")}]`+ : `PASS a read-only calendar is not somewhere to put an event [${offered.join(", ")}]`+ );+ if (readOnlyOffered) failures++;+ await page.close();+}+// ── An account with nothing in it ─────────────────────────────────────────────────────// Everything above was measured against one real library: nine lists, folders, a Drive with// things in it. A person installing this may have none of that — a new Apple ID, or one whosediff --git a/.uiverify/shots.mjs b/.uiverify/shots.mjsindex e622f98..b1eefd9 100644--- a/.uiverify/shots.mjs+++ b/.uiverify/shots.mjs@@ -108,10 +108,17 @@ function installStub({ screen, services, twoFactor, calendarFixture, notesFixtur{ guid: "r4", listGuid: "l1", title: "Water the plants", notes: null,dueAt: base - DAY, completedAt: base - DAY, priority: 0, flagged: false, parentGuid: null, etag: null },];+ // Shaped like a real account rather than a tidy one: the default is not the first, and one+ // of them is a subscribed feed that nothing may be written to.const calendars = [- { guid: "work", title: "Work", colour: "#cc73e1", ctag: null, sortOrder: 0, enabled: true },- { guid: "home", title: "Home", colour: "#0088ff", ctag: null, sortOrder: 1, enabled: true },- { guid: "personal", title: "Asha", colour: "#1badf8", ctag: null, sortOrder: 2, enabled: true },+ { guid: "work", title: "Work", colour: "#cc73e1", ctag: null, sortOrder: 0, enabled: true,+ writable: true, isDefault: false },+ { guid: "home", title: "Home", colour: "#0088ff", ctag: null, sortOrder: 1, enabled: true,+ writable: true, isDefault: true },+ { guid: "personal", title: "Asha", colour: "#1badf8", ctag: null, sortOrder: 2, enabled: true,+ writable: true, isDefault: false },+ { guid: "holidays", title: "Holidays in India", colour: "#8e8e93", ctag: null, sortOrder: 3,+ enabled: true, writable: false, isDefault: false },];window.__TAURI_INTERNALS__ = {transformCallback: (cb) => cb,diff --git a/crates/quince-core/src/calendar.rs b/crates/quince-core/src/calendar.rsindex d442c17..dfe9f28 100644--- a/crates/quince-core/src/calendar.rs+++ b/crates/quince-core/src/calendar.rs@@ -17,6 +17,17 @@ pub struct Calendar {pub ctag: Option<String>,pub sort_order: i64,pub enabled: bool,+ /// False for a subscribed feed or a calendar shared for reading only. Nothing may be+ /// written to one, so nothing should offer to.+ #[serde(default = "yes")]+ pub writable: bool,+ /// The one Apple puts a new event in. Named outright rather than guessed at.+ #[serde(default)]+ pub is_default: bool,+}++const fn yes() -> bool {+ true}#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]@@ -51,14 +62,17 @@ impl Library {let tx = self.conn.transaction()?;{let mut stmt = tx.prepare(- "INSERT INTO calendars (guid, title, colour, ctag, sort_order, enabled, updated_at)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)+ "INSERT INTO calendars (guid, title, colour, ctag, sort_order, enabled,+ writable, is_default, updated_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)ON CONFLICT(guid) DO UPDATE SETtitle = excluded.title,colour = excluded.colour,ctag = excluded.ctag,sort_order = excluded.sort_order,enabled = excluded.enabled,+ writable = excluded.writable,+ is_default = excluded.is_default,updated_at = excluded.updated_at",)?;let stamp = now();@@ -70,6 +84,8 @@ impl Library {c.ctag,c.sort_order,i64::from(c.enabled),+ i64::from(c.writable),+ i64::from(c.is_default),stamp])?;}@@ -135,7 +151,7 @@ impl Library {pub fn calendars(&self) -> Result<Vec<Calendar>> {let mut stmt = self.conn.prepare(- "SELECT guid, title, colour, ctag, sort_order, enabled+ "SELECT guid, title, colour, ctag, sort_order, enabled, writable, is_defaultFROM calendars ORDER BY sort_order, title",)?;let rows = stmt.query_map([], |row| {@@ -146,6 +162,8 @@ impl Library {ctag: row.get(3)?,sort_order: row.get(4)?,enabled: row.get::<_, i64>(5)? != 0,+ writable: row.get::<_, i64>(6)? != 0,+ is_default: row.get::<_, i64>(7)? != 0,})})?;Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)@@ -261,6 +279,8 @@ mod tests {ctag: Some("ctag-1".into()),sort_order: 0,enabled: true,+ writable: true,+ is_default: false,}}diff --git a/crates/quince-core/src/schema.rs b/crates/quince-core/src/schema.rsindex f47d5c4..51a3666 100644--- a/crates/quince-core/src/schema.rs+++ b/crates/quince-core/src/schema.rs@@ -232,4 +232,16 @@ pub const MIGRATIONS: &[&str] = &[r#"ALTER TABLE contacts ADD COLUMN photo_crop TEXT;"#,+ // 15 — what Apple says about each calendar.+ //+ // A subscribed calendar — a holiday feed, a sports fixture list — and a calendar shared+ // with you for reading only both come back with readOnly set. Offering to put an event in+ // one produces a refusal that reads as a bug in this app rather than as the truth.+ //+ // And Apple names the default calendar outright. Picking the first of the list instead is+ // the same mistake that put every new reminder in whichever list happened to sort first.+ r#"+ ALTER TABLE calendars ADD COLUMN writable INTEGER NOT NULL DEFAULT 1;+ ALTER TABLE calendars ADD COLUMN is_default INTEGER NOT NULL DEFAULT 0;+ "#,];diff --git a/crates/quince-icloud/src/calendar.rs b/crates/quince-icloud/src/calendar.rsindex 815cadd..24e4a03 100644--- a/crates/quince-icloud/src/calendar.rs+++ b/crates/quince-icloud/src/calendar.rs@@ -90,7 +90,19 @@ fn string(v: &Value, key: &str) -> Option<String> {}/// Turn one entry of Apple's `Collection` array into a calendar.+///+/// Not everything in that array is a calendar of events. Apple surfaces reminder lists through+/// the same endpoint and tells them apart with `supportedType`, so anything that does not hold+/// events is left out rather than shown as an empty calendar nobody can put anything in.fn collection_from(v: &Value) -> Option<Calendar> {+ // Absent means events — only the other kinds say what they are.+ let holds_events = v+ .get("supportedType")+ .and_then(Value::as_str)+ .is_none_or(|kind| kind.eq_ignore_ascii_case("Event"));+ if !holds_events {+ return None;+ }Some(Calendar {guid: string(v, "guid")?,title: string(v, "title").unwrap_or_else(|| "Untitled".into()),@@ -99,6 +111,13 @@ fn collection_from(v: &Value) -> Option<Calendar> {sort_order: v.get("order").and_then(Value::as_i64).unwrap_or(0),// Apple omits `enabled` for calendars that are on.enabled: v.get("enabled").and_then(Value::as_bool).unwrap_or(true),+ // A subscribed feed, or a calendar shared for reading only. Apple refuses a write to+ // one, and that refusal reads as a bug here unless nothing offered it in the first+ // place. Absent means writable, which is the common case.+ writable: !v.get("readOnly").and_then(Value::as_bool).unwrap_or(false),+ // Apple names the default outright. Taking the first of the list instead is the same+ // mistake that put every new reminder in whichever list happened to sort first.+ is_default: v.get("isDefault").and_then(Value::as_bool).unwrap_or(false),})}@@ -903,3 +922,87 @@ mod write_tests {assert!(message.contains("bad event"), "{message}");}}++/// Calendars this account does not have, but other people's do.+///+/// This account has four calendars, all writable, none subscribed. A subscribed holiday feed,+/// a calendar shared for reading only, and a reminder list surfaced through the same endpoint+/// are all ordinary things to have and none of them appear here to be learned from — so they+/// are checked against the shapes Apple documents in the fields it does send.+#[cfg(test)]+mod other_calendars_tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn a_subscribed_or_shared_calendar_is_kept_but_not_written_to() {+ let feed = collection_from(&json!({+ "guid": "holidays", "title": "Holidays in India", "readOnly": true,+ "supportedType": "Event"+ }))+ .unwrap();+ assert!(!feed.writable, "nothing may be put in a feed");+ assert_eq!(feed.title, "Holidays in India", "but it is still shown");+ }++ /// Absent means writable — most calendars never say so.+ #[test]+ fn a_calendar_that_says_nothing_is_writable() {+ let plain = collection_from(&json!({ "guid": "c1", "title": "Work" })).unwrap();+ assert!(plain.writable);+ assert!(!plain.is_default);+ assert!(plain.enabled);+ }++ /// Apple names the default outright, and it is not always the first.+ #[test]+ fn the_default_is_the_one_apple_says_it_is() {+ let collections = json!([+ { "guid": "a", "title": "Work", "order": 0 },+ { "guid": "b", "title": "Home", "order": 1, "isDefault": true },+ ]);+ let parsed: Vec<Calendar> = collections+ .as_array()+ .unwrap()+ .iter()+ .filter_map(collection_from)+ .collect();+ assert_eq!(parsed.iter().filter(|c| c.is_default).count(), 1);+ assert_eq!(parsed.iter().find(|c| c.is_default).unwrap().guid, "b");+ }++ /// Apple surfaces reminder lists through the calendar endpoint. Shown as calendars they+ /// are empty ones nobody can put an event in.+ #[test]+ fn a_collection_that_does_not_hold_events_is_not_a_calendar() {+ assert!(collection_from(&json!({+ "guid": "r1", "title": "Groceries", "supportedType": "Reminder"+ }))+ .is_none());+ assert!(collection_from(&json!({+ "guid": "c1", "title": "Work", "supportedType": "Event"+ }))+ .is_some());+ assert!(+ collection_from(&json!({ "guid": "c2", "title": "Work" })).is_some(),+ "saying nothing means events"+ );+ }++ /// An account with nothing but a subscribed feed has nowhere to put an event, and the+ /// interface has to be able to tell.+ #[test]+ fn an_account_of_only_feeds_offers_nowhere_to_write() {+ let parsed: Vec<Calendar> = json!([+ { "guid": "a", "title": "Holidays", "readOnly": true },+ { "guid": "b", "title": "Fixtures", "readOnly": true },+ ])+ .as_array()+ .unwrap()+ .iter()+ .filter_map(collection_from)+ .collect();+ assert_eq!(parsed.len(), 2);+ assert!(parsed.iter().all(|c| !c.writable));+ }+}diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex fd930ef..cb20994 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -129,8 +129,24 @@ export type Calendar = {ctag: string | null;sortOrder: number;enabled: boolean;+ /** False for a subscribed feed or a calendar shared for reading only. */+ writable: boolean;+ /** The one Apple puts a new event in. */+ isDefault: boolean;};+/**+ * Where a new event should go.+ *+ * Apple names the default calendar outright, so it is asked rather than guessed. Taking the+ * first of the list is the mistake that put every new reminder in whichever list happened to+ * sort first — and the first calendar can also be one nothing may be written to.+ */+export function defaultCalendar(calendars: Calendar[]): Calendar | null {+ const writable = calendars.filter((c) => c.writable);+ return writable.find((c) => c.isDefault) ?? writable[0] ?? null;+}+/** What the app sends to create or change an event. A guid means it already exists. */export type EventWrite = {guid: string | null;diff --git a/src/screens/CalendarView.tsx b/src/screens/CalendarView.tsxindex b1241f8..37353c5 100644--- a/src/screens/CalendarView.tsx+++ b/src/screens/CalendarView.tsx@@ -1,5 +1,12 @@import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";-import { api, messageOf, type Calendar, type CalendarEvent, type Reminder } from "../lib/ipc";+import {+ api,+ defaultCalendar,+ messageOf,+ type Calendar,+ type CalendarEvent,+ type Reminder,+} from "../lib/ipc";import { useSync } from "../lib/sync";import { Picker } from "../components/Picker";@@ -723,7 +730,7 @@ export function CalendarView() {// An account with no calendars has nowhere to put an event. The New// event button already knows that; clicking an empty hour has to know// it too, or it opens a form that cannot be saved.- const target = calendars[0]?.guid;+ const target = defaultCalendar(calendars)?.guid;if (!target) return;const startsAt = Math.floor(at.getTime() / 1000);setDraft({@@ -785,9 +792,9 @@ export function CalendarView() {</h2><buttonclassName="quiet"- disabled={busy || calendars.length === 0}+ disabled={busy || defaultCalendar(calendars) === null}onClick={() => {- const target = calendars[0]?.guid;+ const target = defaultCalendar(calendars)?.guid;if (target) setDraft(blankEvent(selected, target));}}>@@ -818,7 +825,12 @@ export function CalendarView() {label="Calendar"value={draft.calendarGuid}onChange={(guid) => setDraft({ ...draft, calendarGuid: guid })}- options={calendars.map((c) => ({ value: c.guid, label: c.title }))}+ /* A subscribed feed or a calendar shared for reading only cannot take an+ event, so it is not offered as somewhere to put one. The one the event is+ already in stays listed either way, or moving it would look impossible. */+ options={calendars+ .filter((c) => c.writable || c.guid === draft.calendarGuid)+ .map((c) => ({ value: c.guid, label: c.title }))}/></div><label>