iced-cube 0.0.25

Themeable application components for the iced GUI library, with Lucide icons
Documentation
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
//! Where steps sit when they are placed by time rather than evenly, and the
//! marks of the time ruler.

use std::time::Duration;

use super::Span;

/// The least room, in pixels, each ruler label is given along the track.
pub const MARK_SPACING: f32 = 64.0;

/// Ruler labels closer than this, in pixels, drop the later one.
const MARK_GAP: f32 = 40.0;

/// The most two steps at one moment are spread apart, as a share of the
/// track, so each can still be picked.
const MOST_SPREAD: f32 = 0.02;

/// A stretch of the track where an idle gap is drawn shorter than it
/// lasted, from `start` to `end` along the track (0 to 1), and how much
/// time it leaves out.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Break {
    pub start: f32,
    pub end: f32,
    pub hidden: Duration,
}

/// A ruler mark: a time and where it falls along the track (0 to 1).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Mark {
    pub time: Duration,
    pub place: f32,
}

/// Where timed steps sit along a track, from 0 at its start to 1 at its end.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Timing {
    positions: Vec<f32>,
    /// Each step's time and place, then the end of the track's.
    anchors: Vec<(Duration, f32)>,
    /// The time left out of the stretch after each anchor.
    hidden: Vec<Duration>,
    breaks: Vec<Break>,
    /// How much time the track shows once long gaps are compressed.
    shown: Duration,
}

impl Timing {
    /// Places one step at each of `times`, the moment it began. A time
    /// earlier than the one before it is taken as that one. The track runs
    /// from the first time to `end`, or to the last time when `end` is
    /// earlier or `None`. Gaps longer than `compress` are drawn as long as
    /// `compress`, each with a [`Break`].
    ///
    /// Time runs evenly along the track, so the ruler stays linear. Only
    /// steps too close to pick apart, such as several at one moment, are
    /// nudged a little apart; the ruler does not move with them. When no
    /// time passes at all the steps sit evenly.
    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),
        }
    }

    /// Where each step sits, 0 to 1.
    pub fn positions(&self) -> &[f32] {
        &self.positions
    }

    /// The compressed gaps, in order along the track.
    pub fn breaks(&self) -> &[Break] {
        &self.breaks
    }

    /// The time at the start of the track.
    pub fn start(&self) -> Duration {
        self.anchors
            .first()
            .map_or(Duration::ZERO, |anchor| anchor.0)
    }

    /// The time at the end of the track.
    pub fn end(&self) -> Duration {
        self.anchors
            .last()
            .map_or(Duration::ZERO, |anchor| anchor.0)
    }

    /// How much time the track shows once long gaps are compressed.
    pub fn shown(&self) -> Duration {
        self.shown
    }

    /// Where `time` falls along the track, 0 to 1, between the steps either
    /// side of it. Times outside the track go to its ends.
    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)
    }

    /// The step nearest `fraction` along the track.
    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,
        }
    }

    /// The edges of `span`, 0 to 1: halfway to the steps either side of it,
    /// or the ends of the track.
    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))
    }

    /// The time between ruler marks on a track `width` pixels wide: a round
    /// amount that keeps the labels [`MARK_SPACING`] apart. `None` when no
    /// time passes.
    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)
    }

    /// The ruler marks on a track `width` pixels wide, at whole multiples of
    /// the [`interval`](Self::interval). None fall inside a compressed gap,
    /// and one too close to the mark before it is left out.
    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
    }
}

/// Moves `places` the least needed to keep each at least `gap` after the
/// one before, within 0 to 1. Places already far enough apart stay put.
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
}

/// Where step `index` of `count` sits when they are spread evenly, 0 to 1.
fn even(index: usize, count: usize) -> f32 {
    if count < 2 {
        return 0.0;
    }
    index.min(count - 1) as f32 / (count - 1) as f32
}

/// The place of `time` on the straight stretch from `from` to `to`.
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)
}

/// Round times between marks, shortest first: 1, 2 and 5 of a power of ten
/// below a second, then the steps a clock face uses, then whole days.
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)
}

/// The default ruler label for `time`, with marks `interval` apart on a
/// track that ends at `end`: milliseconds under a second, seconds under a
/// minute, and minutes and seconds (or hours, minutes and seconds) beyond.
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())
}

/// How many decimal places of a second tell marks `interval` apart.
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(&times, 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(&times, 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");
    }
}