//! 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.usecrate::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)]pubenumWhen {/// 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)]pubstructEvent {pub uid: String,pub title: String,pub notes: Option<String>,pub place: Option<String>,pub start: Option<When>,pub end: Option<When>,/// The rule as the store keeps it (`FREQ=WEEKLY;BYDAY=MO`), no `RRULE:`.pub rule: Option<String>,pub taken_out: Vec<When>,/// For a changed occurrence: the start it replaces.pub replaces: Option<When>,pub made: Option<i64>,}/// Where a to-do stands.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]pubenumStatus { #[default]Open,Done,Dropped,}/// One to-do.#[derive(Debug, Clone, Default, PartialEq, Eq)]pubstructTodo {pub uid: String,pub title: String,pub details: Option<String>,pub due: Option<When>,pub status: Status,pub done_at: Option<i64>,pub groups: Vec<String>,pub made: Option<i64>,}/// The whole file: `name` is the calendar's (`X-WR-CALNAME`), `now` the/// instant every entry is stamped with (`DTSTAMP`).pubfn calendar(name: &str, events: &[Event], todos: &[Todo], now: i64) -> String {letmut 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}"));ifletSome(made) = event.made { out.push(format!("CREATED:{}", utc(made))); }ifletSome(replaces) = &event.replaces { out.push(property("RECURRENCE-ID", replaces)); }ifletSome(start) = &event.start { out.push(property("DTSTART", start)); }ifletSome(end) = &event.end { out.push(property("DTEND", end)); }ifletSome(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)));ifletSome(notes) = event.notes.as_deref().filter(|n| !n.trim().is_empty()) { out.push(format!("DESCRIPTION:{}", text(notes))); }ifletSome(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}"));ifletSome(made) = todo.made { out.push(format!("CREATED:{}", utc(made))); } out.push(format!("SUMMARY:{}", text(&todo.title)));ifletSome(details) = todo.details.as_deref().filter(|d| !d.trim().is_empty()) { out.push(format!("DESCRIPTION:{}", text(details))); }ifletSome(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 {ifletSome(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::<Vec<_>>().join(","))); } out.push("END:VTODO".to_string()); } out.push("END:VCALENDAR".to_string());letmut 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 {letmut 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: &mutString) {letmut 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;