//! An iCalendar file (RFC 5545), written: Days' events and to-dos as one //! `.ics` another calendar app opens (owner, 23 Nov 2026: export, promised on //! the website for launch; `assets/design/days/CONTRACT.md` "Export"). //! //! Pure: the phone's `days.export` reads the rows and hands them here; this //! writes the text. What it keeps of each: //! //! - an **event**: its title, notes, place, start and end (an all-day event as //! dates, its end the day after its last; a timed one at its instant in UTC, //! or, when it repeats, at its clock in its zone so the repeats keep their //! hour across a clock change), its rule, the dates taken out of it, and a //! changed occurrence as its own VEVENT under the series' UID with the //! RECURRENCE-ID it replaces; //! - a **to-do**: its title, details, when it is due (a day, or an instant), //! whether it is done and when, and its group as a CATEGORY. //! //! The reader is [`crate::import::ical`]; the tests read every file written //! here back through it. use crate::cotton_rules::zoned_clock::{civil_from_days, zoned_parts}; /// When something is: a calendar day, an instant, or an instant read at its /// clock in a named zone. #[derive(Debug, Clone, PartialEq, Eq)] pub enum When { /// A day with no time: days since 1970-01-01. Day(i64), /// An instant, written in UTC. Instant(i64), /// An instant written as its clock in `zone` (`TZID=`). Zoned { ms: i64, zone: String }, } /// One event (or one changed occurrence of a series). #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Event { pub uid: String, pub title: String, pub notes: Option, pub place: Option, pub start: Option, pub end: Option, /// The rule as the store keeps it (`FREQ=WEEKLY;BYDAY=MO`), no `RRULE:`. pub rule: Option, pub taken_out: Vec, /// For a changed occurrence: the start it replaces. pub replaces: Option, pub made: Option, } /// Where a to-do stands. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum Status { #[default] Open, Done, Dropped, } /// One to-do. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Todo { pub uid: String, pub title: String, pub details: Option, pub due: Option, pub status: Status, pub done_at: Option, pub groups: Vec, pub made: Option, } /// The whole file: `name` is the calendar's (`X-WR-CALNAME`), `now` the /// instant every entry is stamped with (`DTSTAMP`). pub fn calendar(name: &str, events: &[Event], todos: &[Todo], now: i64) -> String { let mut out = Vec::new(); out.push("BEGIN:VCALENDAR".to_string()); out.push("VERSION:2.0".to_string()); out.push("PRODID:-//Cotton//Days//EN".to_string()); out.push("CALSCALE:GREGORIAN".to_string()); out.push(format!("X-WR-CALNAME:{}", text(name))); let stamp = utc(now); for event in events { out.push("BEGIN:VEVENT".to_string()); out.push(format!("UID:{}", text(&event.uid))); out.push(format!("DTSTAMP:{stamp}")); if let Some(made) = event.made { out.push(format!("CREATED:{}", utc(made))); } if let Some(replaces) = &event.replaces { out.push(property("RECURRENCE-ID", replaces)); } if let Some(start) = &event.start { out.push(property("DTSTART", start)); } if let Some(end) = &event.end { out.push(property("DTEND", end)); } if let Some(rule) = event.rule.as_deref().map(str::trim).filter(|r| !r.is_empty()) { out.push(format!("RRULE:{}", rule.trim_start_matches("RRULE:"))); } for out_of in &event.taken_out { out.push(property("EXDATE", out_of)); } out.push(format!("SUMMARY:{}", text(&event.title))); if let Some(notes) = event.notes.as_deref().filter(|n| !n.trim().is_empty()) { out.push(format!("DESCRIPTION:{}", text(notes))); } if let Some(place) = event.place.as_deref().filter(|p| !p.trim().is_empty()) { out.push(format!("LOCATION:{}", text(place))); } out.push("END:VEVENT".to_string()); } for todo in todos { out.push("BEGIN:VTODO".to_string()); out.push(format!("UID:{}", text(&todo.uid))); out.push(format!("DTSTAMP:{stamp}")); if let Some(made) = todo.made { out.push(format!("CREATED:{}", utc(made))); } out.push(format!("SUMMARY:{}", text(&todo.title))); if let Some(details) = todo.details.as_deref().filter(|d| !d.trim().is_empty()) { out.push(format!("DESCRIPTION:{}", text(details))); } if let Some(due) = &todo.due { out.push(property("DUE", due)); } out.push( match todo.status { Status::Open => "STATUS:NEEDS-ACTION", Status::Done => "STATUS:COMPLETED", Status::Dropped => "STATUS:CANCELLED", } .to_string(), ); if todo.status == Status::Done { if let Some(done) = todo.done_at { out.push(format!("COMPLETED:{}", utc(done))); } } if !todo.groups.is_empty() { out.push(format!("CATEGORIES:{}", todo.groups.iter().map(|g| text(g)).collect::>().join(","))); } out.push("END:VTODO".to_string()); } out.push("END:VCALENDAR".to_string()); let mut file = String::new(); for line in out { fold(&line, &mut file); } file } /// `NAME:value`, `NAME;VALUE=DATE:value` or `NAME;TZID=zone:value`. fn property(name: &str, when: &When) -> String { match when { When::Day(day) => format!("{name};VALUE=DATE:{}", date(*day)), When::Instant(ms) => format!("{name}:{}", utc(*ms)), When::Zoned { ms, zone } => match zoned_parts(*ms, zone) { Ok(p) => format!("{name};TZID={zone}:{:04}{:02}{:02}T{:02}{:02}{:02}", p.year, p.month, p.day, p.hour, p.minute, p.second), // A zone this phone cannot read: the instant itself, which is never wrong. Err(_) => format!("{name}:{}", utc(*ms)), }, } } fn date(day: i64) -> String { let (year, month, date) = civil_from_days(day); format!("{year:04}{month:02}{date:02}") } fn utc(ms: i64) -> String { match zoned_parts(ms, "UTC") { Ok(p) => format!("{:04}{:02}{:02}T{:02}{:02}{:02}Z", p.year, p.month, p.day, p.hour, p.minute, p.second), Err(_) => "19700101T000000Z".to_string(), } } /// A TEXT value, escaped (RFC 5545 3.3.11). fn text(value: &str) -> String { let mut out = String::with_capacity(value.len()); for c in value.replace("\r\n", "\n").chars() { match c { '\\' => out.push_str("\\\\"), ';' => out.push_str("\\;"), ',' => out.push_str("\\,"), '\n' => out.push_str("\\n"), '\r' => {} c => out.push(c), } } out } /// One content line, folded at 75 octets without splitting a character, each /// ending CRLF (RFC 5545 3.1). fn fold(line: &str, out: &mut String) { let mut width = 0; for c in line.chars() { let len = c.len_utf8(); if width + len > 75 { out.push_str("\r\n "); width = 1; } out.push(c); width += len; } out.push_str("\r\n"); } #[cfg(test)] #[path = "ics_tests.rs"] mod tests;