use std::time::Duration;
use super::Span;
pub const MARK_SPACING: f32 = 64.0;
const MARK_GAP: f32 = 40.0;
const MOST_SPREAD: f32 = 0.02;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Break {
pub start: f32,
pub end: f32,
pub hidden: Duration,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Mark {
pub time: Duration,
pub place: f32,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Timing {
positions: Vec<f32>,
anchors: Vec<(Duration, f32)>,
hidden: Vec<Duration>,
breaks: Vec<Break>,
shown: Duration,
}
impl Timing {
pub fn new(times: &[Duration], end: Option<Duration>, compress: Option<Duration>) -> Self {
let Some(&first) = times.first() else {
return Self::default();
};
let mut keys: Vec<Duration> = Vec::with_capacity(times.len() + 1);
for &time in times {
let floor = keys.last().copied().unwrap_or(first);
keys.push(time.max(floor));
}
let last = keys.last().copied().unwrap_or(first);
keys.push(end.map_or(last, |end| end.max(last)));
let mut units = vec![0.0_f64];
let mut hidden = Vec::with_capacity(keys.len());
let mut total = 0.0_f64;
for pair in keys.windows(2) {
let gap = pair[1].saturating_sub(pair[0]);
let drawn = match compress {
Some(limit) if gap > limit => limit,
_ => gap,
};
hidden.push(gap - drawn);
total += drawn.as_secs_f64();
units.push(total);
}
hidden.push(Duration::ZERO);
let count = times.len();
if total <= 0.0 {
let positions: Vec<f32> = (0..count).map(|index| even(index, count)).collect();
return Self {
anchors: keys.iter().map(|time| (*time, 0.0)).collect(),
hidden: vec![Duration::ZERO; keys.len()],
positions,
breaks: Vec::new(),
shown: Duration::ZERO,
};
}
let places: Vec<f32> = units.iter().map(|unit| (unit / total) as f32).collect();
let breaks = hidden
.iter()
.zip(places.windows(2))
.filter(|(hidden, _)| !hidden.is_zero())
.map(|(hidden, pair)| Break {
start: pair[0],
end: pair[1],
hidden: *hidden,
})
.collect();
let spread = if count < 2 {
0.0
} else {
(0.5 / (count - 1) as f32).min(MOST_SPREAD)
};
Self {
positions: spread_apart(places.iter().take(count).copied().collect(), spread),
anchors: keys.into_iter().zip(places).collect(),
hidden,
breaks,
shown: Duration::from_secs_f64(total),
}
}
pub fn positions(&self) -> &[f32] {
&self.positions
}
pub fn breaks(&self) -> &[Break] {
&self.breaks
}
pub fn start(&self) -> Duration {
self.anchors
.first()
.map_or(Duration::ZERO, |anchor| anchor.0)
}
pub fn end(&self) -> Duration {
self.anchors
.last()
.map_or(Duration::ZERO, |anchor| anchor.0)
}
pub fn shown(&self) -> Duration {
self.shown
}
pub fn place(&self, time: Duration) -> f32 {
let after = self.anchors.partition_point(|anchor| anchor.0 < time);
let (Some(before), Some(at)) = (
after
.checked_sub(1)
.and_then(|index| self.anchors.get(index)),
self.anchors.get(after),
) else {
let edge = self.anchors.get(after).or(self.anchors.last());
return edge.map_or(0.0, |anchor| anchor.1);
};
between(*before, *at, time)
}
pub fn nearest(&self, fraction: f32) -> usize {
let after = self.positions.partition_point(|place| *place < fraction);
let Some(&at) = self.positions.get(after) else {
return self.positions.len().saturating_sub(1);
};
let Some(before) = after.checked_sub(1) else {
return after;
};
match self.positions.get(before) {
Some(&place) if fraction - place <= at - fraction => before,
_ => after,
}
}
pub fn extent(&self, span: Span) -> (f32, f32) {
let last = self.positions.len().saturating_sub(1);
let (start, end) = (span.start.min(last), span.end.min(last));
let place = |index: usize| self.positions.get(index).copied().unwrap_or(0.0);
let left = match start.checked_sub(1) {
Some(before) => (place(before) + place(start)) / 2.0,
None => 0.0,
};
let right = if end >= last {
1.0
} else {
(place(end) + place(end + 1)) / 2.0
};
(left, right.max(left))
}
pub fn interval(&self, width: f32) -> Option<Duration> {
if self.shown.is_zero() || width <= 0.0 {
return None;
}
let most = (width / MARK_SPACING).floor().max(1.0) as f64;
let shown = self.shown.as_secs_f64();
intervals().find(|interval| shown / interval.as_secs_f64() <= most)
}
pub fn marks(&self, width: f32) -> Vec<Mark> {
let Some(interval) = self.interval(width) else {
return Vec::new();
};
let step = interval.as_nanos().max(1);
let mut marks: Vec<Mark> = Vec::new();
for (index, pair) in self.anchors.windows(2).enumerate() {
if self
.hidden
.get(index)
.is_some_and(|hidden| !hidden.is_zero())
{
continue;
}
let (from, to) = (pair[0], pair[1]);
let first = from.0.as_nanos().div_ceil(step);
let last = to.0.as_nanos() / step;
for multiple in first..=last {
let time = nanos(multiple * step);
if marks.last().is_some_and(|mark| mark.time >= time) {
continue;
}
let place = between(from, to, time);
if marks
.last()
.is_some_and(|mark| (place - mark.place) * width < MARK_GAP)
{
continue;
}
marks.push(Mark { time, place });
}
}
marks
}
}
fn spread_apart(mut places: Vec<f32>, gap: f32) -> Vec<f32> {
for index in 1..places.len() {
places[index] = places[index].max(places[index - 1] + gap);
}
let mut ceiling = 1.0_f32;
for place in places.iter_mut().rev() {
*place = place.min(ceiling).max(0.0);
ceiling = *place - gap;
}
places
}
fn even(index: usize, count: usize) -> f32 {
if count < 2 {
return 0.0;
}
index.min(count - 1) as f32 / (count - 1) as f32
}
fn between(from: (Duration, f32), to: (Duration, f32), time: Duration) -> f32 {
let length = to.0.saturating_sub(from.0).as_secs_f64();
if length <= 0.0 {
return to.1;
}
let along = (time.saturating_sub(from.0).as_secs_f64() / length).clamp(0.0, 1.0) as f32;
from.1 + (to.1 - from.1) * along
}
fn nanos(nanos: u128) -> Duration {
u64::try_from(nanos).map_or(Duration::MAX, Duration::from_nanos)
}
fn intervals() -> impl Iterator<Item = Duration> {
let millis = [1, 2, 5, 10, 20, 50, 100, 200, 500].map(Duration::from_millis);
let seconds = [1, 2, 5, 10, 15, 30].map(Duration::from_secs);
let minutes = [1, 2, 5, 10, 15, 30].map(|minutes| Duration::from_secs(minutes * 60));
let hours = [1, 2, 3, 6, 12].map(|hours| Duration::from_secs(hours * 3600));
let days = (0..).flat_map(|power: u32| {
[1, 2, 5].map(move |m| {
Duration::from_secs(86_400_u64.saturating_mul(m * 10_u64.pow(power.min(15))))
})
});
millis
.into_iter()
.chain(seconds)
.chain(minutes)
.chain(hours)
.chain(days)
}
pub fn time_label(time: Duration, interval: Duration, end: Duration) -> String {
let decimals = decimals(interval);
if end < Duration::from_secs(1) {
return format!("{} ms", time.as_millis());
}
if end < Duration::from_secs(60) {
return format!("{:.*} s", decimals, time.as_secs_f64());
}
let seconds = time.as_secs();
let (hours, minutes, seconds) = (seconds / 3600, seconds / 60 % 60, seconds % 60);
let clock = if hours > 0 {
format!("{hours}:{minutes:02}:{seconds:02}")
} else {
format!("{minutes}:{seconds:02}")
};
if decimals == 0 {
return clock;
}
let fraction = format!("{:03}", time.subsec_millis());
format!("{clock}.{}", fraction.get(..decimals).unwrap_or_default())
}
fn decimals(interval: Duration) -> usize {
let millis = interval.subsec_millis();
if millis == 0 {
0
} else if millis.is_multiple_of(100) {
1
} else if millis.is_multiple_of(10) {
2
} else {
3
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ms(millis: u64) -> Duration {
Duration::from_millis(millis)
}
fn secs(seconds: u64) -> Duration {
Duration::from_secs(seconds)
}
#[test]
fn steps_sit_in_proportion_to_their_times() {
let timing = Timing::new(&[secs(0), secs(1), secs(4)], None, None);
assert_eq!(timing.positions(), [0.0, 0.25, 1.0]);
assert_eq!(timing.start(), secs(0));
assert_eq!(timing.end(), secs(4));
assert!(timing.breaks().is_empty());
}
#[test]
fn the_track_starts_at_the_first_time_and_runs_to_the_end() {
let timing = Timing::new(&[secs(2), secs(4)], Some(secs(6)), None);
assert_eq!(timing.positions(), [0.0, 0.5]);
assert_eq!(timing.place(secs(6)), 1.0);
let early = Timing::new(&[secs(2), secs(4)], Some(secs(1)), None);
assert_eq!(
early.end(),
secs(4),
"an end before the last step is ignored"
);
}
#[test]
fn steps_at_one_moment_are_spread_apart() {
let timing = Timing::new(&[secs(0), secs(0), secs(0), secs(9)], None, None);
let positions = timing.positions();
assert!(positions[1] > positions[0] && positions[2] > positions[1]);
assert_eq!(positions[3], 1.0);
for (index, place) in positions.iter().enumerate() {
assert_eq!(timing.nearest(*place), index);
}
}
#[test]
fn times_running_backwards_take_the_one_before() {
let timing = Timing::new(&[secs(5), secs(2), secs(10)], None, None);
assert_eq!(timing.start(), secs(5));
assert!(timing.positions()[1] > 0.0 && timing.positions()[1] < 0.5);
}
#[test]
fn no_time_passing_spreads_the_steps_evenly() {
let timing = Timing::new(&[secs(3); 5], None, None);
assert_eq!(timing.positions(), [0.0, 0.25, 0.5, 0.75, 1.0]);
assert_eq!(timing.interval(400.0), None);
assert!(timing.marks(400.0).is_empty());
assert_eq!(Timing::new(&[], None, None).nearest(0.5), 0);
assert_eq!(Timing::new(&[secs(1)], None, None).positions(), [0.0]);
}
#[test]
fn long_gaps_are_compressed_with_a_break() {
let times = [secs(0), secs(1), secs(101), secs(102)];
let timing = Timing::new(×, None, Some(secs(1)));
assert_eq!(timing.shown(), secs(3));
let positions = timing.positions();
assert!((positions[1] - 1.0 / 3.0).abs() < 1e-6);
assert!((positions[2] - 2.0 / 3.0).abs() < 1e-6);
assert_eq!(timing.breaks().len(), 1);
assert_eq!(timing.breaks()[0].start, positions[1]);
assert_eq!(timing.breaks()[0].end, positions[2]);
assert_eq!(timing.breaks()[0].hidden, secs(99));
let uncompressed = Timing::new(×, None, None);
assert!(uncompressed.positions()[2] > 0.8);
assert!(uncompressed.breaks().is_empty());
}
#[test]
fn places_interpolate_between_steps_and_clamp_at_the_ends() {
let timing = Timing::new(&[secs(10), secs(20)], None, None);
assert_eq!(timing.place(secs(15)), 0.5);
assert_eq!(timing.place(secs(0)), 0.0);
assert_eq!(timing.place(secs(99)), 1.0);
}
#[test]
fn nearest_picks_the_closer_neighbour() {
let timing = Timing::new(&[secs(0), secs(1), secs(4)], None, None);
assert_eq!(timing.nearest(-1.0), 0);
assert_eq!(timing.nearest(0.1), 0);
assert_eq!(timing.nearest(0.2), 1);
assert_eq!(timing.nearest(0.7), 2);
assert_eq!(timing.nearest(2.0), 2);
}
#[test]
fn spans_reach_halfway_to_their_neighbours() {
let timing = Timing::new(&[secs(0), secs(1), secs(4)], None, None);
assert_eq!(timing.extent(Span::new(1, 1)), (0.125, 0.625));
assert_eq!(timing.extent(Span::new(0, 2)), (0.0, 1.0));
assert_eq!(timing.extent(Span::new(2, 9)), (0.625, 1.0));
}
#[test]
fn the_interval_keeps_labels_apart_in_round_steps() {
let timing = Timing::new(&[secs(0), secs(10)], None, None);
assert_eq!(timing.interval(640.0), Some(secs(1)));
assert_eq!(timing.interval(320.0), Some(secs(2)));
assert_eq!(timing.interval(64.0), Some(secs(10)));
let short = Timing::new(&[ms(0), ms(300)], None, None);
assert_eq!(short.interval(640.0), Some(ms(50)));
let long = Timing::new(&[secs(0), secs(3 * 86_400)], None, None);
assert_eq!(long.interval(64.0), Some(secs(5 * 86_400)));
}
#[test]
fn marks_fall_on_whole_intervals_and_skip_breaks() {
let timing = Timing::new(&[secs(0), secs(4)], None, None);
let marks = timing.marks(256.0);
let times: Vec<Duration> = marks.iter().map(|mark| mark.time).collect();
assert_eq!(times, [secs(0), secs(1), secs(2), secs(3), secs(4)]);
assert_eq!(marks[2].place, 0.5);
let gapped = Timing::new(
&[secs(0), secs(2), secs(100), secs(102)],
None,
Some(secs(2)),
);
let times: Vec<Duration> = gapped.marks(1200.0).iter().map(|m| m.time).collect();
assert!(times.contains(&secs(1)));
assert!(times.contains(&secs(101)));
assert!(!times.iter().any(|t| *t > secs(2) && *t < secs(100)));
}
#[test]
fn close_steps_are_nudged_apart_without_bending_the_ruler() {
let timing = Timing::new(&[secs(0), ms(10), secs(10)], None, None);
let positions = timing.positions();
assert_eq!(positions[0], 0.0);
assert!((positions[1] - MOST_SPREAD).abs() < 1e-6);
assert_eq!(positions[2], 1.0);
let marks = timing.marks(640.0);
assert_eq!(marks.len(), 11);
for (index, mark) in marks.iter().enumerate() {
assert!((mark.place - index as f32 / 10.0).abs() < 1e-5, "{mark:?}");
}
let bunched = Timing::new(&[secs(10), secs(10), secs(10)], Some(secs(10)), None);
assert_eq!(bunched.positions(), [0.0, 0.5, 1.0], "no time passes");
let end = Timing::new(&[secs(0), secs(10), secs(10)], None, None);
assert_eq!(end.positions()[2], 1.0);
assert!((end.positions()[1] - (1.0 - MOST_SPREAD)).abs() < 1e-6);
}
#[test]
fn marks_too_close_together_drop_the_later_one() {
let gapped = Timing::new(
&[secs(0), secs(1), secs(1000), secs(1001)],
None,
Some(ms(10)),
);
let marks = gapped.marks(200.0);
for pair in marks.windows(2) {
assert!((pair[1].place - pair[0].place) * 200.0 >= MARK_GAP);
}
}
#[test]
fn labels_suit_the_length_of_the_track() {
assert_eq!(time_label(ms(250), ms(50), ms(800)), "250 ms");
assert_eq!(time_label(ms(1500), ms(500), secs(5)), "1.5 s");
assert_eq!(time_label(secs(2), secs(1), secs(5)), "2 s");
assert_eq!(time_label(ms(2250), ms(250), secs(5)), "2.25 s");
assert_eq!(time_label(secs(95), secs(5), secs(120)), "1:35");
assert_eq!(time_label(secs(3725), secs(60), secs(7200)), "1:02:05");
assert_eq!(time_label(ms(61_500), ms(500), secs(90)), "1:01.5");
}
}