1use std::time::Duration;
5
6use super::Span;
7
8pub const MARK_SPACING: f32 = 64.0;
10
11const MARK_GAP: f32 = 40.0;
13
14const MOST_SPREAD: f32 = 0.02;
17
18#[derive(Debug, Clone, Copy, PartialEq)]
22pub struct Break {
23 pub start: f32,
24 pub end: f32,
25 pub hidden: Duration,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq)]
30pub struct Mark {
31 pub time: Duration,
32 pub place: f32,
33}
34
35#[derive(Debug, Clone, PartialEq, Default)]
37pub struct Timing {
38 positions: Vec<f32>,
39 anchors: Vec<(Duration, f32)>,
41 hidden: Vec<Duration>,
43 breaks: Vec<Break>,
44 shown: Duration,
46}
47
48impl Timing {
49 pub fn new(times: &[Duration], end: Option<Duration>, compress: Option<Duration>) -> Self {
60 let Some(&first) = times.first() else {
61 return Self::default();
62 };
63 let mut keys: Vec<Duration> = Vec::with_capacity(times.len() + 1);
64 for &time in times {
65 let floor = keys.last().copied().unwrap_or(first);
66 keys.push(time.max(floor));
67 }
68 let last = keys.last().copied().unwrap_or(first);
69 keys.push(end.map_or(last, |end| end.max(last)));
70
71 let mut units = vec![0.0_f64];
72 let mut hidden = Vec::with_capacity(keys.len());
73 let mut total = 0.0_f64;
74 for pair in keys.windows(2) {
75 let gap = pair[1].saturating_sub(pair[0]);
76 let drawn = match compress {
77 Some(limit) if gap > limit => limit,
78 _ => gap,
79 };
80 hidden.push(gap - drawn);
81 total += drawn.as_secs_f64();
82 units.push(total);
83 }
84 hidden.push(Duration::ZERO);
85
86 let count = times.len();
87 if total <= 0.0 {
88 let positions: Vec<f32> = (0..count).map(|index| even(index, count)).collect();
89 return Self {
90 anchors: keys.iter().map(|time| (*time, 0.0)).collect(),
91 hidden: vec![Duration::ZERO; keys.len()],
92 positions,
93 breaks: Vec::new(),
94 shown: Duration::ZERO,
95 };
96 }
97
98 let places: Vec<f32> = units.iter().map(|unit| (unit / total) as f32).collect();
99 let breaks = hidden
100 .iter()
101 .zip(places.windows(2))
102 .filter(|(hidden, _)| !hidden.is_zero())
103 .map(|(hidden, pair)| Break {
104 start: pair[0],
105 end: pair[1],
106 hidden: *hidden,
107 })
108 .collect();
109 let spread = if count < 2 {
110 0.0
111 } else {
112 (0.5 / (count - 1) as f32).min(MOST_SPREAD)
113 };
114 Self {
115 positions: spread_apart(places.iter().take(count).copied().collect(), spread),
116 anchors: keys.into_iter().zip(places).collect(),
117 hidden,
118 breaks,
119 shown: Duration::from_secs_f64(total),
120 }
121 }
122
123 pub fn positions(&self) -> &[f32] {
125 &self.positions
126 }
127
128 pub fn breaks(&self) -> &[Break] {
130 &self.breaks
131 }
132
133 pub fn start(&self) -> Duration {
135 self.anchors
136 .first()
137 .map_or(Duration::ZERO, |anchor| anchor.0)
138 }
139
140 pub fn end(&self) -> Duration {
142 self.anchors
143 .last()
144 .map_or(Duration::ZERO, |anchor| anchor.0)
145 }
146
147 pub fn shown(&self) -> Duration {
149 self.shown
150 }
151
152 pub fn place(&self, time: Duration) -> f32 {
155 let after = self.anchors.partition_point(|anchor| anchor.0 < time);
156 let (Some(before), Some(at)) = (
157 after
158 .checked_sub(1)
159 .and_then(|index| self.anchors.get(index)),
160 self.anchors.get(after),
161 ) else {
162 let edge = self.anchors.get(after).or(self.anchors.last());
163 return edge.map_or(0.0, |anchor| anchor.1);
164 };
165 between(*before, *at, time)
166 }
167
168 pub fn nearest(&self, fraction: f32) -> usize {
170 let after = self.positions.partition_point(|place| *place < fraction);
171 let Some(&at) = self.positions.get(after) else {
172 return self.positions.len().saturating_sub(1);
173 };
174 let Some(before) = after.checked_sub(1) else {
175 return after;
176 };
177 match self.positions.get(before) {
178 Some(&place) if fraction - place <= at - fraction => before,
179 _ => after,
180 }
181 }
182
183 pub fn extent(&self, span: Span) -> (f32, f32) {
186 let last = self.positions.len().saturating_sub(1);
187 let (start, end) = (span.start.min(last), span.end.min(last));
188 let place = |index: usize| self.positions.get(index).copied().unwrap_or(0.0);
189 let left = match start.checked_sub(1) {
190 Some(before) => (place(before) + place(start)) / 2.0,
191 None => 0.0,
192 };
193 let right = if end >= last {
194 1.0
195 } else {
196 (place(end) + place(end + 1)) / 2.0
197 };
198 (left, right.max(left))
199 }
200
201 pub fn interval(&self, width: f32) -> Option<Duration> {
205 if self.shown.is_zero() || width <= 0.0 {
206 return None;
207 }
208 let most = (width / MARK_SPACING).floor().max(1.0) as f64;
209 let shown = self.shown.as_secs_f64();
210 intervals().find(|interval| shown / interval.as_secs_f64() <= most)
211 }
212
213 pub fn marks(&self, width: f32) -> Vec<Mark> {
217 let Some(interval) = self.interval(width) else {
218 return Vec::new();
219 };
220 let step = interval.as_nanos().max(1);
221 let mut marks: Vec<Mark> = Vec::new();
222 for (index, pair) in self.anchors.windows(2).enumerate() {
223 if self
224 .hidden
225 .get(index)
226 .is_some_and(|hidden| !hidden.is_zero())
227 {
228 continue;
229 }
230 let (from, to) = (pair[0], pair[1]);
231 let first = from.0.as_nanos().div_ceil(step);
232 let last = to.0.as_nanos() / step;
233 for multiple in first..=last {
234 let time = nanos(multiple * step);
235 if marks.last().is_some_and(|mark| mark.time >= time) {
236 continue;
237 }
238 let place = between(from, to, time);
239 if marks
240 .last()
241 .is_some_and(|mark| (place - mark.place) * width < MARK_GAP)
242 {
243 continue;
244 }
245 marks.push(Mark { time, place });
246 }
247 }
248 marks
249 }
250}
251
252fn spread_apart(mut places: Vec<f32>, gap: f32) -> Vec<f32> {
255 for index in 1..places.len() {
256 places[index] = places[index].max(places[index - 1] + gap);
257 }
258 let mut ceiling = 1.0_f32;
259 for place in places.iter_mut().rev() {
260 *place = place.min(ceiling).max(0.0);
261 ceiling = *place - gap;
262 }
263 places
264}
265
266fn even(index: usize, count: usize) -> f32 {
268 if count < 2 {
269 return 0.0;
270 }
271 index.min(count - 1) as f32 / (count - 1) as f32
272}
273
274fn between(from: (Duration, f32), to: (Duration, f32), time: Duration) -> f32 {
276 let length = to.0.saturating_sub(from.0).as_secs_f64();
277 if length <= 0.0 {
278 return to.1;
279 }
280 let along = (time.saturating_sub(from.0).as_secs_f64() / length).clamp(0.0, 1.0) as f32;
281 from.1 + (to.1 - from.1) * along
282}
283
284fn nanos(nanos: u128) -> Duration {
285 u64::try_from(nanos).map_or(Duration::MAX, Duration::from_nanos)
286}
287
288fn intervals() -> impl Iterator<Item = Duration> {
291 let millis = [1, 2, 5, 10, 20, 50, 100, 200, 500].map(Duration::from_millis);
292 let seconds = [1, 2, 5, 10, 15, 30].map(Duration::from_secs);
293 let minutes = [1, 2, 5, 10, 15, 30].map(|minutes| Duration::from_secs(minutes * 60));
294 let hours = [1, 2, 3, 6, 12].map(|hours| Duration::from_secs(hours * 3600));
295 let days = (0..).flat_map(|power: u32| {
296 [1, 2, 5].map(move |m| {
297 Duration::from_secs(86_400_u64.saturating_mul(m * 10_u64.pow(power.min(15))))
298 })
299 });
300 millis
301 .into_iter()
302 .chain(seconds)
303 .chain(minutes)
304 .chain(hours)
305 .chain(days)
306}
307
308pub fn time_label(time: Duration, interval: Duration, end: Duration) -> String {
312 let decimals = decimals(interval);
313 if end < Duration::from_secs(1) {
314 return format!("{} ms", time.as_millis());
315 }
316 if end < Duration::from_secs(60) {
317 return format!("{:.*} s", decimals, time.as_secs_f64());
318 }
319 let seconds = time.as_secs();
320 let (hours, minutes, seconds) = (seconds / 3600, seconds / 60 % 60, seconds % 60);
321 let clock = if hours > 0 {
322 format!("{hours}:{minutes:02}:{seconds:02}")
323 } else {
324 format!("{minutes}:{seconds:02}")
325 };
326 if decimals == 0 {
327 return clock;
328 }
329 let fraction = format!("{:03}", time.subsec_millis());
330 format!("{clock}.{}", fraction.get(..decimals).unwrap_or_default())
331}
332
333fn decimals(interval: Duration) -> usize {
335 let millis = interval.subsec_millis();
336 if millis == 0 {
337 0
338 } else if millis.is_multiple_of(100) {
339 1
340 } else if millis.is_multiple_of(10) {
341 2
342 } else {
343 3
344 }
345}
346
347#[cfg(test)]
348mod tests {
349 use super::*;
350
351 fn ms(millis: u64) -> Duration {
352 Duration::from_millis(millis)
353 }
354
355 fn secs(seconds: u64) -> Duration {
356 Duration::from_secs(seconds)
357 }
358
359 #[test]
360 fn steps_sit_in_proportion_to_their_times() {
361 let timing = Timing::new(&[secs(0), secs(1), secs(4)], None, None);
362 assert_eq!(timing.positions(), [0.0, 0.25, 1.0]);
363 assert_eq!(timing.start(), secs(0));
364 assert_eq!(timing.end(), secs(4));
365 assert!(timing.breaks().is_empty());
366 }
367
368 #[test]
369 fn the_track_starts_at_the_first_time_and_runs_to_the_end() {
370 let timing = Timing::new(&[secs(2), secs(4)], Some(secs(6)), None);
371 assert_eq!(timing.positions(), [0.0, 0.5]);
372 assert_eq!(timing.place(secs(6)), 1.0);
373 let early = Timing::new(&[secs(2), secs(4)], Some(secs(1)), None);
374 assert_eq!(
375 early.end(),
376 secs(4),
377 "an end before the last step is ignored"
378 );
379 }
380
381 #[test]
382 fn steps_at_one_moment_are_spread_apart() {
383 let timing = Timing::new(&[secs(0), secs(0), secs(0), secs(9)], None, None);
384 let positions = timing.positions();
385 assert!(positions[1] > positions[0] && positions[2] > positions[1]);
386 assert_eq!(positions[3], 1.0);
387 for (index, place) in positions.iter().enumerate() {
388 assert_eq!(timing.nearest(*place), index);
389 }
390 }
391
392 #[test]
393 fn times_running_backwards_take_the_one_before() {
394 let timing = Timing::new(&[secs(5), secs(2), secs(10)], None, None);
395 assert_eq!(timing.start(), secs(5));
396 assert!(timing.positions()[1] > 0.0 && timing.positions()[1] < 0.5);
397 }
398
399 #[test]
400 fn no_time_passing_spreads_the_steps_evenly() {
401 let timing = Timing::new(&[secs(3); 5], None, None);
402 assert_eq!(timing.positions(), [0.0, 0.25, 0.5, 0.75, 1.0]);
403 assert_eq!(timing.interval(400.0), None);
404 assert!(timing.marks(400.0).is_empty());
405 assert_eq!(Timing::new(&[], None, None).nearest(0.5), 0);
406 assert_eq!(Timing::new(&[secs(1)], None, None).positions(), [0.0]);
407 }
408
409 #[test]
410 fn long_gaps_are_compressed_with_a_break() {
411 let times = [secs(0), secs(1), secs(101), secs(102)];
412 let timing = Timing::new(×, None, Some(secs(1)));
413 assert_eq!(timing.shown(), secs(3));
414 let positions = timing.positions();
415 assert!((positions[1] - 1.0 / 3.0).abs() < 1e-6);
416 assert!((positions[2] - 2.0 / 3.0).abs() < 1e-6);
417 assert_eq!(timing.breaks().len(), 1);
418 assert_eq!(timing.breaks()[0].start, positions[1]);
419 assert_eq!(timing.breaks()[0].end, positions[2]);
420 assert_eq!(timing.breaks()[0].hidden, secs(99));
421
422 let uncompressed = Timing::new(×, None, None);
423 assert!(uncompressed.positions()[2] > 0.8);
424 assert!(uncompressed.breaks().is_empty());
425 }
426
427 #[test]
428 fn places_interpolate_between_steps_and_clamp_at_the_ends() {
429 let timing = Timing::new(&[secs(10), secs(20)], None, None);
430 assert_eq!(timing.place(secs(15)), 0.5);
431 assert_eq!(timing.place(secs(0)), 0.0);
432 assert_eq!(timing.place(secs(99)), 1.0);
433 }
434
435 #[test]
436 fn nearest_picks_the_closer_neighbour() {
437 let timing = Timing::new(&[secs(0), secs(1), secs(4)], None, None);
438 assert_eq!(timing.nearest(-1.0), 0);
439 assert_eq!(timing.nearest(0.1), 0);
440 assert_eq!(timing.nearest(0.2), 1);
441 assert_eq!(timing.nearest(0.7), 2);
442 assert_eq!(timing.nearest(2.0), 2);
443 }
444
445 #[test]
446 fn spans_reach_halfway_to_their_neighbours() {
447 let timing = Timing::new(&[secs(0), secs(1), secs(4)], None, None);
448 assert_eq!(timing.extent(Span::new(1, 1)), (0.125, 0.625));
449 assert_eq!(timing.extent(Span::new(0, 2)), (0.0, 1.0));
450 assert_eq!(timing.extent(Span::new(2, 9)), (0.625, 1.0));
451 }
452
453 #[test]
454 fn the_interval_keeps_labels_apart_in_round_steps() {
455 let timing = Timing::new(&[secs(0), secs(10)], None, None);
456 assert_eq!(timing.interval(640.0), Some(secs(1)));
457 assert_eq!(timing.interval(320.0), Some(secs(2)));
458 assert_eq!(timing.interval(64.0), Some(secs(10)));
459 let short = Timing::new(&[ms(0), ms(300)], None, None);
460 assert_eq!(short.interval(640.0), Some(ms(50)));
461 let long = Timing::new(&[secs(0), secs(3 * 86_400)], None, None);
462 assert_eq!(long.interval(64.0), Some(secs(5 * 86_400)));
463 }
464
465 #[test]
466 fn marks_fall_on_whole_intervals_and_skip_breaks() {
467 let timing = Timing::new(&[secs(0), secs(4)], None, None);
468 let marks = timing.marks(256.0);
469 let times: Vec<Duration> = marks.iter().map(|mark| mark.time).collect();
470 assert_eq!(times, [secs(0), secs(1), secs(2), secs(3), secs(4)]);
471 assert_eq!(marks[2].place, 0.5);
472
473 let gapped = Timing::new(
474 &[secs(0), secs(2), secs(100), secs(102)],
475 None,
476 Some(secs(2)),
477 );
478 let times: Vec<Duration> = gapped.marks(1200.0).iter().map(|m| m.time).collect();
479 assert!(times.contains(&secs(1)));
480 assert!(times.contains(&secs(101)));
481 assert!(!times.iter().any(|t| *t > secs(2) && *t < secs(100)));
482 }
483
484 #[test]
485 fn close_steps_are_nudged_apart_without_bending_the_ruler() {
486 let timing = Timing::new(&[secs(0), ms(10), secs(10)], None, None);
487 let positions = timing.positions();
488 assert_eq!(positions[0], 0.0);
489 assert!((positions[1] - MOST_SPREAD).abs() < 1e-6);
490 assert_eq!(positions[2], 1.0);
491 let marks = timing.marks(640.0);
492 assert_eq!(marks.len(), 11);
493 for (index, mark) in marks.iter().enumerate() {
494 assert!((mark.place - index as f32 / 10.0).abs() < 1e-5, "{mark:?}");
495 }
496
497 let bunched = Timing::new(&[secs(10), secs(10), secs(10)], Some(secs(10)), None);
498 assert_eq!(bunched.positions(), [0.0, 0.5, 1.0], "no time passes");
499 let end = Timing::new(&[secs(0), secs(10), secs(10)], None, None);
500 assert_eq!(end.positions()[2], 1.0);
501 assert!((end.positions()[1] - (1.0 - MOST_SPREAD)).abs() < 1e-6);
502 }
503
504 #[test]
505 fn marks_too_close_together_drop_the_later_one() {
506 let gapped = Timing::new(
507 &[secs(0), secs(1), secs(1000), secs(1001)],
508 None,
509 Some(ms(10)),
510 );
511 let marks = gapped.marks(200.0);
512 for pair in marks.windows(2) {
513 assert!((pair[1].place - pair[0].place) * 200.0 >= MARK_GAP);
514 }
515 }
516
517 #[test]
518 fn labels_suit_the_length_of_the_track() {
519 assert_eq!(time_label(ms(250), ms(50), ms(800)), "250 ms");
520 assert_eq!(time_label(ms(1500), ms(500), secs(5)), "1.5 s");
521 assert_eq!(time_label(secs(2), secs(1), secs(5)), "2 s");
522 assert_eq!(time_label(ms(2250), ms(250), secs(5)), "2.25 s");
523 assert_eq!(time_label(secs(95), secs(5), secs(120)), "1:35");
524 assert_eq!(time_label(secs(3725), secs(60), secs(7200)), "1:02:05");
525 assert_eq!(time_label(ms(61_500), ms(500), secs(90)), "1:01.5");
526 }
527}