1use crate::accessibility::Role;
16use crate::color::Color;
17use crate::event::{Key, Mods};
18use crate::geom::Rect;
19use crate::id::Id;
20use crate::layout::Align;
21use crate::ui::{Icon, Response, Ui};
22use crate::widgets::{Before, DOWN, RIGHT};
23#[cfg(unix)]
24use std::ffi::{c_int, c_long};
25use std::fmt::Write;
26
27const LEFT: Icon = Icon::line("M9.5 4 5.5 8 9.5 12");
28const NUMBERS: [&str; 31] =
30 ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"];
31const DAY: [f32; 2] = [30.0, 26.0];
33
34#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
36pub struct Date {
37 pub year: i32,
39 pub month: u8,
41 pub day: u8,
43}
44
45impl Date {
46 pub const fn new(year: i32, month: u8, day: u8) -> Self {
48 Date { year, month, day }
49 }
50
51 pub fn days(self) -> i64 {
53 let year = self.year as i64 - (self.month <= 2) as i64;
56 let (era, month) = (year.div_euclid(400), (self.month as i64 + 9) % 12);
57 let of_year = (153 * month + 2) / 5 + self.day as i64 - 1;
58 let of_era = year.rem_euclid(400) * 365 + year.rem_euclid(400) / 4 - year.rem_euclid(400) / 100 + of_year;
59 era * 146_097 + of_era - 719_468
60 }
61 pub fn from_days(days: i64) -> Self {
63 let shifted = days.saturating_add(719_468);
64 let (era, of_era) = (shifted.div_euclid(146_097), shifted.rem_euclid(146_097));
65 let year_of_era = (of_era - of_era / 1460 + of_era / 36_524 - of_era / 146_096) / 365;
66 let of_year = of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
67 let month = (5 * of_year + 2) / 153;
68 let (day, month) = (of_year - (153 * month + 2) / 5 + 1, (month + 2) % 12 + 1);
69 let year = (year_of_era + era * 400 + (month <= 2) as i64).clamp(i32::MIN as i64, i32::MAX as i64) as i32;
70 Date { year, month: month as u8, day: day as u8 }
71 }
72 pub fn weekday(self) -> u8 {
74 (self.days() + 3).rem_euclid(7) as u8
75 }
76 pub fn month_length(self) -> u8 {
78 let leap = self.year % 4 == 0 && (self.year % 100 != 0 || self.year % 400 == 0);
79 match self.month {
80 2 if leap => 29,
81 2 => 28,
82 4 | 6 | 9 | 11 => 30,
83 _ => 31,
84 }
85 }
86 pub fn add_months(self, months: i32) -> Self {
89 let counted = self.year as i64 * 12 + self.month as i64 - 1 + months as i64;
90 let year = counted.div_euclid(12).clamp(i32::MIN as i64, i32::MAX as i64) as i32;
91 let first = Date::new(year, counted.rem_euclid(12) as u8 + 1, 1);
92 Date { day: self.day.min(first.month_length()), ..first }
93 }
94 pub fn today() -> Self {
96 let [year, month, day, ..] = local_now();
97 Date::new(year, month as u8, day as u8)
98 }
99}
100
101impl Default for Date {
103 fn default() -> Self {
104 Date::new(1970, 1, 1)
105 }
106}
107
108impl std::fmt::Display for Date {
111 fn fmt(&self, to: &mut std::fmt::Formatter) -> std::fmt::Result {
112 write!(to, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
113 }
114}
115
116#[cfg(windows)]
118pub(crate) fn local_now() -> [i32; 6] {
119 crate::windows::local_time().map(i32::from)
120}
121
122#[cfg(unix)]
124#[repr(C)]
125struct Moment {
126 second: c_int,
127 minute: c_int,
128 hour: c_int,
129 day: c_int,
130 month: c_int,
131 year: c_int,
132 rest: [c_int; 3],
133 ahead: c_long,
134 zone: *const u8,
135}
136
137#[cfg(unix)]
139type Seconds = c_long;
140
141#[cfg(unix)]
142unsafe extern "C" {
143 fn time(into: *mut Seconds) -> Seconds;
144 fn localtime_r(time: *const Seconds, into: *mut Moment) -> *mut Moment;
145}
146
147#[cfg(unix)]
148pub(crate) fn local_now() -> [i32; 6] {
149 let mut moment = Moment { second: 0, minute: 0, hour: 0, day: 1, month: 0, year: 70, rest: [0; 3], ahead: 0, zone: std::ptr::null() };
150 unsafe { localtime_r(&time(std::ptr::null_mut()), &mut moment) };
152 [moment.year + 1900, moment.month + 1, moment.day, moment.hour, moment.minute, moment.second]
153}
154
155#[cfg(not(any(windows, unix)))]
157pub(crate) fn local_now() -> [i32; 6] {
158 #[cfg(target_family = "wasm")]
159 let since = (crate::web_host::unix_seconds() as i64 + crate::web_host::zone_ahead()).max(0) as u64;
160 #[cfg(not(target_family = "wasm"))]
161 let since = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |since| since.as_secs());
162 let (day, of_day) = (Date::from_days((since / 86_400) as i64), (since % 86_400) as i32);
163 [day.year, day.month as i32, day.day as i32, of_day / 3600, of_day / 60 % 60, of_day % 60]
164}
165
166pub(crate) fn ahead_of_greenwich(at: i64) -> i64 {
169 ahead(at)
170}
171
172#[cfg(unix)]
173fn ahead(at: i64) -> i64 {
174 let mut moment = Moment { second: 0, minute: 0, hour: 0, day: 1, month: 0, year: 70, rest: [0; 3], ahead: 0, zone: std::ptr::null() };
175 unsafe { localtime_r(&at, &mut moment) };
177 moment.ahead
178}
179
180#[cfg(windows)]
181#[link(name = "kernel32")]
182unsafe extern "system" {
183 fn GetLocalTime(time: *mut [u16; 8]);
184}
185
186#[cfg(windows)]
188fn ahead(_at: i64) -> i64 {
189 let mut time = [0u16; 8];
190 unsafe { GetLocalTime(&mut time) };
192 let here = Date::new(time[0] as i32, time[1] as u8, time[3] as u8).days() * 86_400 + time[4] as i64 * 3600 + time[5] as i64 * 60 + time[6] as i64;
193 let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |since| since.as_secs() as i64);
194 ((here - now) as f64 / 900.0).round() as i64 * 900
196}
197
198#[cfg(not(any(windows, unix)))]
199fn ahead(_at: i64) -> i64 {
200 #[cfg(target_family = "wasm")]
201 return crate::web_host::zone_ahead();
202 #[allow(unreachable_code)]
203 0
204}
205
206#[derive(Clone, Copy, Debug, PartialEq)]
211pub struct CalendarWords {
212 pub months: [&'static str; 12],
214 pub days: [&'static str; 7],
216 pub halves: [&'static str; 2],
218 pub clock: [&'static str; 4],
220 pub arrows: [&'static str; 2],
222}
223
224impl Default for CalendarWords {
225 fn default() -> Self {
226 CalendarWords {
227 months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
228 days: ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
229 halves: ["AM", "PM"],
230 clock: ["Hours", "Minutes", "Seconds", "AM or PM"],
231 arrows: ["The month before", "The month after"],
232 }
233 }
234}
235
236#[derive(Clone, Copy, Default)]
239pub(crate) struct Shown {
240 of: Id,
241 month: (i32, u8),
242 first: Option<Date>,
243 pointed: Option<Date>,
244}
245
246impl Ui {
248 pub fn date(&mut self, date: &mut Date) -> Response {
250 let mut written = std::mem::take(&mut self.scratch);
251 written.clear();
252 self.formats().write_date(&mut written, *date);
253 let mut state = self.opens_calendar(&written);
254 self.scratch = written;
255 if let Some(day) = self.calendar(state.id, [*date; 2]) {
256 (state.changed, *date) = (day != *date, day);
257 self.close_popup();
258 }
259 state
260 }
261
262 pub fn date_range(&mut self, from: &mut Date, to: &mut Date) -> Response {
267 let (mut written, locale) = (std::mem::take(&mut self.scratch), self.formats());
268 written.clear();
269 locale.write_date(&mut written, *from);
270 written.push_str(" \u{2013} ");
271 locale.write_date(&mut written, *to);
272 let mut state = self.opens_calendar(&written);
273 self.scratch = written;
274 let Some(day) = self.calendar(state.id, [*from, *to]) else { return state };
275 let Some(first) = self.calendar_open.first else {
276 self.calendar_open.first = Some(day);
277 return state;
278 };
279 state.changed = (first.min(day), first.max(day)) != (*from, *to);
280 (*from, *to) = (first.min(day), first.max(day));
281 self.close_popup();
282 state
283 }
284
285 fn opens_calendar(&mut self, written: &str) -> Response {
288 let state = self.button_like(Before::None, written, Some(DOWN), false);
289 if state.clicked {
290 self.open_calendar(state.id, state.rect);
291 }
292 let open = self.popups.iter().any(|popup| popup.id == state.id);
293 self.tell(&state, Role::Fold, Some(open), "");
294 state
295 }
296
297 pub(crate) fn open_calendar(&mut self, of: Id, under: Rect) {
299 self.open_popup(of, under);
300 self.calendar_open.of = 0;
301 }
302
303 pub(crate) fn calendar(&mut self, of: Id, picked: [Date; 2]) -> Option<Date> {
307 if !self.popup(of) {
308 return None;
309 }
310 let t = self.theme;
311 let fresh = self.calendar_open.of != of;
312 if fresh {
313 self.calendar_open = Shown { of, month: (picked[0].year, picked[0].month), ..Shown::default() };
314 }
315 let [wide, high] = self.popup_most();
317 self.column().pad(8.0).gap(6.0).max(wide, high).scroll().scroll_x().fill(t.raised).border(t.line_strong, 1.0).radius(8.0).shadow(16.0).sense().open();
318 let first = self.calendar_month_row();
319 self.grid(7).gap(2.0).open();
320 if fresh {
323 self.set_focus(self.id(picked[0].days()));
324 }
325 self.calendar_keys(first);
326 let size = self.day_size();
327 self.calendar_weekdays(first, size);
328 let pressed = self.calendar_days(first, picked, size);
329 self.close();
330 self.close();
331 pressed
332 }
333
334 fn calendar_month_row(&mut self) -> Date {
337 let (t, words, (year, month)) = (self.theme, self.calendar_words_in_use(), self.calendar_open.month);
338 self.row().gap(6.0).open();
339 let back = self.button_like(Before::Icon(LEFT), "", None, false);
340 self.tell(&back, Role::Button, None, words.arrows[0]);
341 self.spacer();
342 self.text(words.months[(month as usize + 11) % 12], t.font.bold(), t.text);
343 self.year_label(year);
344 self.spacer();
345 let on = self.button_like(Before::Icon(RIGHT), "", None, false);
346 self.tell(&on, Role::Button, None, words.arrows[1]);
347 self.close();
348 let (back, on) = (back.clicked, on.clicked);
349 let first = Date::new(year, month, 1).add_months(on as i32 - back as i32);
350 self.calendar_open.month = (first.year, first.month);
351 self.again |= on || back;
352 first
353 }
354
355 fn calendar_weekdays(&mut self, first: Date, size: [f32; 2]) {
358 let (t, words, first_day) = (self.theme, self.calendar_words_in_use(), self.locale_in_use().first_weekday);
359 let heading = 18f32.max(self.text.metrics(t.small_font, self.scale).height().ceil() + 2.0);
360 for day in 0..7 {
361 self.el().size(size[0], heading).text(words.days[(day + first_day as usize) % 7], t.small_font, t.text_faint).text_align(Align::Center).show();
362 }
363 for _ in 0..(first.weekday() + 7 - first_day % 7) % 7 {
364 self.el().size(size[0], size[1]).show();
365 }
366 }
367
368 fn calendar_days(&mut self, first: Date, picked: [Date; 2], size: [f32; 2]) -> Option<Date> {
370 let shown = match (self.calendar_open.first, self.calendar_open.pointed) {
372 (Some(start), Some(end)) => [start.min(end), start.max(end)],
373 (Some(start), None) => [start; 2],
374 (None, _) => picked,
375 };
376 let (today, mut pressed, mut hovered, mut keyed) = (Date::today(), None, None, None);
377 for day in (1..=first.month_length()).map(|day| Date::new(first.year, first.month, day)) {
378 let state = self.calendar_day(day, shown, today, size);
379 pressed = pressed.or(state.clicked.then_some(day));
380 (hovered, keyed) = (hovered.or(state.hovered.then_some(day)), keyed.or(state.focused.then_some(day)));
381 }
382 let pointed = hovered.or(keyed);
384 let half_picked = self.calendar_open.first.is_some();
385 self.again |= half_picked && std::mem::replace(&mut self.calendar_open.pointed, pointed) != pointed;
386 pressed
387 }
388
389 fn calendar_keys(&mut self, first: Date) {
392 let mut days = (0..first.month_length() as i64).map(|day| Date::from_days(first.days() + day));
393 let Some(on) = days.find(|day| self.id(day.days()) == self.focus) else { return };
394 let into_week = (on.weekday() as i64 - self.locale_in_use().first_weekday as i64).rem_euclid(7);
396 let mut key = |key: Key, mods: Mods| self.key(key, mods) as i64;
397 let along = key(Key::Right, Mods::NONE) - key(Key::Left, Mods::NONE) + 7 * (key(Key::Down, Mods::NONE) - key(Key::Up, Mods::NONE));
398 let months = key(Key::PageDown, Mods::NONE) - key(Key::PageUp, Mods::NONE) + 12 * (key(Key::PageDown, Mods::SHIFT) - key(Key::PageUp, Mods::SHIFT));
399 let ends = (6 - into_week) * key(Key::End, Mods::NONE) - into_week * key(Key::Home, Mods::NONE);
400 let to = Date::from_days(on.add_months(months as i32).days() + along + ends);
401 if to != on {
402 self.calendar_open.month = (to.year, to.month);
403 self.set_focus(self.id(to.days()));
404 }
405 }
406
407 pub(crate) fn line_part(&mut self) -> f32 {
409 self.theme.control_height.max(self.text.metrics(self.theme.font, self.scale).height().ceil() + 8.0)
410 }
411 fn day_size(&mut self) -> [f32; 2] {
413 let (font, wide) = (self.theme.font, self.text_width("30", self.theme.font));
414 [DAY[0].max(wide.ceil() + 10.0), DAY[1].max(self.text.metrics(font, self.scale).height().ceil() + 6.0)]
415 }
416
417 fn year_label(&mut self, year: i32) {
419 let (t, mut written) = (self.theme, std::mem::take(&mut self.scratch));
420 written.clear();
421 let _ = write!(written, "{year}");
422 self.text(&written, t.font.bold(), t.text_dim);
423 self.scratch = written;
424 }
425
426 fn calendar_day(&mut self, day: Date, [start, end]: [Date; 2], today: Date, [wide, high]: [f32; 2]) -> Response {
430 let t = self.theme;
431 let state = self.press(self.id(day.days()));
432 let (ends, within) = (day == start || day == end, start < day && day < end);
433 let (fill, ink) = match (ends, within, state.hovered || state.focused) {
434 (true, ..) => (t.accent, t.on_accent),
435 (false, _, true) => (t.hover, t.text),
436 (false, true, false) => (t.selected, t.text),
437 (false, false, false) => (Color::NONE, t.text),
438 };
439 let edge = match (ends && state.focused, day == today) {
442 (true, _) => t.on_accent,
443 (false, true) => t.accent,
444 (false, false) => Color::NONE,
445 };
446 let cell = self.el().key(day.days()).size(wide, high).text(NUMBERS[day.day as usize - 1], t.font, ink).text_align(Align::Center);
447 cell.fill(fill).border(edge, 1.0).radius(5.0).sense().focusable().show();
448 if self.listening {
449 let name = format!("{} {} {}", day.day, self.calendar_words_in_use().months[day.month as usize - 1], day.year);
450 self.tell(&state, Role::Row, Some(ends || within), &name);
451 self.tell_position(day.day as usize, day.month_length() as usize);
452 }
453 state
454 }
455}
456
457#[cfg(test)]
458mod tests {
459 use super::*;
460
461 #[test]
462 fn days_are_counted_and_named_right() {
463 assert_eq!(Date::new(1970, 1, 1).days(), 0);
464 assert_eq!(Date::new(1970, 1, 1).weekday(), 3, "a Thursday");
465 assert_eq!(Date::new(2026, 11, 11).weekday(), 2, "a Wednesday");
466 assert_eq!(Date::new(2000, 2, 29).days() + 1, Date::new(2000, 3, 1).days(), "2000 was a leap year");
467 assert_eq!([Date::new(2024, 2, 1).month_length(), Date::new(2023, 2, 1).month_length(), Date::new(1900, 2, 1).month_length()], [29, 28, 28]);
468 assert_eq!([Date::new(2026, 12, 5).month_length(), Date::new(2026, 4, 30).month_length()], [31, 30]);
469 assert_eq!(Date::new(2026, 3, 7).to_string(), "2026-03-07");
470 assert!(Date::new(2026, 3, 7) < Date::new(2026, 11, 1));
471 }
472
473 #[test]
474 fn a_month_on_or_back_keeps_the_day_where_the_month_has_it() {
475 let last = Date::new(2026, 1, 31);
476 assert_eq!(
477 [last.add_months(1), last.add_months(2), last.add_months(-2), last.add_months(13)],
478 [Date::new(2026, 2, 28), Date::new(2026, 3, 31), Date::new(2025, 11, 30), Date::new(2027, 2, 28)]
479 );
480 assert_eq!(Date::new(2024, 2, 29).add_months(-12), Date::new(2023, 2, 28));
481 assert_eq!(Date::new(2026, 11, 13).add_months(0), Date::new(2026, 11, 13));
482 }
483
484 #[test]
485 fn every_day_for_eight_hundred_years_comes_back_as_itself() {
486 let mut day = Date::new(1600, 1, 1);
487 for days in day.days()..Date::new(2400, 1, 1).days() {
488 assert_eq!(Date::from_days(days), day);
489 assert_eq!(day.days(), days);
490 let last = day.day == day.month_length();
491 day = match (last, day.month) {
492 (false, _) => Date::new(day.year, day.month, day.day + 1),
493 (true, 12) => Date::new(day.year + 1, 1, 1),
494 (true, _) => Date::new(day.year, day.month + 1, 1),
495 };
496 }
497 }
498}