1use core::fmt::{self, Write};
6
7use crate::data::{LogicalIndex, TimeIndex, Timestamp};
8use crate::error::{Error, Result};
9use crate::geom::Px;
10
11const DAY_MS: i64 = 86_400_000;
12
13pub trait TimeZoneProvider: Send {
26 fn offset_ms(&self, utc: Timestamp) -> i64;
28}
29
30#[derive(Clone, Copy, Debug, Default)]
32pub struct Utc;
33
34impl TimeZoneProvider for Utc {
35 fn offset_ms(&self, _: Timestamp) -> i64 {
36 0
37 }
38}
39
40#[derive(Clone, Copy, Debug, Default)]
42pub struct FixedOffset(pub i64);
43
44impl TimeZoneProvider for FixedOffset {
45 fn offset_ms(&self, _: Timestamp) -> i64 {
46 self.0
47 }
48}
49
50pub fn civil_from_days(days: i64) -> (i64, u32, u32) {
63 let z = days + 719_468;
64 let era = z.div_euclid(146_097);
65 let doe = z.rem_euclid(146_097); let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let d = doy - (153 * mp + 2) / 5 + 1; let m = if mp < 10 { mp + 3 } else { mp - 9 }; let y = yoe + era * 400 + i64::from(m <= 2);
72 (y, m as u32, d as u32)
73}
74
75#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
85pub enum TickWeight {
86 Second,
88 Minute,
90 Min5,
92 Min15,
94 Min30,
96 Hour,
98 Day,
100 Month,
102 Year,
104}
105
106const WEIGHTS_DESC: [TickWeight; 9] = [
107 TickWeight::Year,
108 TickWeight::Month,
109 TickWeight::Day,
110 TickWeight::Hour,
111 TickWeight::Min30,
112 TickWeight::Min15,
113 TickWeight::Min5,
114 TickWeight::Minute,
115 TickWeight::Second,
116];
117
118fn unit(t: i64, weight: TickWeight) -> i64 {
120 let slot = |ms: i64| t.div_euclid(ms);
121 match weight {
122 TickWeight::Year => civil_from_days(t.div_euclid(DAY_MS)).0,
123 TickWeight::Month => {
124 let (y, m, _) = civil_from_days(t.div_euclid(DAY_MS));
125 y * 12 + i64::from(m)
126 }
127 TickWeight::Day => slot(DAY_MS),
128 TickWeight::Hour => slot(3_600_000),
129 TickWeight::Min30 => slot(1_800_000),
130 TickWeight::Min15 => slot(900_000),
131 TickWeight::Min5 => slot(300_000),
132 TickWeight::Minute => slot(60_000),
133 TickWeight::Second => slot(1000),
134 }
135}
136
137pub fn weight_between(a: i64, b: i64) -> TickWeight {
149 WEIGHTS_DESC
150 .into_iter()
151 .find(|&w| unit(a, w) != unit(b, w))
152 .unwrap_or(TickWeight::Second)
153}
154
155const MONTHS: [&str; 12] = [
156 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
157];
158
159pub fn format_tick(t: i64, weight: TickWeight, out: &mut impl Write) -> fmt::Result {
178 let (y, m, d) = civil_from_days(t.div_euclid(DAY_MS));
179 let ms = t.rem_euclid(DAY_MS);
180 let (hh, mm, ss) = (ms / 3_600_000, ms / 60_000 % 60, ms / 1000 % 60);
181 match weight {
182 TickWeight::Year => write!(out, "{y}"),
183 TickWeight::Month => out.write_str(MONTHS[(m as usize).saturating_sub(1) % 12]),
184 TickWeight::Day => write!(out, "{d}"),
185 TickWeight::Second => write!(out, "{hh:02}:{mm:02}:{ss:02}"),
186 _ => write!(out, "{hh:02}:{mm:02}"),
187 }
188}
189
190pub fn format_crosshair_time(t: i64, out: &mut impl Write) -> fmt::Result {
208 let (y, m, d) = civil_from_days(t.div_euclid(DAY_MS));
209 let ms = t.rem_euclid(DAY_MS);
210 write!(out, "{y:04}-{m:02}-{d:02}")?;
211 if ms != 0 {
212 write!(out, " {:02}:{:02}", ms / 3_600_000, ms / 60_000 % 60)?;
213 }
214 Ok(())
215}
216
217fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
220 let y = if m <= 2 { y - 1 } else { y };
221 let era = y.div_euclid(400);
222 let yoe = y.rem_euclid(400);
223 let m = i64::from(m);
224 let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + i64::from(d) - 1;
225 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
226 era * 146_097 + doe - 719_468
227}
228
229const TIME_STEPS: [i64; 31] = [
231 1000,
232 2000,
233 5000,
234 10_000,
235 15_000,
236 30_000, 60_000,
238 120_000,
239 300_000,
240 600_000,
241 900_000,
242 1_800_000, 3_600_000,
244 7_200_000,
245 10_800_000,
246 21_600_000,
247 43_200_000, DAY_MS,
249 2 * DAY_MS,
250 7 * DAY_MS,
251 14 * DAY_MS, -1,
253 -2,
254 -3,
255 -6, -12,
257 -24,
258 -60,
259 -120,
260 -240,
261 -600, ];
263
264pub fn time_ticks(
283 lo: i64,
284 hi: i64,
285 length: f64,
286 min_spacing: f64,
287 out: &mut Vec<(i64, TickWeight)>,
288) {
289 out.clear();
290 if lo >= hi || length <= 0.0 || min_spacing <= 0.0 {
291 return;
292 }
293 let max_ticks = (length / min_spacing).floor().max(1.0);
294 let span = (hi - lo) as f64;
295 let step = TIME_STEPS
296 .into_iter()
297 .find(|&s| {
298 let ms = if s > 0 {
299 s as f64
300 } else {
301 -s as f64 * 30.44 * DAY_MS as f64
302 };
303 span / ms <= max_ticks
304 })
305 .unwrap_or(-1200);
306 let mut push = |t: i64| {
307 if out.len() < 1000 && (out.len() < out.capacity() || out.try_reserve(1).is_ok()) {
308 out.push((t, weight_between(t - 1, t)));
309 }
310 };
311 if step > 0 {
312 let mut t = lo.div_euclid(step) * step;
313 if t < lo {
314 t += step;
315 }
316 while t <= hi {
317 push(t);
318 t += step;
319 }
320 } else {
321 let months = -step;
322 let (y, m, _) = civil_from_days(lo.div_euclid(DAY_MS));
323 let mut k = (y * 12 + i64::from(m) - 1).div_euclid(months) * months;
324 loop {
325 let t = days_from_civil(k.div_euclid(12), (k.rem_euclid(12) + 1) as u32, 1) * DAY_MS;
326 if t > hi {
327 break;
328 }
329 if t >= lo {
330 push(t);
331 }
332 k += months;
333 }
334 }
335}
336
337#[derive(Clone, Copy, Debug, PartialEq)]
339pub(crate) struct TimeTick {
340 pub index: i64,
341 pub weight: TickWeight,
342}
343
344pub(crate) fn collect_ticks(
350 index: &TimeIndex,
351 tz: &dyn TimeZoneProvider,
352 from: i64,
353 to: i64,
354 shift: u32,
355 out: &mut Vec<TimeTick>,
356) {
357 out.clear();
358 let first = index.first_index();
359 let last = index.end_index() - 1;
360 let local = |i: i64| index.time_at(i).map(|t| t + tz.offset_ms(t));
361 let stride = 1_i64 << shift;
362 let lo = from.max(first + 1);
363 let hi = to.min(last);
364 if lo > hi {
365 return;
366 }
367 let anchor = crate::data::ANCHOR;
368 let mut j = anchor + (((lo - anchor) + stride - 1) >> shift << shift);
369 while j <= hi {
370 let prev = (j - stride).max(first);
371 if let (Some(tp), Some(tj)) = (local(prev), local(j)) {
372 let w = weight_between(tp, tj);
373 let up = unit(tp, w);
374 let (mut a, mut b) = (prev + 1, j);
376 while a < b {
377 let mid = a + (b - a) / 2;
378 if local(mid).is_some_and(|t| unit(t, w) != up) {
379 b = mid;
380 } else {
381 a = mid + 1;
382 }
383 }
384 if out.len() < out.capacity() || out.try_reserve(1).is_ok() {
385 out.push(TimeTick {
386 index: a,
387 weight: w,
388 });
389 }
390 }
391 j += stride;
392 }
393}
394
395#[derive(Clone, Debug)]
413pub struct TimeScale {
414 bar_spacing: f64,
415 right_offset: f64,
416 min_spacing: f64,
417 max_spacing: f64,
418 width: f64,
419 first: i64,
420 last: i64,
421 bars: usize,
422 pending: Option<Pending>,
423 pub(crate) changed: bool,
424}
425
426#[derive(Clone, Copy, Debug)]
431enum Pending {
432 Fit,
434 Span { from: f64, to: f64 },
436}
437
438impl TimeScale {
439 pub(crate) fn new(bar_spacing: f64, right_offset: f64, min: f64, max: f64) -> Self {
440 Self {
441 bar_spacing,
442 right_offset,
443 min_spacing: min,
444 max_spacing: max,
445 width: 0.0,
446 first: 0,
447 last: -1,
448 bars: 0,
449 pending: None,
450 changed: true,
451 }
452 }
453
454 pub fn bar_spacing(&self) -> f64 {
456 self.bar_spacing
457 }
458
459 pub fn right_offset(&self) -> f64 {
461 self.right_offset
462 }
463
464 pub fn effective_min_spacing(&self) -> f64 {
467 if self.bars == 0 || self.width <= 0.0 {
468 return self.min_spacing;
469 }
470 self.min_spacing.min(0.9 * self.width / self.bars as f64)
471 }
472
473 pub fn set_bar_spacing(&mut self, px: f64) {
476 if px.is_finite() && px > 0.0 {
477 self.bar_spacing = px;
478 self.pending = None;
479 self.clamp();
480 self.changed = true;
481 }
482 }
483
484 pub fn set_right_offset(&mut self, bars: f64) {
486 if bars.is_finite() {
487 self.right_offset = bars;
488 self.pending = None;
489 self.clamp();
490 self.changed = true;
491 }
492 }
493
494 pub fn scroll_by(&mut self, dx: Px) {
496 let d = f64::from(dx.0) / self.bar_spacing;
497 if d.is_finite() {
498 self.right_offset -= d;
499 self.pending = None;
500 self.clamp();
501 self.changed = true;
502 }
503 }
504
505 pub fn zoom(&mut self, anchor_x: Px, factor: f64) {
507 if !(factor.is_finite() && factor > 0.0) {
508 return;
509 }
510 let x = f64::from(anchor_x.0);
511 let at = self.x_to_index(anchor_x);
512 let spacing = (self.bar_spacing * factor)
513 .clamp(self.effective_min_spacing(), self.max_spacing.max(1e-9));
514 self.bar_spacing = spacing;
515 self.right_offset = at - self.last as f64 - 0.5 + (self.width - x) / spacing;
516 self.pending = None;
517 self.clamp();
518 self.changed = true;
519 }
520
521 pub fn fit_content(&mut self) {
523 self.pending = Some(Pending::Fit);
524 self.apply_pending();
525 self.changed = true;
526 }
527
528 pub fn set_visible_range(&mut self, from: LogicalIndex, to: LogicalIndex) -> Result<()> {
562 if !(from.is_finite() && to.is_finite() && from < to) {
563 return Err(Error::InvalidArgument(
564 "the visible range must be finite with from < to",
565 ));
566 }
567 self.show_span(from, to);
568 Ok(())
569 }
570
571 pub(crate) fn show_span(&mut self, from: f64, to: f64) {
574 self.pending = Some(Pending::Span { from, to });
575 self.apply_pending();
576 self.changed = true;
577 }
578
579 fn apply_pending(&mut self) -> bool {
582 let Some(pending) = self.pending else {
583 return false;
584 };
585 if self.width <= 0.0 || self.bars == 0 {
586 return false;
587 }
588 match pending {
589 Pending::Fit => {
590 self.bar_spacing = self.width / self.bars as f64;
591 self.right_offset = 0.0;
592 }
593 Pending::Span { from, to } => {
594 self.bar_spacing = self.width / (to - from);
595 self.right_offset = to - self.last as f64 - 0.5;
596 }
597 }
598 self.clamp();
599 true
600 }
601
602 pub(crate) fn settle(&mut self) {
605 if self.apply_pending() {
606 self.pending = None;
607 }
608 }
609
610 pub fn visible_range(&self) -> (LogicalIndex, LogicalIndex) {
612 let to = self.last as f64 + self.right_offset + 0.5;
613 (to - self.width / self.bar_spacing, to)
614 }
615
616 pub fn index_to_x(&self, i: LogicalIndex) -> Px {
629 Px(self.index_to_x_f64(i) as f32)
630 }
631
632 pub(crate) fn index_to_x_f64(&self, i: f64) -> f64 {
633 self.width - (self.last as f64 + self.right_offset - i + 0.5) * self.bar_spacing
634 }
635
636 pub fn x_to_index(&self, x: Px) -> LogicalIndex {
638 self.last as f64 + self.right_offset + 0.5
639 - (self.width - f64::from(x.0)) / self.bar_spacing
640 }
641
642 pub(crate) fn scroll_to_first(&mut self) {
644 if self.bars == 0 || self.bar_spacing <= 0.0 {
645 return;
646 }
647 let to = self.first as f64 - 0.5 + self.width / self.bar_spacing;
648 self.set_right_offset(to - self.last as f64 - 0.5);
649 }
650
651 pub(crate) fn set_extent(&mut self, first: i64, end: i64) {
653 self.first = first;
654 self.last = end - 1;
655 self.bars = usize::try_from(end - first).unwrap_or(0);
656 self.apply_pending();
657 self.clamp();
658 }
659
660 pub(crate) fn set_width(&mut self, width: f64) {
662 if (width - self.width).abs() > f64::EPSILON {
663 self.width = width.max(0.0);
664 self.apply_pending();
665 self.clamp();
666 }
667 }
668
669 pub(crate) fn rescale(&mut self, ratio: f64) {
671 self.bar_spacing *= ratio;
672 self.min_spacing *= ratio;
673 self.max_spacing *= ratio;
674 self.clamp();
675 self.changed = true;
676 }
677
678 fn clamp(&mut self) {
680 self.bar_spacing = self
681 .bar_spacing
682 .clamp(self.effective_min_spacing(), self.max_spacing.max(1e-9));
683 if self.bars == 0 || self.width <= 0.0 {
684 return;
685 }
686 let lo = (self.first - self.last) as f64 + 0.5;
687 let hi = (self.width / self.bar_spacing - 1.0).max(lo);
688 self.right_offset = self.right_offset.clamp(lo, hi);
689 }
690}
691
692#[cfg(test)]
693mod tests {
694 use super::*;
695
696 #[test]
697 fn days_from_civil_inverts_civil_from_days() {
698 for d in [-800_000_i64, -1, 0, 59, 60, 11_016, 19_723, 2_000_000] {
699 let (y, m, dd) = civil_from_days(d);
700 assert_eq!(days_from_civil(y, m, dd), d);
701 }
702 }
703
704 #[test]
705 fn time_ticks_are_aligned_and_spaced() {
706 let t0 = 1_710_513_000_000; let mut out = Vec::new();
708 time_ticks(t0, t0 + 6 * 3_600_000, 600.0, 60.0, &mut out);
710 assert_eq!(out.len(), 6);
711 assert!(
712 out.iter()
713 .all(|&(t, w)| t % 3_600_000 == 0 && w == TickWeight::Hour)
714 );
715 time_ticks(t0, t0 + 3650 * DAY_MS, 600.0, 60.0, &mut out);
717 assert!(out.iter().all(|&(_, w)| w == TickWeight::Year), "{out:?}");
718 assert!(out.windows(2).all(|w| w[0].0 < w[1].0));
719 time_ticks(t0, t0, 600.0, 60.0, &mut out);
721 assert!(out.is_empty());
722 }
723 use proptest::prelude::*;
724
725 #[test]
726 fn pending_view_follows_width_until_settled() {
727 let mut ts = TimeScale::new(6.0, 0.0, 0.5, 50.0);
728 ts.set_extent(0, 100);
729 ts.set_width(600.0);
730 ts.fit_content();
732 ts.set_width(540.0);
733 ts.settle();
734 let (from, to) = ts.visible_range();
735 assert!(
736 (from + 0.5).abs() < 1e-9 && (to - 99.5).abs() < 1e-9,
737 "{from} {to}"
738 );
739 ts.set_width(600.0);
741 assert!((ts.bar_spacing() - 5.4).abs() < 1e-9);
742
743 ts.show_span(20.0, 60.0);
744 ts.set_width(400.0);
745 ts.settle();
746 let (from, to) = ts.visible_range();
747 assert!(
748 (from - 20.0).abs() < 1e-9 && (to - 60.0).abs() < 1e-9,
749 "{from} {to}"
750 );
751 ts.show_span(0.0, 50.0);
753 ts.set_bar_spacing(4.0);
754 ts.set_width(500.0);
755 ts.settle();
756 assert!((ts.bar_spacing() - 4.0).abs() < 1e-9);
757 }
758
759 #[test]
760 fn known_dates() {
761 assert_eq!(civil_from_days(11_016), (2000, 2, 29));
762 assert_eq!(civil_from_days(-719_468), (0, 3, 1));
763 assert_eq!(civil_from_days(2_932_896), (9999, 12, 31));
764 }
765
766 #[test]
767 fn labels() {
768 let mut s = crate::text::StackStr::<16>::new();
769 let t = 1_704_067_200_000; for (w, want) in [
771 (TickWeight::Year, "2024"),
772 (TickWeight::Month, "Jan"),
773 (TickWeight::Day, "1"),
774 (TickWeight::Minute, "00:00"),
775 (TickWeight::Second, "00:00:00"),
776 ] {
777 s.clear();
778 format_tick(t, w, &mut s).unwrap();
779 assert_eq!(s.as_str(), want);
780 }
781 }
782
783 #[test]
784 fn ticks_find_exact_boundaries() {
785 let start = 1_703_030_400_000;
787 let index = TimeIndex::from_times((0..40).map(|d| start + d * DAY_MS).collect()).unwrap();
788 let mut out = Vec::new();
789 collect_ticks(&index, &Utc, 0, 39, 3, &mut out);
790 let year = out.iter().find(|t| t.weight == TickWeight::Year).unwrap();
791 assert_eq!(index.time_at(year.index), Some(1_704_067_200_000));
792 }
793
794 proptest! {
795 #[test]
797 fn civil_steps_by_one_day(days in -1_000_000i64..1_000_000) {
798 let (y0, m0, d0) = civil_from_days(days);
799 let (y1, m1, d1) = civil_from_days(days + 1);
800 let next_day = d1 == d0 + 1 && m1 == m0 && y1 == y0;
801 let next_month = d1 == 1 && ((m1 == m0 + 1 && y1 == y0) || (m0 == 12 && m1 == 1 && y1 == y0 + 1));
802 prop_assert!(next_day || next_month);
803 prop_assert!((28..=31).contains(&d0) || next_day);
804 }
805
806 #[test]
808 fn zoom_keeps_anchor(x in 0.0f32..800.0, factor in 0.5f64..2.0) {
809 let mut ts = TimeScale::new(6.0, 3.0, 0.5, 50.0);
810 ts.set_extent(0, 1000);
811 ts.set_width(800.0);
812 let before = ts.x_to_index(Px(x));
813 ts.zoom(Px(x), factor);
814 prop_assert!((ts.x_to_index(Px(x)) - before).abs() < 1e-6);
815 }
816 }
817}