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: read Windows zone names by CLDR's mapping and honour a file's own VTIMEZONE

Yashwanth Kamireddi070483cbf4cd
diff --git a/crates/quince-icloud/src/calendar.rs b/crates/quince-icloud/src/calendar.rs
index 0596e4e..80dd390 100644
--- a/crates/quince-icloud/src/calendar.rs
+++ b/crates/quince-icloud/src/calendar.rs
@@ -3,7 +3,7 @@
//! `/ca/startup` returns the collections plus the events in a window; `/ca/events` returns
//! events alone. Both are shaped for the icloud.com web client rather than for us.
-use crate::{Error, Result};
+use crate::{zones, Error, Result};
use jiff::{civil, tz::TimeZone};
use quince_core::calendar::{Calendar, Event};
use serde_json::Value;
@@ -147,15 +147,27 @@ fn dates_zone(all_day: bool, timezone: Option<&str>) -> Option<String> {
/// This computer's own zone, where it has no name to give.
pub(crate) const SYSTEM_ZONE: &str = "<system>";
-/// The zone a name names: [`SYSTEM_ZONE`] this computer's, an unknown one UTC.
+/// The zone a name names: [`SYSTEM_ZONE`] this computer's; an IANA name, a Windows one (an
+/// event Outlook or Exchange made) or an id ending in an IANA name, that zone; one no zone
+/// database knows, UTC.
fn zone_named(name: Option<&str>) -> TimeZone {
match name {
Some(SYSTEM_ZONE) => TimeZone::system(),
- Some(name) => TimeZone::get(name).unwrap_or(TimeZone::UTC),
+ Some(name) => zones::named(name).map_or(TimeZone::UTC, |z| z.tz),
None => TimeZone::UTC,
}
}
+/// An event's zone by its IANA name. Apple passes on the `TZID` the event was made with, and
+/// one made in Outlook says "W. Europe Standard Time": the window draws in a zone by its IANA
+/// name, and an edit then tells Apple the same zone by that name.
+fn iana_named(name: String) -> String {
+ match zones::named(&name).and_then(|z| z.name) {
+ Some(iana) => iana,
+ None => name,
+ }
+}
+
/// A zone as Apple is told it (`usertz`): by name, or UTC where it has none.
fn apple_tz(name: Option<&str>) -> &str {
name.filter(|n| *n != SYSTEM_ZONE).unwrap_or("UTC")
@@ -177,7 +189,7 @@ fn event_from(v: &Value) -> Result<Option<Event>> {
let (Some(guid), Some(calendar_guid)) = (string(v, "guid"), string(v, "pGuid")) else {
return Ok(None);
};
- let timezone = string(v, "tz");
+ let timezone = string(v, "tz").map(iana_named);
let Some(start_raw) = v.get("startDate") else {
return Ok(None);
};
@@ -1706,6 +1718,39 @@ mod tests {
assert_eq!(utc.to_string(), "2026-09-12T09:00:00Z");
}
+ /// A meeting an Exchange organiser sent: Apple passes on the zone it was made in by its
+ /// Windows name. Read as UTC it was drawn two hours late; it is Berlin, and kept by
+ /// Berlin's IANA name for the window and for an edit sent back.
+ #[test]
+ fn an_event_in_a_windows_zone_is_read_in_that_zone() {
+ let event = event_from(&json!({
+ "guid": "EX", "pGuid": "work", "title": "Review",
+ "tz": "W. Europe Standard Time", "allDay": false,
+ "startDate": [20260715, 2026, 7, 15, 10, 0, 600],
+ "endDate": [20260715, 2026, 7, 15, 11, 0, 660],
+ }))
+ .unwrap()
+ .unwrap();
+ assert_eq!(event.timezone.as_deref(), Some("Europe/Berlin"));
+ let start = jiff::Timestamp::from_second(event.starts_at).unwrap();
+ assert_eq!(start.to_string(), "2026-07-15T08:00:00Z");
+ assert_eq!(event.ends_at - event.starts_at, 3600);
+ // And the date read back in that zone is the one Apple sent.
+ let raw = json!([20260715, 2026, 7, 15, 10, 0, 600]);
+ assert_eq!(
+ format_apple_date(event.starts_at, Some("W. Europe Standard Time")),
+ raw
+ );
+ // A name no zone database knows stays as Apple sent it.
+ let odd = event_from(&json!({
+ "guid": "O", "pGuid": "work", "tz": "Nowhere Time",
+ "startDate": [20260715, 2026, 7, 15, 10, 0, 600],
+ }))
+ .unwrap()
+ .unwrap();
+ assert_eq!(odd.timezone.as_deref(), Some("Nowhere Time"));
+ }
+
#[test]
fn the_same_reading_in_another_zone_is_another_instant() {
let raw = json!([20260912, 2026, 9, 12, 14, 30, 870]);
diff --git a/crates/quince-icloud/src/calendar_feeds.rs b/crates/quince-icloud/src/calendar_feeds.rs
index ef335db..25d7113 100644
--- a/crates/quince-icloud/src/calendar_feeds.rs
+++ b/crates/quince-icloud/src/calendar_feeds.rs
@@ -5,7 +5,7 @@
//! Nothing here is Apple's. The file is fetched with a client that can reach the hosts the
//! person subscribed to and nothing else (`quince_auth::listed_only`), and only once they have.
-use crate::{Error, Result};
+use crate::{zones, Error, Result};
use jiff::civil::{Date, DateTime, Time, Weekday};
use jiff::tz::TimeZone;
use jiff::{Span, Timestamp, ToSpan};
@@ -283,79 +283,19 @@ fn parse_datetime(s: &str) -> Option<(DateTime, bool)> {
Some((date.to_datetime(time), utc))
}
-/// A `TZID` this computer knows: an IANA name, one inside a longer id
-/// (`/mozilla.org/20050126_1/Europe/Berlin`), or one of the Windows names Outlook writes.
-fn zone_named(tzid: &str) -> Option<TimeZone> {
- let tzid = tzid.trim().trim_matches('"').trim_start_matches('/');
- if let Ok(tz) = TimeZone::get(tzid) {
- return Some(tz);
- }
- let segments: Vec<&str> = tzid.split('/').collect();
- for start in 1..segments.len() {
- if let Ok(tz) = TimeZone::get(&segments[start..].join("/")) {
- return Some(tz);
- }
- }
- WINDOWS_ZONES
- .iter()
- .find(|(w, _)| w.eq_ignore_ascii_case(tzid))
- .and_then(|(_, iana)| TimeZone::get(iana).ok())
+/// What a file's times are read against: this computer's clock for a floating time, and the
+/// zones the file itself defines in its `VTIMEZONE`s.
+struct Clock<'a> {
+ here: &'a TimeZone,
+ zones: &'a zones::Defined,
}
-/// Windows' zone names, as Outlook and Exchange publish them (CLDR's windowsZones, "001").
-const WINDOWS_ZONES: &[(&str, &str)] = &[
- ("UTC", "UTC"),
- ("GMT Standard Time", "Europe/London"),
- ("Greenwich Standard Time", "Atlantic/Reykjavik"),
- ("W. Europe Standard Time", "Europe/Berlin"),
- ("Romance Standard Time", "Europe/Paris"),
- ("Central Europe Standard Time", "Europe/Budapest"),
- ("Central European Standard Time", "Europe/Warsaw"),
- ("E. Europe Standard Time", "Europe/Chisinau"),
- ("FLE Standard Time", "Europe/Kiev"),
- ("GTB Standard Time", "Europe/Bucharest"),
- ("Russian Standard Time", "Europe/Moscow"),
- ("Turkey Standard Time", "Europe/Istanbul"),
- ("Israel Standard Time", "Asia/Jerusalem"),
- ("South Africa Standard Time", "Africa/Johannesburg"),
- ("Egypt Standard Time", "Africa/Cairo"),
- ("Arabian Standard Time", "Asia/Dubai"),
- ("Arab Standard Time", "Asia/Riyadh"),
- ("Pakistan Standard Time", "Asia/Karachi"),
- ("India Standard Time", "Asia/Kolkata"),
- ("Sri Lanka Standard Time", "Asia/Colombo"),
- ("Nepal Standard Time", "Asia/Kathmandu"),
- ("Bangladesh Standard Time", "Asia/Dhaka"),
- ("SE Asia Standard Time", "Asia/Bangkok"),
- ("Singapore Standard Time", "Asia/Singapore"),
- ("China Standard Time", "Asia/Shanghai"),
- ("Taipei Standard Time", "Asia/Taipei"),
- ("Tokyo Standard Time", "Asia/Tokyo"),
- ("Korea Standard Time", "Asia/Seoul"),
- ("AUS Eastern Standard Time", "Australia/Sydney"),
- ("E. Australia Standard Time", "Australia/Brisbane"),
- ("W. Australia Standard Time", "Australia/Perth"),
- ("New Zealand Standard Time", "Pacific/Auckland"),
- ("Hawaiian Standard Time", "Pacific/Honolulu"),
- ("Alaskan Standard Time", "America/Anchorage"),
- ("Pacific Standard Time", "America/Los_Angeles"),
- ("Mountain Standard Time", "America/Denver"),
- ("US Mountain Standard Time", "America/Phoenix"),
- ("Central Standard Time", "America/Chicago"),
- ("Eastern Standard Time", "America/New_York"),
- ("Atlantic Standard Time", "America/Halifax"),
- ("Newfoundland Standard Time", "America/St_Johns"),
- ("E. South America Standard Time", "America/Sao_Paulo"),
- ("Argentina Standard Time", "America/Buenos_Aires"),
- ("Mexico Standard Time", "America/Mexico_City"),
-];
-
/// A date or date-time property, read in `here` when it floats (no zone given).
-fn when_of(p: &Property, here: &TimeZone) -> Option<When> {
+fn when_of(p: &Property, here: &Clock) -> Option<When> {
when_value(&p.value, p, here)
}
-fn when_value(value: &str, p: &Property, here: &TimeZone) -> Option<When> {
+fn when_value(value: &str, p: &Property, here: &Clock) -> Option<When> {
let date_only = p
.param("VALUE")
.is_some_and(|v| v.eq_ignore_ascii_case("DATE"))
@@ -368,8 +308,8 @@ fn when_value(value: &str, p: &Property, here: &TimeZone) -> Option<When> {
TimeZone::UTC
} else {
p.param("TZID")
- .and_then(zone_named)
- .unwrap_or_else(|| here.clone())
+ .and_then(|tzid| here.zones.zone(tzid))
+ .map_or_else(|| here.here.clone(), |z| z.tz)
};
Some(When::At(dt, zone))
}
@@ -447,7 +387,7 @@ fn weekday_of(code: &str) -> Option<Weekday> {
})
}
-fn rule_of(p: &Property, here: &TimeZone) -> Option<Rule> {
+fn rule_of(p: &Property, here: &Clock) -> Option<Rule> {
let mut rule = Rule {
freq: Freq::Daily,
interval: 1,
@@ -564,6 +504,11 @@ pub fn parse(text: &str, here: &TimeZone) -> Result<Feed> {
if !text.contains("BEGIN:VCALENDAR") {
return Err(Error::Refused("That isn’t a calendar file.".into()));
}
+ let zones = zones::Defined::read(text);
+ let here = &Clock {
+ here,
+ zones: &zones,
+ };
let mut feed = Feed::default();
// Nesting: VCALENDAR > VEVENT > VALARM. Only a VEVENT's own lines are its own.
let mut stack: Vec<String> = Vec::new();
@@ -621,7 +566,7 @@ pub fn parse(text: &str, here: &TimeZone) -> Result<Feed> {
Ok(feed)
}
-fn item_of(props: &[Property], here: &TimeZone) -> Option<Item> {
+fn item_of(props: &[Property], here: &Clock) -> Option<Item> {
let get = |name: &str| props.iter().find(|p| p.name == name);
let text = |name: &str| {
get(name)
@@ -1229,6 +1174,46 @@ mod tests {
assert_eq!(got[0].starts_at, at("Asia/Kolkata", "20261015T160000"));
}
+ /// An Outlook-published calendar (Outlook on the web's "Publish calendar"): a zone Outlook
+ /// named itself, defined only by the file's VTIMEZONE, and a Windows name the file defines
+ /// too. Read on this computer's clock (UTC here) both were hours off.
+ #[test]
+ fn an_outlook_feeds_own_zones_are_read_by_their_rules() {
+ let text = concat!(
+ "BEGIN:VCALENDAR\r\nMETHOD:PUBLISH\r\nPRODID:Microsoft Exchange Server 2010\r\nVERSION:2.0\r\nX-WR-CALNAME:Team\r\n",
+ "BEGIN:VTIMEZONE\r\nTZID:Customized Time Zone\r\n",
+ "BEGIN:STANDARD\r\nDTSTART:16010101T030000\r\nTZOFFSETFROM:+1030\r\nTZOFFSETTO:+0930\r\n",
+ "RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=1SU;BYMONTH=4\r\nEND:STANDARD\r\n",
+ "BEGIN:DAYLIGHT\r\nDTSTART:16010101T020000\r\nTZOFFSETFROM:+0930\r\nTZOFFSETTO:+1030\r\n",
+ "RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=1SU;BYMONTH=10\r\nEND:DAYLIGHT\r\nEND:VTIMEZONE\r\n",
+ "BEGIN:VTIMEZONE\r\nTZID:Jordan Standard Time\r\n",
+ "BEGIN:STANDARD\r\nDTSTART:16010101T000000\r\nTZOFFSETFROM:+0300\r\nTZOFFSETTO:+0300\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n",
+ "BEGIN:VEVENT\r\nUID:weekly\r\nSUMMARY:Sync\r\n",
+ "DTSTART;TZID=Customized Time Zone:20260329T090000\r\nDTEND;TZID=Customized Time Zone:20260329T093000\r\n",
+ "RRULE:FREQ=WEEKLY;COUNT=2\r\nEND:VEVENT\r\n",
+ "BEGIN:VEVENT\r\nUID:amman\r\nSUMMARY:Amman\r\n",
+ "DTSTART;TZID=Jordan Standard Time:20260715T100000\r\nDTEND;TZID=Jordan Standard Time:20260715T110000\r\nEND:VEVENT\r\n",
+ "END:VCALENDAR\r\n",
+ );
+ let feed = parse(text, &TimeZone::UTC).unwrap();
+ let (from, to) = year(2026);
+ let mut got = events(&feed, "c", from, to);
+ got.sort_by_key(|e| e.starts_at);
+ assert_eq!(got.len(), 3);
+ // Adelaide's rules: 09:00 at +10:30 on 29 March, at +09:30 a week on (5 April).
+ assert_eq!(
+ got[0].starts_at,
+ at("Australia/Adelaide", "20260329T090000")
+ );
+ assert_eq!(got[0].ends_at - got[0].starts_at, 1800);
+ assert_eq!(
+ got[1].starts_at,
+ at("Australia/Adelaide", "20260405T090000")
+ );
+ // Amman, as the file defines it.
+ assert_eq!(got[2].starts_at, at("Asia/Amman", "20260715T100000"));
+ }
+
#[test]
fn a_subscription_is_due_by_its_own_interval() {
let mut s = Subscription {
diff --git a/crates/quince-icloud/src/lib.rs b/crates/quince-icloud/src/lib.rs
index 6f4ad31..87b5a0a 100644
--- a/crates/quince-icloud/src/lib.rs
+++ b/crates/quince-icloud/src/lib.rs
@@ -36,6 +36,7 @@ pub mod shared_albums;
pub mod sync;
pub mod table;
pub mod topotext;
+pub mod zones;
#[derive(Debug, thiserror::Error)]
pub enum Error {
diff --git a/crates/quince-icloud/src/windows_zones.tsv b/crates/quince-icloud/src/windows_zones.tsv
new file mode 100644
index 0000000..c321e77
--- /dev/null
+++ b/crates/quince-icloud/src/windows_zones.tsv
@@ -0,0 +1,148 @@
+# Windows time zone names and the IANA zone each is: every territory="001" row of Unicode
+# CLDR's windowsZones.xml, as published and in its order, one "other<TAB>type" per line.
+# Source: https://github.com/unicode-org/cldr/blob/release-49/common/supplemental/windowsZones.xml
+# CLDR release 49; mapTimezones otherVersion="7e11800" typeVersion="2021a";
+# file sha256 5f902f94106a396cb7774f0b0e1ca4dfecb686494045350c0b4935d378e3913b.
+# To update: replace the rows below with the new release's territory="001" rows.
+Dateline Standard Time Etc/GMT+12
+UTC-11 Etc/GMT+11
+Aleutian Standard Time America/Adak
+Hawaiian Standard Time Pacific/Honolulu
+Marquesas Standard Time Pacific/Marquesas
+Alaskan Standard Time America/Anchorage
+UTC-09 Etc/GMT+9
+Pacific Standard Time (Mexico) America/Tijuana
+UTC-08 Etc/GMT+8
+Pacific Standard Time America/Los_Angeles
+US Mountain Standard Time America/Phoenix
+Mountain Standard Time (Mexico) America/Mazatlan
+Mountain Standard Time America/Denver
+British Columbia Standard Time America/Vancouver
+Yukon Standard Time America/Whitehorse
+Alberta Standard Time America/Edmonton
+Central America Standard Time America/Guatemala
+Central Standard Time America/Chicago
+Easter Island Standard Time Pacific/Easter
+Central Standard Time (Mexico) America/Mexico_City
+Canada Central Standard Time America/Regina
+Manitoba Standard Time America/Winnipeg
+SA Pacific Standard Time America/Bogota
+Eastern Standard Time (Mexico) America/Cancun
+Eastern Standard Time America/New_York
+Haiti Standard Time America/Port-au-Prince
+Cuba Standard Time America/Havana
+US Eastern Standard Time America/Indianapolis
+Turks And Caicos Standard Time America/Grand_Turk
+Paraguay Standard Time America/Asuncion
+Atlantic Standard Time America/Halifax
+Venezuela Standard Time America/Caracas
+Central Brazilian Standard Time America/Cuiaba
+SA Western Standard Time America/La_Paz
+Pacific SA Standard Time America/Santiago
+Newfoundland Standard Time America/St_Johns
+Tocantins Standard Time America/Araguaina
+E. South America Standard Time America/Sao_Paulo
+SA Eastern Standard Time America/Cayenne
+Argentina Standard Time America/Buenos_Aires
+Greenland Standard Time America/Godthab
+Montevideo Standard Time America/Montevideo
+Magallanes Standard Time America/Punta_Arenas
+Saint Pierre Standard Time America/Miquelon
+Bahia Standard Time America/Bahia
+UTC-02 Etc/GMT+2
+Azores Standard Time Atlantic/Azores
+Cape Verde Standard Time Atlantic/Cape_Verde
+UTC Etc/UTC
+GMT Standard Time Europe/London
+Greenwich Standard Time Atlantic/Reykjavik
+Sao Tome Standard Time Africa/Sao_Tome
+Morocco Standard Time Africa/Casablanca
+W. Europe Standard Time Europe/Berlin
+Central Europe Standard Time Europe/Budapest
+Romance Standard Time Europe/Paris
+Central European Standard Time Europe/Warsaw
+W. Central Africa Standard Time Africa/Lagos
+Jordan Standard Time Asia/Amman
+GTB Standard Time Europe/Bucharest
+Middle East Standard Time Asia/Beirut
+Egypt Standard Time Africa/Cairo
+E. Europe Standard Time Europe/Chisinau
+Syria Standard Time Asia/Damascus
+West Bank Standard Time Asia/Hebron
+South Africa Standard Time Africa/Johannesburg
+FLE Standard Time Europe/Kiev
+Israel Standard Time Asia/Jerusalem
+South Sudan Standard Time Africa/Juba
+Kaliningrad Standard Time Europe/Kaliningrad
+Sudan Standard Time Africa/Khartoum
+Libya Standard Time Africa/Tripoli
+Namibia Standard Time Africa/Windhoek
+Arabic Standard Time Asia/Baghdad
+Turkey Standard Time Europe/Istanbul
+Arab Standard Time Asia/Riyadh
+Belarus Standard Time Europe/Minsk
+Russian Standard Time Europe/Moscow
+E. Africa Standard Time Africa/Nairobi
+Iran Standard Time Asia/Tehran
+Arabian Standard Time Asia/Dubai
+Astrakhan Standard Time Europe/Astrakhan
+Azerbaijan Standard Time Asia/Baku
+Russia Time Zone 3 Europe/Samara
+Mauritius Standard Time Indian/Mauritius
+Saratov Standard Time Europe/Saratov
+Georgian Standard Time Asia/Tbilisi
+Volgograd Standard Time Europe/Volgograd
+Caucasus Standard Time Asia/Yerevan
+Afghanistan Standard Time Asia/Kabul
+West Asia Standard Time Asia/Tashkent
+Ekaterinburg Standard Time Asia/Yekaterinburg
+Pakistan Standard Time Asia/Karachi
+Qyzylorda Standard Time Asia/Qyzylorda
+India Standard Time Asia/Calcutta
+Sri Lanka Standard Time Asia/Colombo
+Nepal Standard Time Asia/Katmandu
+Central Asia Standard Time Asia/Bishkek
+Bangladesh Standard Time Asia/Dhaka
+Omsk Standard Time Asia/Omsk
+Myanmar Standard Time Asia/Rangoon
+SE Asia Standard Time Asia/Bangkok
+Altai Standard Time Asia/Barnaul
+W. Mongolia Standard Time Asia/Hovd
+North Asia Standard Time Asia/Krasnoyarsk
+N. Central Asia Standard Time Asia/Novosibirsk
+Tomsk Standard Time Asia/Tomsk
+China Standard Time Asia/Shanghai
+North Asia East Standard Time Asia/Irkutsk
+Singapore Standard Time Asia/Singapore
+W. Australia Standard Time Australia/Perth
+Taipei Standard Time Asia/Taipei
+Ulaanbaatar Standard Time Asia/Ulaanbaatar
+Aus Central W. Standard Time Australia/Eucla
+Transbaikal Standard Time Asia/Chita
+Tokyo Standard Time Asia/Tokyo
+North Korea Standard Time Asia/Pyongyang
+Korea Standard Time Asia/Seoul
+Yakutsk Standard Time Asia/Yakutsk
+Cen. Australia Standard Time Australia/Adelaide
+AUS Central Standard Time Australia/Darwin
+E. Australia Standard Time Australia/Brisbane
+AUS Eastern Standard Time Australia/Sydney
+West Pacific Standard Time Pacific/Port_Moresby
+Tasmania Standard Time Australia/Hobart
+Vladivostok Standard Time Asia/Vladivostok
+Lord Howe Standard Time Australia/Lord_Howe
+Bougainville Standard Time Pacific/Bougainville
+Russia Time Zone 10 Asia/Srednekolymsk
+Magadan Standard Time Asia/Magadan
+Norfolk Standard Time Pacific/Norfolk
+Sakhalin Standard Time Asia/Sakhalin
+Central Pacific Standard Time Pacific/Guadalcanal
+Russia Time Zone 11 Asia/Kamchatka
+New Zealand Standard Time Pacific/Auckland
+UTC+12 Etc/GMT-12
+Fiji Standard Time Pacific/Fiji
+Chatham Islands Standard Time Pacific/Chatham
+UTC+13 Etc/GMT-13
+Tonga Standard Time Pacific/Tongatapu
+Samoa Standard Time Pacific/Apia
+Line Islands Standard Time Pacific/Kiritimati
diff --git a/crates/quince-icloud/src/zones.rs b/crates/quince-icloud/src/zones.rs
new file mode 100644
index 0000000..d7509eb
--- /dev/null
+++ b/crates/quince-icloud/src/zones.rs
@@ -0,0 +1,532 @@
+//! The zone a calendar names, however it names it.
+//!
+//! A `TZID` (and Apple's own `tz` on an event) is usually an IANA name, but Outlook and
+//! Exchange write Windows' names ("W. Europe Standard Time"), Thunderbird a longer id with the
+//! IANA name at its end, and Outlook sometimes a name of its own ("Customized Time Zone") that
+//! only the file's `VTIMEZONE` defines. Read as nothing, each became UTC or this computer's
+//! clock, and the event was drawn hours off.
+//!
+//! Windows' names are Unicode CLDR's `windowsZones` mapping, kept as data in
+//! `windows_zones.tsv` with the release it came from.
+
+use jiff::tz::TimeZone;
+
+/// CLDR's territory "001" rows: a Windows name, a tab, the IANA zone.
+const WINDOWS_ZONES: &str = include_str!("windows_zones.tsv");
+
+/// CLDR keeps the IANA ids it first published; IANA has since renamed these (its `backward`
+/// file). The current name is what Calendar shows and what is written back to Apple; the old
+/// one is still read where a computer's zone database predates the rename.
+const RENAMED: &[(&str, &str)] = &[
+ ("America/Buenos_Aires", "America/Argentina/Buenos_Aires"),
+ ("America/Godthab", "America/Nuuk"),
+ ("America/Indianapolis", "America/Indiana/Indianapolis"),
+ ("Asia/Calcutta", "Asia/Kolkata"),
+ ("Asia/Katmandu", "Asia/Kathmandu"),
+ ("Asia/Rangoon", "Asia/Yangon"),
+ ("Europe/Kiev", "Europe/Kyiv"),
+];
+
+/// The IANA zone CLDR maps a Windows zone name to, by its current IANA name.
+#[must_use]
+pub fn windows_zone(name: &str) -> Option<&'static str> {
+ let name = name.trim();
+ let iana = WINDOWS_ZONES
+ .lines()
+ .filter(|l| !l.starts_with('#'))
+ .filter_map(|l| l.split_once('\t'))
+ .find(|(windows, _)| windows.eq_ignore_ascii_case(name))
+ .map(|(_, iana)| iana.trim())?;
+ Some(
+ RENAMED
+ .iter()
+ .find(|(old, _)| *old == iana)
+ .map_or(iana, |(_, new)| new),
+ )
+}
+
+/// A zone found, and the IANA name it goes by where it has one. A zone only a file's
+/// `VTIMEZONE` defines has none.
+#[derive(Debug, Clone)]
+pub struct Zone {
+ pub tz: TimeZone,
+ pub name: Option<String>,
+}
+
+fn by_iana(name: &str) -> Option<Zone> {
+ let tz = TimeZone::get(name).ok()?;
+ let name = tz.iana_name().unwrap_or(name).to_string();
+ Some(Zone {
+ tz,
+ name: Some(name),
+ })
+}
+
+/// A CLDR zone by its current name, or by the name CLDR gives it where this computer's zone
+/// database has only that.
+fn by_windows(name: &str) -> Option<Zone> {
+ let iana = windows_zone(name)?;
+ by_iana(iana).or_else(|| {
+ let old = RENAMED.iter().find(|(_, new)| *new == iana)?.0;
+ let tz = TimeZone::get(old).ok()?;
+ Some(Zone {
+ tz,
+ name: Some(old.to_string()),
+ })
+ })
+}
+
+fn cleaned(tzid: &str) -> &str {
+ tzid.trim().trim_matches('"').trim_start_matches('/')
+}
+
+/// An IANA name inside a longer id, as Thunderbird writes them
+/// (`/mozilla.org/20050126_1/Europe/Berlin`).
+fn by_segments(tzid: &str) -> Option<Zone> {
+ let segments: Vec<&str> = tzid.split('/').collect();
+ (1..segments.len()).find_map(|start| by_iana(&segments[start..].join("/")))
+}
+
+/// A zone by name alone, where there is no file to define it: an IANA name, a Windows name,
+/// or an IANA name at the end of a longer id.
+#[must_use]
+pub fn named(tzid: &str) -> Option<Zone> {
+ let tzid = cleaned(tzid);
+ if tzid.is_empty() {
+ return None;
+ }
+ by_iana(tzid)
+ .or_else(|| by_windows(tzid))
+ .or_else(|| by_segments(tzid))
+}
+
+/// The zones a calendar file defines in its `VTIMEZONE`s, by their `TZID`.
+#[derive(Debug, Clone, Default)]
+pub struct Defined {
+ zones: Vec<(String, TimeZone)>,
+}
+
+impl Defined {
+ /// Every `VTIMEZONE` in a calendar file whose rules can be read.
+ #[must_use]
+ pub fn read(text: &str) -> Self {
+ let mut zones = Vec::new();
+ let mut tzid: Option<String> = None;
+ let mut observances: Vec<Observance> = Vec::new();
+ let mut current: Option<Observance> = None;
+ let mut inside = false;
+ for line in unfold(text) {
+ let Some((name, value)) = name_value(&line) else {
+ continue;
+ };
+ let upper = value.trim().to_ascii_uppercase();
+ match (name.as_str(), upper.as_str()) {
+ ("BEGIN", "VTIMEZONE") => {
+ inside = true;
+ tzid = None;
+ observances.clear();
+ }
+ ("END", "VTIMEZONE") => {
+ if let (Some(id), Some(tz)) = (tzid.take(), zone_of(&observances)) {
+ zones.push((id, tz));
+ }
+ inside = false;
+ }
+ ("BEGIN", kind @ ("STANDARD" | "DAYLIGHT")) if inside => {
+ current = Some(Observance {
+ daylight: kind == "DAYLIGHT",
+ ..Observance::default()
+ });
+ }
+ ("END", "STANDARD" | "DAYLIGHT") if inside => {
+ observances.extend(current.take());
+ }
+ _ if !inside => {}
+ ("TZID", _) if current.is_none() => {
+ tzid = Some(cleaned(&value).to_string());
+ }
+ _ => {
+ if let Some(o) = current.as_mut() {
+ let value = value.trim().to_string();
+ match name.as_str() {
+ "DTSTART" => o.start = value,
+ "TZOFFSETFROM" => o.from = offset(&value),
+ "TZOFFSETTO" => o.to = offset(&value),
+ "RRULE" => o.rule = Some(value),
+ _ => {}
+ }
+ }
+ }
+ }
+ }
+ Defined { zones }
+ }
+
+ fn get(&self, tzid: &str) -> Option<&TimeZone> {
+ let tzid = cleaned(tzid);
+ self.zones
+ .iter()
+ .find(|(id, _)| id == tzid)
+ .or_else(|| {
+ self.zones
+ .iter()
+ .find(|(id, _)| id.eq_ignore_ascii_case(tzid))
+ })
+ .map(|(_, tz)| tz)
+ }
+
+ /// The zone a `TZID` in this file means.
+ ///
+ /// An IANA name is the zone database's, which knows its history; so is one at the end of
+ /// a longer id. Any other name is what the file's own `VTIMEZONE` says it is (RFC 5545),
+ /// named for Apple by CLDR where it is a Windows name; and without one, CLDR's zone.
+ #[must_use]
+ pub fn zone(&self, tzid: &str) -> Option<Zone> {
+ let clean = cleaned(tzid);
+ if clean.is_empty() {
+ return None;
+ }
+ if let Some(z) = by_iana(clean).or_else(|| by_segments(clean)) {
+ return Some(z);
+ }
+ if let Some(tz) = self.get(clean) {
+ return Some(Zone {
+ tz: tz.clone(),
+ name: by_windows(clean).and_then(|z| z.name),
+ });
+ }
+ by_windows(clean)
+ }
+}
+
+/// One `STANDARD` or `DAYLIGHT` of a `VTIMEZONE`.
+#[derive(Debug, Clone, Default)]
+struct Observance {
+ daylight: bool,
+ /// `DTSTART`, a local time on the clock before this observance began.
+ start: String,
+ from: Option<i32>,
+ to: Option<i32>,
+ rule: Option<String>,
+}
+
+impl Observance {
+ /// A yearly rule with no end: the observance as it still stands.
+ fn ongoing_rule(&self) -> Option<&str> {
+ let rule = self.rule.as_deref()?;
+ let parts = rule_parts(rule);
+ let yearly = parts
+ .iter()
+ .any(|(k, v)| k == "FREQ" && v.eq_ignore_ascii_case("YEARLY"));
+ let ends = parts.iter().any(|(k, _)| k == "UNTIL" || k == "COUNT");
+ (yearly && !ends).then_some(rule)
+ }
+}
+
+fn rule_parts(rule: &str) -> Vec<(String, String)> {
+ rule.split(';')
+ .filter_map(|p| p.split_once('='))
+ .map(|(k, v)| (k.trim().to_ascii_uppercase(), v.trim().to_string()))
+ .collect()
+}
+
+/// `+0100`, `-0530`, `+013000`: seconds east of UTC.
+fn offset(s: &str) -> Option<i32> {
+ let s = s.trim();
+ let (sign, digits) = match s.as_bytes().first()? {
+ b'+' => (1, &s[1..]),
+ b'-' => (-1, &s[1..]),
+ _ => (1, s),
+ };
+ if !(digits.len() == 4 || digits.len() == 6) || !digits.bytes().all(|b| b.is_ascii_digit()) {
+ return None;
+ }
+ let h: i32 = digits[0..2].parse().ok()?;
+ let m: i32 = digits[2..4].parse().ok()?;
+ let sec: i32 = digits.get(4..6).map_or(Some(0), |x| x.parse().ok())?;
+ (h < 24 && m < 60 && sec < 60).then_some(sign * (h * 3600 + m * 60 + sec))
+}
+
+/// A `VTIMEZONE`'s rules as a zone: its standing yearly change between standard time and
+/// daylight time, or the offset it last settled on where it no longer changes.
+fn zone_of(observances: &[Observance]) -> Option<TimeZone> {
+ let latest = |daylight: bool, ongoing: bool| {
+ observances
+ .iter()
+ .filter(|o| o.daylight == daylight && (!ongoing || o.ongoing_rule().is_some()))
+ .max_by(|a, b| a.start.cmp(&b.start))
+ };
+ if let (Some(std), Some(dst)) = (latest(false, true), latest(true, true)) {
+ if let Some(tz) = posix_of(std, dst).and_then(|p| TimeZone::posix(&p).ok()) {
+ return Some(tz);
+ }
+ }
+ // No standing change: the offset of whichever observance began last.
+ let last = observances.iter().max_by(|a, b| a.start.cmp(&b.start))?;
+ let to = last.to?;
+ jiff::tz::Offset::from_seconds(to).ok().map(TimeZone::fixed)
+}
+
+/// The two yearly changes as a POSIX TZ string, which keeps applying them for every year.
+fn posix_of(std: &Observance, dst: &Observance) -> Option<String> {
+ let std_offset = std.to?;
+ let dst_offset = dst.to?;
+ let begins = change_of(dst)?;
+ let ends = change_of(std)?;
+ Some(format!(
+ "STD{}DST{},{begins},{ends}",
+ posix_offset(std_offset),
+ posix_offset(dst_offset)
+ ))
+}
+
+/// POSIX writes an offset as how far behind UTC the clock is: UTC+1 is `-1`.
+fn posix_offset(east: i32) -> String {
+ let west = -east;
+ let sign = if west < 0 { "-" } else { "" };
+ let a = west.unsigned_abs();
+ format!("{sign}{}:{:02}:{:02}", a / 3600, a / 60 % 60, a % 60)
+}
+
+/// When an observance begins each year, as POSIX says it: `M3.5.0/02:00:00` (the last Sunday
+/// of March, at 2:00 on the clock before), or `J80/00:00:00` (a fixed date).
+fn change_of(o: &Observance) -> Option<String> {
+ let rule = rule_parts(o.ongoing_rule()?);
+ let get = |k: &str| {
+ rule.iter()
+ .find(|(key, _)| key == k)
+ .map(|(_, v)| v.as_str())
+ };
+ let (date, time) = o.start.split_once(['T', 't'])?;
+ let time = time.trim_end_matches(['Z', 'z']);
+ if date.len() != 8 || time.len() < 4 || !time.bytes().all(|b| b.is_ascii_digit()) {
+ return None;
+ }
+ let month: u8 = match get("BYMONTH") {
+ Some(m) => m.parse().ok()?,
+ None => date[4..6].parse().ok()?,
+ };
+ if !(1..=12).contains(&month) {
+ return None;
+ }
+ let at = format!(
+ "/{}:{}:{}",
+ &time[0..2],
+ &time[2..4],
+ time.get(4..6).unwrap_or("00")
+ );
+ let month_days: Vec<i8> = get("BYMONTHDAY")
+ .map(|v| v.split(',').filter_map(|d| d.trim().parse().ok()).collect())
+ .unwrap_or_default();
+ let day = match get("BYDAY") {
+ Some(by_day) => {
+ let by_day = by_day.trim();
+ if by_day.contains(',') || by_day.len() < 2 {
+ return None;
+ }
+ let (n, code) = by_day.split_at(by_day.len() - 2);
+ let weekday = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"]
+ .iter()
+ .position(|c| c.eq_ignore_ascii_case(code))?;
+ let n: i8 = match n.trim_start_matches('+') {
+ "" => week_of_days(&month_days)?,
+ n => n.parse().ok()?,
+ };
+ let week = match n {
+ 1..=4 => n,
+ 5 | -1 => 5,
+ _ => return None,
+ };
+ format!("M{month}.{week}.{weekday}")
+ }
+ None => {
+ // A fixed date each year, counted as POSIX's `J` does: never a 29 February.
+ let &[d] = month_days.as_slice() else {
+ return None;
+ };
+ let first_of_months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
+ let days_in = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
+ let m = usize::from(month - 1);
+ if !(1..=days_in[m]).contains(&d) {
+ return None;
+ }
+ format!("J{}", first_of_months[m] + i32::from(d))
+ }
+ };
+ Some(format!("{day}{at}"))
+}
+
+/// A weekday given with the seven days of the month it falls in (`BYMONTHDAY=8,…,14;BYDAY=SU`,
+/// the second Sunday), as the week POSIX counts.
+fn week_of_days(days: &[i8]) -> Option<i8> {
+ let first = *days.iter().min()?;
+ if days.len() != 7 {
+ return None;
+ }
+ match first {
+ 1 | 8 | 15 | 22 => Some((first - 1) / 7 + 1),
+ -7 => Some(5),
+ _ => None,
+ }
+}
+
+fn unfold(text: &str) -> Vec<String> {
+ let mut lines: Vec<String> = Vec::new();
+ for raw in text.split('\n') {
+ let raw = raw.strip_suffix('\r').unwrap_or(raw);
+ if let Some(rest) = raw.strip_prefix([' ', '\t']) {
+ if let Some(last) = lines.last_mut() {
+ last.push_str(rest);
+ continue;
+ }
+ }
+ if !raw.is_empty() {
+ lines.push(raw.to_string());
+ }
+ }
+ lines
+}
+
+/// A line's name and value, a colon inside a quoted parameter not ending the name.
+fn name_value(line: &str) -> Option<(String, String)> {
+ let mut quoted = false;
+ let at = line.char_indices().find_map(|(i, c)| match c {
+ '"' => {
+ quoted = !quoted;
+ None
+ }
+ ':' if !quoted => Some(i),
+ _ => None,
+ })?;
+ let name = line[..at].split(';').next()?.trim().to_ascii_uppercase();
+ Some((name, line[at + 1..].to_string()))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use jiff::civil::DateTime;
+
+ /// Seconds east of UTC that `tz` is at a clock reading on it.
+ fn offset_at(tz: &TimeZone, clock: &str) -> i32 {
+ let dt: DateTime = clock.parse().unwrap();
+ dt.to_zoned(tz.clone()).unwrap().offset().seconds()
+ }
+
+ #[test]
+ fn every_cldr_row_is_a_zone_this_computer_knows() {
+ let rows: Vec<&str> = WINDOWS_ZONES
+ .lines()
+ .filter(|l| !l.starts_with('#'))
+ .collect();
+ assert_eq!(rows.len(), 142, "CLDR 49 has 142 territory 001 rows");
+ for row in rows {
+ let (windows, _) = row.split_once('\t').expect("a tab between the two names");
+ let z = named(windows).unwrap_or_else(|| panic!("{windows} is no zone here"));
+ assert!(z.name.is_some(), "{windows}");
+ }
+ }
+
+ #[test]
+ fn windows_names_are_cldrs_001_zone_by_its_current_name() {
+ assert_eq!(
+ windows_zone("W. Europe Standard Time"),
+ Some("Europe/Berlin")
+ );
+ assert_eq!(windows_zone("india standard time"), Some("Asia/Kolkata"));
+ assert_eq!(windows_zone("FLE Standard Time"), Some("Europe/Kyiv"));
+ assert_eq!(windows_zone("UTC"), Some("Etc/UTC"));
+ assert_eq!(windows_zone("Mars Standard Time"), None);
+ let z = named("\"India Standard Time\"").unwrap();
+ assert_eq!(z.name.as_deref(), Some("Asia/Kolkata"));
+ assert_eq!(offset_at(&z.tz, "2026-01-15T09:00"), 19_800);
+ // An IANA name stands as it is; one at the end of a longer id is found.
+ assert_eq!(
+ named("America/New_York").unwrap().name.as_deref(),
+ Some("America/New_York")
+ );
+ assert_eq!(
+ named("/mozilla.org/20050126_1/Europe/Berlin")
+ .unwrap()
+ .name
+ .as_deref(),
+ Some("Europe/Berlin")
+ );
+ assert!(named("Mars/Olympus_Mons").is_none());
+ assert!(named("").is_none());
+ }
+
+ /// Outlook's own export of a meeting in Berlin time: the Windows name, and its rules.
+ const OUTLOOK: &str = "BEGIN:VCALENDAR\r\nPRODID:-//Microsoft Corporation//Outlook 16.0 MIMEDIR//EN\r\nVERSION:2.0\r\nMETHOD:REQUEST\r\nBEGIN:VTIMEZONE\r\nTZID:W. Europe Standard Time\r\nBEGIN:STANDARD\r\nDTSTART:16011028T030000\r\nRRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10\r\nTZOFFSETFROM:+0200\r\nTZOFFSETTO:+0100\r\nEND:STANDARD\r\nBEGIN:DAYLIGHT\r\nDTSTART:16010325T020000\r\nRRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=3\r\nTZOFFSETFROM:+0100\r\nTZOFFSETTO:+0200\r\nEND:DAYLIGHT\r\nEND:VTIMEZONE\r\nEND:VCALENDAR\r\n";
+
+ #[test]
+ fn a_vtimezone_defines_its_own_name() {
+ let defined = Defined::read(OUTLOOK);
+ let z = defined.zone("W. Europe Standard Time").unwrap();
+ assert_eq!(z.name.as_deref(), Some("Europe/Berlin"));
+ assert_eq!(offset_at(&z.tz, "2026-07-15T10:00"), 7_200);
+ assert_eq!(offset_at(&z.tz, "2026-01-15T10:00"), 3_600);
+ // The changes fall where Berlin's do: 29 March and 25 October 2026.
+ assert_eq!(offset_at(&z.tz, "2026-03-29T01:30"), 3_600);
+ assert_eq!(offset_at(&z.tz, "2026-03-29T03:30"), 7_200);
+ assert_eq!(offset_at(&z.tz, "2026-10-25T03:30"), 3_600);
+ }
+
+ /// Outlook's "Customized Time Zone": no name anyone else knows, only its rules — here
+ /// Sydney's, a southern summer that spans the new year, written with Exchange's
+ /// month-day form for "the first Sunday".
+ const CUSTOM: &str = "BEGIN:VCALENDAR\r\nBEGIN:VTIMEZONE\r\nTZID:Customized Time Zone\r\nBEGIN:STANDARD\r\nDTSTART:16010401T030000\r\nRRULE:FREQ=YEARLY;INTERVAL=1;BYMONTH=4;BYMONTHDAY=1,2,3,4,5,6,7;BYDAY=SU\r\nTZOFFSETFROM:+1100\r\nTZOFFSETTO:+1000\r\nEND:STANDARD\r\nBEGIN:DAYLIGHT\r\nDTSTART:16011007T020000\r\nRRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=1SU;BYMONTH=10\r\nTZOFFSETFROM:+1000\r\nTZOFFSETTO:+1100\r\nEND:DAYLIGHT\r\nEND:VTIMEZONE\r\nBEGIN:VTIMEZONE\r\nTZID:(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi\r\nBEGIN:STANDARD\r\nDTSTART:16010101T000000\r\nTZOFFSETFROM:+0530\r\nTZOFFSETTO:+0530\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\nEND:VCALENDAR\r\n";
+
+ #[test]
+ fn a_customized_zone_is_its_rules_and_has_no_name() {
+ let defined = Defined::read(CUSTOM);
+ let sydney = defined.zone("Customized Time Zone").unwrap();
+ assert!(sydney.name.is_none());
+ assert_eq!(offset_at(&sydney.tz, "2026-01-10T09:00"), 39_600);
+ assert_eq!(offset_at(&sydney.tz, "2026-06-10T09:00"), 36_000);
+ // 5 April 2026 and 4 October 2026 are the first Sundays.
+ assert_eq!(offset_at(&sydney.tz, "2026-04-05T03:30"), 36_000);
+ assert_eq!(offset_at(&sydney.tz, "2026-10-04T03:30"), 39_600);
+
+ let india = defined
+ .zone("(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi")
+ .unwrap();
+ assert_eq!(offset_at(&india.tz, "2026-07-01T12:00"), 19_800);
+ assert!(defined.zone("Nowhere Standard Time").is_none());
+ }
+
+ #[test]
+ fn an_iana_name_is_the_zone_databases_even_with_a_vtimezone() {
+ // A VTIMEZONE that claims New York is always UTC-5 does not move a July meeting:
+ // the zone database knows New York.
+ let text = "BEGIN:VTIMEZONE\r\nTZID:America/New_York\r\nBEGIN:STANDARD\r\nDTSTART:19700101T000000\r\nTZOFFSETFROM:-0500\r\nTZOFFSETTO:-0500\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n";
+ let z = Defined::read(text).zone("America/New_York").unwrap();
+ assert_eq!(offset_at(&z.tz, "2026-07-14T09:00"), -4 * 3600);
+ }
+
+ #[test]
+ fn a_zone_that_stopped_changing_keeps_its_last_offset() {
+ // Daylight time ended by an UNTIL, then standard time for good.
+ let text = "BEGIN:VTIMEZONE\r\nTZID:Somewhere\r\nBEGIN:DAYLIGHT\r\nDTSTART:20000326T020000\r\nRRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=3;UNTIL=20100328T010000Z\r\nTZOFFSETFROM:+0300\r\nTZOFFSETTO:+0400\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nDTSTART:20101031T030000\r\nTZOFFSETFROM:+0400\r\nTZOFFSETTO:+0300\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\n";
+ let z = Defined::read(text).zone("Somewhere").unwrap();
+ assert_eq!(offset_at(&z.tz, "2026-07-01T12:00"), 3 * 3600);
+ assert_eq!(offset_at(&z.tz, "2026-01-01T12:00"), 3 * 3600);
+ }
+
+ #[test]
+ fn offsets_and_unreadable_rules() {
+ assert_eq!(offset("+0530"), Some(19_800));
+ assert_eq!(offset("-0330"), Some(-12_600));
+ assert_eq!(offset("+013000"), Some(5_400));
+ assert_eq!(offset("+2500"), None);
+ assert_eq!(offset("+05"), None);
+ assert_eq!(posix_offset(3_600), "-1:00:00");
+ assert_eq!(posix_offset(-12_600), "3:30:00");
+ // A rule POSIX can't say (the second-last Sunday) falls back to the last offset.
+ let text = "BEGIN:VTIMEZONE\r\nTZID:Odd\r\nBEGIN:STANDARD\r\nDTSTART:16011028T030000\r\nRRULE:FREQ=YEARLY;BYDAY=-2SU;BYMONTH=10\r\nTZOFFSETFROM:+0200\r\nTZOFFSETTO:+0100\r\nEND:STANDARD\r\nBEGIN:DAYLIGHT\r\nDTSTART:16010325T020000\r\nRRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=3\r\nTZOFFSETFROM:+0100\r\nTZOFFSETTO:+0200\r\nEND:DAYLIGHT\r\nEND:VTIMEZONE\r\n";
+ assert!(Defined::read(text).zone("Odd").is_some());
+ // Nothing in it at all: not a zone.
+ let empty = "BEGIN:VTIMEZONE\r\nTZID:Empty\r\nEND:VTIMEZONE\r\n";
+ assert!(Defined::read(empty).zone("Empty").is_none());
+ }
+}
diff --git a/src-tauri/src/intake.rs b/src-tauri/src/intake.rs
index c1f1009..72a1326 100644
--- a/src-tauri/src/intake.rs
+++ b/src-tauri/src/intake.rs
@@ -20,6 +20,7 @@ use jiff::civil::{Date, DateTime, Weekday};
use jiff::tz::TimeZone;
use jiff::{Span, Timestamp};
use quince_icloud::calendar::EventRepeat;
+use quince_icloud::zones;
/// Told to a window when something has arrived for it: it asks `intake_pending` for it.
const ARRIVED: &str = "quince://intake";
@@ -562,8 +563,9 @@ enum When {
Floating(DateTime),
/// `…Z`.
Utc(Timestamp),
- /// `TZID=…`: a clock time in that zone, and the zone's own name.
- Zoned(DateTime, TimeZone, String),
+ /// `TZID=…`: a clock time in that zone, and the zone's IANA name — none for a zone only
+ /// the file's own `VTIMEZONE` defines.
+ Zoned(DateTime, TimeZone, Option<String>),
}
impl When {
@@ -617,81 +619,8 @@ fn parse_datetime(s: &str) -> Option<(DateTime, bool)> {
Some((date.to_datetime(time), utc))
}
-/// A `TZID` this computer knows: an IANA name as it stands; one carried inside a longer id
-/// (`/mozilla.org/20050126_1/Europe/Berlin`); or one of the Windows names Outlook writes.
-fn zone_named(tzid: &str) -> Option<(TimeZone, String)> {
- let tzid = tzid.trim().trim_matches('"').trim_start_matches('/');
- let found = |name: &str| {
- TimeZone::get(name)
- .ok()
- .map(|tz| (tz.clone(), tz.iana_name().unwrap_or(name).to_string()))
- };
- if let Some(z) = found(tzid) {
- return Some(z);
- }
- let segments: Vec<&str> = tzid.split('/').collect();
- for start in 1..segments.len() {
- if let Some(z) = found(&segments[start..].join("/")) {
- return Some(z);
- }
- }
- WINDOWS_ZONES
- .iter()
- .find(|(w, _)| w.eq_ignore_ascii_case(tzid))
- .and_then(|(_, iana)| found(iana))
-}
-
-/// Windows' zone names, as Outlook and Exchange write them in a `TZID`, and the IANA zone
-/// each is (CLDR's windowsZones, the territory "001" row).
-const WINDOWS_ZONES: &[(&str, &str)] = &[
- ("UTC", "UTC"),
- ("GMT Standard Time", "Europe/London"),
- ("Greenwich Standard Time", "Atlantic/Reykjavik"),
- ("W. Europe Standard Time", "Europe/Berlin"),
- ("Romance Standard Time", "Europe/Paris"),
- ("Central Europe Standard Time", "Europe/Budapest"),
- ("Central European Standard Time", "Europe/Warsaw"),
- ("E. Europe Standard Time", "Europe/Chisinau"),
- ("FLE Standard Time", "Europe/Kiev"),
- ("GTB Standard Time", "Europe/Bucharest"),
- ("Russian Standard Time", "Europe/Moscow"),
- ("Turkey Standard Time", "Europe/Istanbul"),
- ("Israel Standard Time", "Asia/Jerusalem"),
- ("South Africa Standard Time", "Africa/Johannesburg"),
- ("Egypt Standard Time", "Africa/Cairo"),
- ("Arabian Standard Time", "Asia/Dubai"),
- ("Arab Standard Time", "Asia/Riyadh"),
- ("Pakistan Standard Time", "Asia/Karachi"),
- ("India Standard Time", "Asia/Kolkata"),
- ("Sri Lanka Standard Time", "Asia/Colombo"),
- ("Nepal Standard Time", "Asia/Kathmandu"),
- ("Bangladesh Standard Time", "Asia/Dhaka"),
- ("SE Asia Standard Time", "Asia/Bangkok"),
- ("Singapore Standard Time", "Asia/Singapore"),
- ("China Standard Time", "Asia/Shanghai"),
- ("Taipei Standard Time", "Asia/Taipei"),
- ("Tokyo Standard Time", "Asia/Tokyo"),
- ("Korea Standard Time", "Asia/Seoul"),
- ("AUS Eastern Standard Time", "Australia/Sydney"),
- ("E. Australia Standard Time", "Australia/Brisbane"),
- ("W. Australia Standard Time", "Australia/Perth"),
- ("New Zealand Standard Time", "Pacific/Auckland"),
- ("Hawaiian Standard Time", "Pacific/Honolulu"),
- ("Alaskan Standard Time", "America/Anchorage"),
- ("Pacific Standard Time", "America/Los_Angeles"),
- ("Mountain Standard Time", "America/Denver"),
- ("US Mountain Standard Time", "America/Phoenix"),
- ("Central Standard Time", "America/Chicago"),
- ("Eastern Standard Time", "America/New_York"),
- ("Atlantic Standard Time", "America/Halifax"),
- ("Newfoundland Standard Time", "America/St_Johns"),
- ("E. South America Standard Time", "America/Sao_Paulo"),
- ("Argentina Standard Time", "America/Buenos_Aires"),
- ("Mexico Standard Time", "America/Mexico_City"),
- ("Central Standard Time (Mexico)", "America/Mexico_City"),
-];
-
-fn when(p: &Property) -> Result<When, String> {
+/// A date or time property, its `TZID` read as this file defines it (see [`zones::Defined`]).
+fn when(p: &Property, zones: &zones::Defined) -> Result<When, String> {
let date_only = p
.param("VALUE")
.is_some_and(|v| v.eq_ignore_ascii_case("DATE"))
@@ -711,8 +640,8 @@ fn when(p: &Property) -> Result<When, String> {
}
match p.param("TZID") {
None => Ok(When::Floating(dt)),
- Some(tzid) => match zone_named(tzid) {
- Some((tz, name)) => Ok(When::Zoned(dt, tz, name)),
+ Some(tzid) => match zones.zone(tzid) {
+ Some(zone) => Ok(When::Zoned(dt, zone.tz, zone.name)),
None => Err(format!(
"It uses a time zone this computer doesn’t know ({tzid})."
)),
@@ -769,6 +698,7 @@ pub fn parse_calendar(
.get("METHOD")
.is_some_and(|m| m.value.trim().eq_ignore_ascii_case("CANCEL"));
let here_name = here.iana_name().map(ToString::to_string);
+ let zones = zones::Defined::read(text);
let mut events = Vec::new();
let mut refused = Vec::new();
for c in &calendar.children {
@@ -799,7 +729,7 @@ pub fn parse_calendar(
});
continue;
}
- match event_of(c, here, here_name.as_deref()) {
+ match event_of(c, here, here_name.as_deref(), &zones) {
Ok(event) => events.push(event),
Err(reason) => refused.push(Refused {
title: shown(),
@@ -814,6 +744,7 @@ fn event_of(
c: &Component,
here: &TimeZone,
here_name: Option<&str>,
+ zones: &zones::Defined,
) -> Result<ImportEvent, String> {
if c.get("STATUS")
.is_some_and(|s| s.value.trim().eq_ignore_ascii_case("CANCELLED"))
@@ -826,7 +757,7 @@ fn event_of(
.into(),
);
}
- let start = when(c.get("DTSTART").ok_or("It has no start date.")?)?;
+ let start = when(c.get("DTSTART").ok_or("It has no start date.")?, zones)?;
let all_day = matches!(start, When::Day(_));
let starts_at = start.instant(here).ok_or("Its date can’t be read.")?;
@@ -835,7 +766,7 @@ fn event_of(
unreachable!()
};
let last = match (c.get("DTEND"), c.get("DURATION")) {
- (Some(end), _) => match when(end)? {
+ (Some(end), _) => match when(end, zones)? {
When::Day(d) => d,
other => other.civil(here).date(),
},
@@ -859,7 +790,9 @@ fn event_of(
.ok_or("Its date can’t be read.")?
} else {
match (c.get("DTEND"), c.get("DURATION")) {
- (Some(end), _) => when(end)?.instant(here).ok_or("Its end can’t be read.")?,
+ (Some(end), _) => when(end, zones)?
+ .instant(here)
+ .ok_or("Its end can’t be read.")?,
(None, Some(d)) => {
let secs = duration(&d.value).ok_or("Its length can’t be read.")?;
starts_at
@@ -876,7 +809,9 @@ fn event_of(
let repeat = repeat_of(c, &start, here)?;
let alerts = alerts_of(c, starts_at);
let timezone = match &start {
- When::Zoned(_, _, name) => Some(name.clone()),
+ // A zone only the file defines has no name Apple would know: the instants are its,
+ // and the event is kept on this computer's clock.
+ When::Zoned(_, _, Some(name)) => Some(name.clone()),
_ => here_name.map(ToString::to_string),
};
Ok(ImportEvent {
@@ -1215,6 +1150,26 @@ mod tests {
assert!(refused[0].reason.contains("Mars/Olympus_Mons"));
}
+ /// An Exchange invitation as it arrives by mail: a Windows zone with its VTIMEZONE, and
+ /// Outlook's "Customized Time Zone" that only the file defines. The second was refused as
+ /// a zone this computer doesn't know.
+ #[test]
+ fn an_exchange_invite_and_a_zone_only_the_file_defines() {
+ let (events, refused) = parse_calendar(&sample("exchange.ics"), &kolkata()).unwrap();
+ assert!(refused.is_empty(), "{refused:?}");
+ assert_eq!(events.len(), 2);
+ // 10:00 in Berlin in July is 08:00 UTC; kept in Berlin by its IANA name.
+ assert_eq!(events[0].title, "Budget review");
+ assert_eq!(events[0].starts_at, at("2026-07-15T08:00:00Z"));
+ assert_eq!(events[0].ends_at, at("2026-07-15T09:30:00Z"));
+ assert_eq!(events[0].timezone.as_deref(), Some("Europe/Berlin"));
+ assert_eq!(events[0].alerts, Some(vec![15]));
+ // 09:00 at +05:45 is 03:15 UTC; a zone with no name is kept on this computer's clock.
+ assert_eq!(events[1].starts_at, at("2026-12-01T03:15:00Z"));
+ assert_eq!(events[1].ends_at, at("2026-12-01T03:45:00Z"));
+ assert_eq!(events[1].timezone.as_deref(), Some("Asia/Kolkata"));
+ }
+
#[test]
fn not_a_calendar_and_a_cancellation() {
assert!(parse_calendar("hello", &kolkata()).is_err());
diff --git a/src-tauri/tests/intake/exchange.ics b/src-tauri/tests/intake/exchange.ics
new file mode 100644
index 0000000..1ea03d8
--- /dev/null
+++ b/src-tauri/tests/intake/exchange.ics
@@ -0,0 +1,57 @@
+BEGIN:VCALENDAR
+METHOD:REQUEST
+PRODID:Microsoft Exchange Server 2010
+VERSION:2.0
+BEGIN:VTIMEZONE
+TZID:W. Europe Standard Time
+BEGIN:STANDARD
+DTSTART:16010101T030000
+TZOFFSETFROM:+0200
+TZOFFSETTO:+0100
+RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=-1SU;BYMONTH=10
+END:STANDARD
+BEGIN:DAYLIGHT
+DTSTART:16010101T020000
+TZOFFSETFROM:+0100
+TZOFFSETTO:+0200
+RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=-1SU;BYMONTH=3
+END:DAYLIGHT
+END:VTIMEZONE
+BEGIN:VTIMEZONE
+TZID:Customized Time Zone
+BEGIN:STANDARD
+DTSTART:16010101T000000
+TZOFFSETFROM:+0545
+TZOFFSETTO:+0545
+END:STANDARD
+END:VTIMEZONE
+BEGIN:VEVENT
+ORGANIZER;CN=Anna Weber:mailto:[email protected]
+ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN=You:mailto:[email protected]
+DESCRIPTION;LANGUAGE=en-US:Quarterly numbers.\n
+UID:040000008200E00074C5B7101A82E00800000000A0B1C2D3E4F5A601000000000000000010000000
+SUMMARY;LANGUAGE=en-US:Budget review
+DTSTART;TZID=W. Europe Standard Time:20260715T100000
+DTEND;TZID=W. Europe Standard Time:20260715T113000
+CLASS:PUBLIC
+PRIORITY:5
+DTSTAMP:20260701T120000Z
+TRANSP:OPAQUE
+STATUS:CONFIRMED
+SEQUENCE:0
+LOCATION;LANGUAGE=en-US:Room Spree
+X-MICROSOFT-CDO-BUSYSTATUS:TENTATIVE
+BEGIN:VALARM
+DESCRIPTION:REMINDER
+TRIGGER;RELATED=START:-PT15M
+ACTION:DISPLAY
+END:VALARM
+END:VEVENT
+BEGIN:VEVENT
+UID:custom-zone-1
+SUMMARY:Call with Kathmandu
+DTSTART;TZID=Customized Time Zone:20261201T090000
+DTEND;TZID=Customized Time Zone:20261201T093000
+DTSTAMP:20261101T120000Z
+END:VEVENT
+END:VCALENDAR