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.

Calendar alerts on the desktop: events of the next two days have their alerts read once and again only when changed, and each rings once at its moment — 'In 15 minutes · 4:30 PM' — as reminders' do

Yashwanth Kamireddi67f1ba7fcc74
diff --git a/crates/quince-core/src/alarms.rs b/crates/quince-core/src/alarms.rs
index 03d8695..45721b3 100644
--- a/crates/quince-core/src/alarms.rs
+++ b/crates/quince-core/src/alarms.rs
@@ -156,6 +156,15 @@ impl Library {
}
/// Remember that an alert has rung, so it never rings again. A snooze, once rung, is done.
+ /// Whether this alert, at this moment, has already had its one chance to ring.
+ pub fn alarm_already_fired(&self, key: &str, fires_at: i64) -> Result<bool> {
+ Ok(self.conn().query_row(
+ "SELECT EXISTS (SELECT 1 FROM alarm_fired WHERE alarm_id = ?1 AND fires_at = ?2)",
+ params![key, fires_at],
+ |r| r.get::<_, i64>(0),
+ )? != 0)
+ }
+
pub fn mark_alarm_fired(&mut self, key: &str, fires_at: i64, now: i64) -> Result<()> {
self.conn().execute(
"INSERT OR IGNORE INTO alarm_fired (alarm_id, fires_at, fired_at) VALUES (?1, ?2, ?3)",
@@ -343,4 +352,18 @@ mod tests {
lib.snooze_reminder("R", 8_200).unwrap();
assert_eq!(lib.due_alarms(9_000).unwrap().len(), 1);
}
+
+ /// A calendar alert, keyed by event and lead time, rings once at its moment — and again
+ /// only if the event moves and its moment with it.
+ #[test]
+ fn an_event_alert_is_recorded_once_per_moment() {
+ let mut lib = Library::in_memory().unwrap();
+ assert!(!lib.alarm_already_fired("event:E:15", 1_000).unwrap());
+ lib.mark_alarm_fired("event:E:15", 1_000, 1_000).unwrap();
+ assert!(lib.alarm_already_fired("event:E:15", 1_000).unwrap());
+ assert!(
+ !lib.alarm_already_fired("event:E:15", 4_600).unwrap(),
+ "moved, it rings at its new time"
+ );
+ }
}
diff --git a/probe/examples/calendar_startup_alarms.rs b/probe/examples/calendar_startup_alarms.rs
new file mode 100644
index 0000000..177ccf1
--- /dev/null
+++ b/probe/examples/calendar_startup_alarms.rs
@@ -0,0 +1,70 @@
+//! Live, read-only: does Calendar's startup/events answer carry each event's Alarm objects?
+use anyhow::{anyhow, Result};
+#[tokio::main]
+async fn main() -> Result<()> {
+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");
+ let mut client = quince_auth::Client::new(&dir)?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let root = client
+ .session()
+ .service_url("calendar")
+ .ok_or_else(|| anyhow!("no calendar"))?;
+ let mut q = client.service_params();
+ for (k, v) in [
+ ("clientVersion", "5.1"),
+ ("lang", "en-us"),
+ ("usertz", "Asia/Kolkata"),
+ ("startDate", "2026-10-01"),
+ ("endDate", "2026-10-31"),
+ ("requestID", "4"),
+ ] {
+ q.push((k.into(), v.into()));
+ }
+ for path in ["ca/startup", "ca/events"] {
+ let body: serde_json::Value = client
+ .http()
+ .get(format!("{}/{path}", root.trim_end_matches('/')))
+ .query(&q)
+ .send()
+ .await?
+ .json()
+ .await?;
+ let keys: Vec<_> = body
+ .as_object()
+ .map(|o| o.keys().cloned().collect())
+ .unwrap_or_default();
+ let alarms = body["Alarm"].as_array().map_or(0, Vec::len);
+ let with = body["Event"].as_array().map_or(0, |e| {
+ e.iter()
+ .filter(|e| e["alarms"].as_array().is_some_and(|a| !a.is_empty()))
+ .count()
+ });
+ println!("{path}: keys={keys:?} Alarm objects={alarms} events with alarms={with}");
+ if let Some(a) = body["Alarm"].as_array().and_then(|a| a.first()) {
+ println!(
+ " e.g. {}",
+ a.to_string().chars().take(300).collect::<String>()
+ );
+ }
+ }
+ let now = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)?
+ .as_millis() as u64;
+ let body = serde_json::json!({ "ClientState": { "Collection": [], "alarmRange": 60, "fullState": true, "userTime": now } });
+ let r = client
+ .http()
+ .post(format!("{}/ca/startup", root.trim_end_matches('/')))
+ .query(&q)
+ .json(&body)
+ .send()
+ .await?;
+ let st = r.status();
+ let t = r.text().await?;
+ println!(
+ "POST startup {st}: {}",
+ t.chars().take(600).collect::<String>()
+ );
+ Ok(())
+}
diff --git a/probe/examples/notes_format_roundtrip.rs b/probe/examples/notes_format_roundtrip.rs
index 9bcf9c5..6f88acb 100644
--- a/probe/examples/notes_format_roundtrip.rs
+++ b/probe/examples/notes_format_roundtrip.rs
@@ -7,26 +7,99 @@ use quince_icloud::ckdocument::{runs_from_base64, ParagraphChange};
async fn main() -> Result<()> {
let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");
let mut client = quince_auth::Client::new(&dir)?;
- if !client.resume().await? { return Err(anyhow!("no session")); }
- let root = client.session().service_url("ckdatabasews").ok_or_else(|| anyhow!("no ckdatabasews"))?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let root = client
+ .session()
+ .service_url("ckdatabasews")
+ .ok_or_else(|| anyhow!("no ckdatabasews"))?;
let (http, p) = (client.http().clone(), client.service_params());
let zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p.clone());
let body = "Quince format test\nBuy milk\nCall the bank";
- let guid = quince_icloud::notes::create_cloudkit(&http, &root, p.clone(), None, body, None).await?;
- let note = quince_core::notes::Note { guid: guid.clone(), folder_guid: None, title: "Quince format test".into(), snippet: None, body: None, locked: false, pinned: false, created_at: None, modified_at: None, editable: true, etag: None, runs: None };
+ let guid =
+ quince_icloud::notes::create_cloudkit(&http, &root, p.clone(), None, body, None).await?;
+ let note = quince_core::notes::Note {
+ guid: guid.clone(),
+ folder_guid: None,
+ title: "Quince format test".into(),
+ snippet: None,
+ body: None,
+ locked: false,
+ pinned: false,
+ created_at: None,
+ modified_at: None,
+ editable: true,
+ etag: None,
+ runs: None,
+ };
let show = |r: &serde_json::Value| {
- runs_from_base64(r["fields"]["TextDataEncrypted"]["value"].as_str().unwrap_or(""))
- .iter().map(|x| format!("{}:{:?}{}", x.length, x.style, x.checked.map(|c| if c { "✓" } else { "○" }).unwrap_or(""))).collect::<Vec<_>>().join(" ")
+ runs_from_base64(
+ r["fields"]["TextDataEncrypted"]["value"]
+ .as_str()
+ .unwrap_or(""),
+ )
+ .iter()
+ .map(|x| {
+ format!(
+ "{}:{:?}{}",
+ x.length,
+ x.style,
+ x.checked.map(|c| if c { "✓" } else { "○" }).unwrap_or("")
+ )
+ })
+ .collect::<Vec<_>>()
+ .join(" ")
};
- println!("made: {}", show(&zc.lookup_record("Notes", &guid).await?.unwrap()));
- quince_icloud::notes::set_paragraph_cloudkit(&http, &root, p.clone(), &note, 19, ParagraphChange::Style(103)).await?;
- println!("checklist: {}", show(&zc.lookup_record("Notes", &guid).await?.unwrap()));
- quince_icloud::notes::set_paragraph_cloudkit(&http, &root, p.clone(), &note, 19, ParagraphChange::Checked(true)).await?;
- println!("ticked: {}", show(&zc.lookup_record("Notes", &guid).await?.unwrap()));
- quince_icloud::notes::set_paragraph_cloudkit(&http, &root, p.clone(), &note, 28, ParagraphChange::Style(101)).await?;
+ println!(
+ "made: {}",
+ show(&zc.lookup_record("Notes", &guid).await?.unwrap())
+ );
+ quince_icloud::notes::set_paragraph_cloudkit(
+ &http,
+ &root,
+ p.clone(),
+ &note,
+ 19,
+ ParagraphChange::Style(103),
+ )
+ .await?;
+ println!(
+ "checklist: {}",
+ show(&zc.lookup_record("Notes", &guid).await?.unwrap())
+ );
+ quince_icloud::notes::set_paragraph_cloudkit(
+ &http,
+ &root,
+ p.clone(),
+ &note,
+ 19,
+ ParagraphChange::Checked(true),
+ )
+ .await?;
+ println!(
+ "ticked: {}",
+ show(&zc.lookup_record("Notes", &guid).await?.unwrap())
+ );
+ quince_icloud::notes::set_paragraph_cloudkit(
+ &http,
+ &root,
+ p.clone(),
+ &note,
+ 28,
+ ParagraphChange::Style(101),
+ )
+ .await?;
let last = zc.lookup_record("Notes", &guid).await?.unwrap();
println!("dashed: {}", show(&last));
- println!("text kept: {:?}", quince_icloud::ckdocument::text_from_base64(last["fields"]["TextDataEncrypted"]["value"].as_str().unwrap_or("")));
+ println!(
+ "text kept: {:?}",
+ quince_icloud::ckdocument::text_from_base64(
+ last["fields"]["TextDataEncrypted"]["value"]
+ .as_str()
+ .unwrap_or("")
+ )
+ );
println!("note {guid} left in place for a look on the phone");
Ok(())
}
diff --git a/src-tauri/src/alerts.rs b/src-tauri/src/alerts.rs
index 2a797b9..16fd7ff 100644
--- a/src-tauri/src/alerts.rs
+++ b/src-tauri/src/alerts.rs
@@ -274,3 +274,131 @@ mod tests {
assert!(lib.due_alarms(now).unwrap().is_empty());
}
}
+
+/// Calendar alerts on the desktop, rung as the phone rings them.
+///
+/// Apple keeps an event's alerts beside it, read one event at a time, so this looks only at
+/// what is coming: the events starting in the next two days, their alerts asked for once and
+/// asked again only when the event changes. Each alert is recorded as rung before it shows,
+/// under the same rule as reminders' — never twice, and one missed by more than a few hours
+/// is let go rather than shown late.
+pub fn spawn_events(app: AppHandle) {
+ tauri::async_runtime::spawn(async move {
+ // Alerts already read, by event: its version, and minutes before its start.
+ let mut known: std::collections::HashMap<String, (Option<String>, Vec<i64>)> =
+ std::collections::HashMap::new();
+ loop {
+ let at = now();
+ let coming: Vec<quince_core::calendar::Event> = {
+ let data = app.state::<Data>();
+ let library = data.0.lock().await;
+ library
+ .events_starting_between(at - STILL_WORTH_SAYING, at + 2 * 86_400)
+ .unwrap_or_default()
+ .into_iter()
+ .filter(|(guid, _)| !guid.starts_with("quince:"))
+ .filter_map(|(guid, _)| library.event(&guid).ok().flatten())
+ .collect()
+ };
+ // Ask for the alerts of any event not yet read, or changed since.
+ let stale: Vec<_> = coming
+ .iter()
+ .filter(|e| known.get(&e.guid).is_none_or(|(tag, _)| *tag != e.etag))
+ .cloned()
+ .collect();
+ if !stale.is_empty() {
+ let session = {
+ let auth = app.state::<Auth>();
+ let client = auth.client.lock().await;
+ client
+ .session()
+ .service_url("calendar")
+ .map(|root| (client.http().clone(), root, client.service_params()))
+ };
+ if let Some((http, root, params)) = session {
+ let cal = quince_icloud::calendar::CalendarClient::new(&http, &root, params);
+ for e in &stale {
+ if let Ok(alerts) = cal.alerts(e).await {
+ known.insert(e.guid.clone(), (e.etag.clone(), alerts));
+ }
+ }
+ }
+ }
+ let mut next: Option<i64> = None;
+ for e in &coming {
+ let Some((_, alerts)) = known.get(&e.guid) else {
+ continue;
+ };
+ for minutes in alerts {
+ let fires_at = e.starts_at - minutes * 60;
+ if fires_at > at {
+ next = Some(next.map_or(fires_at, |n| n.min(fires_at)));
+ continue;
+ }
+ if at - fires_at > STILL_WORTH_SAYING {
+ continue;
+ }
+ let key = format!("event:{}:{minutes}", e.guid);
+ let ring = {
+ let data = app.state::<Data>();
+ let mut library = data.0.lock().await;
+ !library.alarm_already_fired(&key, fires_at).unwrap_or(true)
+ && library.mark_alarm_fired(&key, fires_at, at).is_ok()
+ };
+ if ring {
+ show_event(app.clone(), e.clone(), *minutes);
+ }
+ }
+ }
+ // Until the next alert, but look again every two minutes for new and moved events.
+ let wait = next.map_or(120, |t| (t - at).clamp(1, 120));
+ tokio::time::sleep(Duration::from_secs(u64::try_from(wait).unwrap_or(120))).await;
+ }
+ });
+}
+
+/// "Dentist" — "In 15 minutes · 4:30 PM", as Calendar words an alert.
+fn show_event(app: AppHandle, event: quince_core::calendar::Event, minutes: i64) {
+ std::thread::spawn(move || {
+ let when = jiff::Timestamp::from_second(event.starts_at)
+ .map(|t| {
+ t.to_zoned(jiff::tz::TimeZone::system())
+ .strftime("%-I:%M %p")
+ .to_string()
+ })
+ .unwrap_or_default();
+ let lead = match minutes {
+ 0 => "Now".to_string(),
+ m if m % 1440 == 0 => {
+ format!("In {} day{}", m / 1440, if m == 1440 { "" } else { "s" })
+ }
+ m if m % 60 == 0 => format!("In {} hour{}", m / 60, if m == 60 { "" } else { "s" }),
+ m if m > 0 => format!("In {m} minutes"),
+ m => format!("Started {} minutes ago", -m),
+ };
+ let mut body = if event.all_day {
+ lead
+ } else {
+ format!("{lead} · {when}")
+ };
+ if let Some(place) = event.location.as_deref().filter(|p| !p.trim().is_empty()) {
+ body.push_str(&format!("\n{place}"));
+ }
+ let shown = notify_rust::Notification::new()
+ .appname("Quince")
+ .summary(&event.title)
+ .body(&body)
+ .icon(icon_path(&app).unwrap_or("quince"))
+ .hint(notify_rust::Hint::Category("calendar".into()))
+ .hint(notify_rust::Hint::DesktopEntry("quince".into()))
+ .action("default", "Open")
+ .show();
+ if let Ok(handle) = shown {
+ handle.wait_for_action(|action| {
+ if action == "default" {
+ crate::show_window(&app);
+ }
+ });
+ }
+ });
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index c6743bc..09a4bff 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -1015,9 +1015,16 @@ async fn note_paragraph(
};
let (http, root, params) = cloudkit_context(&auth).await?;
let note = note_by_guid(&data, &guid).await?;
- quince_icloud::notes::set_paragraph_cloudkit(&http, &root, params.clone(), &note, start, change)
- .await
- .map_err(|e| e.to_string())?;
+ quince_icloud::notes::set_paragraph_cloudkit(
+ &http,
+ &root,
+ params.clone(),
+ &note,
+ start,
+ change,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
resync_notes(&http, &root, params, &data).await
}
@@ -2379,6 +2386,7 @@ fn main() {
spawn_heartbeat(Arc::clone(&client));
spawn_auto_sync(app.handle().clone(), client);
alerts::spawn(app.handle().clone());
+ alerts::spawn_events(app.handle().clone());
// A tiling compositor places, sizes and closes windows itself; a title bar with
// minimise and maximise there only takes room and does nothing it does not. On a
// desktop that floats windows — GNOME, KDE — it is how a window is moved, so it stays.