livesplit-core 0.13.0

livesplit-core is a library that provides a lot of functionality for creating a speedrun timer.
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
//! Provides the `Timer` Component and relevant types for using it. The `Timer`
//! Component is a component that shows the total time of the current attempt as
//! a digital clock. The color of the time shown is based on a how well the
//! current attempt is doing compared to the chosen comparison.

use crate::{
    analysis::split_color,
    platform::prelude::*,
    settings::{Color, Field, Gradient, SemanticColor, SettingsDescription, Value},
    timing::{
        formatter::{timer as formatter, Accuracy, DigitsFormat, TimeFormatter},
        Snapshot,
    },
    GeneralLayoutSettings, TimeSpan, TimerPhase, TimingMethod,
};
use core::fmt::Write;
use serde::{Deserialize, Serialize};

/// The `Timer` Component is a component that shows the total time of the current
/// attempt as a digital clock. The color of the time shown is based on a how
/// well the current attempt is doing compared to the chosen comparison.
#[derive(Default, Clone)]
pub struct Component {
    settings: Settings,
}

/// Represents the possible backgrounds for a timer.
#[derive(Copy, Clone, PartialEq, Serialize, Deserialize)]
#[serde(from = "serialize::DeltaGradient", into = "serialize::DeltaGradient")]
pub enum DeltaGradient {
    /// A normal gradient of some kind
    Gradient(Gradient),
    /// Delta based plain color
    DeltaPlain,
    /// Delta based gradient, Vertical
    DeltaVertical,
    /// Delta based gradient, horizontal
    DeltaHorizontal,
}

impl From<Gradient> for DeltaGradient {
    fn from(g: Gradient) -> Self {
        Self::Gradient(g)
    }
}

impl Default for DeltaGradient {
    fn default() -> Self {
        Self::Gradient(Gradient::default())
    }
}

impl DeltaGradient {
    /// Converts the DeltaGradient to a normal gradient for purposes of rendering
    ///
    ///  # Arguments
    /// * `delta` - the color used to represent the timer's current state
    pub fn gradient(&self, delta: Color) -> Gradient {
        let [h, s, v, a] = delta.to_hsva();

        match self {
            DeltaGradient::Gradient(g) => *g,
            DeltaGradient::DeltaVertical => {
                let color_a = Color::hsva(h, s * 0.5, v * 0.25, a * (1.0 / 6.0));
                let color_b = Color::hsva(h, s * 0.5, v * 0.25, a);

                Gradient::Vertical(color_a, color_b)
            }
            DeltaGradient::DeltaPlain => {
                Gradient::Plain(Color::hsva(h, s * 0.5, v * 0.25, a * (7.0 / 12.0)))
            }
            DeltaGradient::DeltaHorizontal => {
                let color_a = Color::hsva(h, s * 0.5, v * 0.25, a * (1.0 / 6.0));
                let color_b = Color::hsva(h, s * 0.5, v * 0.25, a);

                Gradient::Horizontal(color_a, color_b)
            }
        }
    }
}
/// The Settings for this component.
#[derive(Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Settings {
    /// The background shown behind the component.
    pub background: DeltaGradient,
    /// Specifies the Timing Method to use. If set to `None` the Timing Method
    /// of the Timer is used for showing the time. Otherwise the Timing Method
    /// provided is used.
    pub timing_method: Option<TimingMethod>,
    /// The height of the timer.
    pub height: u32,
    /// Instead of automatically determining the color of the time shown, based
    /// on a how well the current attempt is doing, a specific color to always
    /// be used can be provided instead.
    pub color_override: Option<Color>,
    /// The Timer Component automatically converts the color it is supposed to
    /// use into a gradient and shows that. If this is set to `false` the actual
    /// color is used instead of a gradient.
    pub show_gradient: bool,
    /// Determines how many digits are to always be shown. If the duration is
    /// lower than the digits to be shown, they are filled up with zeros.
    pub digits_format: DigitsFormat,
    /// The accuracy of the time shown.
    pub accuracy: Accuracy,
    /// Specifies whether to show the how much time has passed since the start
    /// current segment, rather than how much time has passed since the start of
    /// the current attempt.
    pub is_segment_timer: bool,
}

impl Default for Settings {
    fn default() -> Self {
        Self {
            background: DeltaGradient::default(),
            timing_method: None,
            height: 60,
            color_override: None,
            show_gradient: true,
            digits_format: DigitsFormat::SingleDigitSeconds,
            accuracy: Accuracy::Hundredths,
            is_segment_timer: false,
        }
    }
}

/// The state object describes the information to visualize for this component.
#[derive(Default, Serialize, Deserialize)]
pub struct State {
    /// The background shown behind the component.
    pub background: Gradient,
    /// The time shown by the component without the fractional part.
    pub time: String,
    /// The fractional part of the time shown (including the dot).
    pub fraction: String,
    /// The semantic coloring information the time carries.
    pub semantic_color: SemanticColor,
    /// The top color of the timer's gradient.
    pub top_color: Color,
    /// The bottom color of the timer's gradient.
    pub bottom_color: Color,
    /// The height of the timer.
    pub height: u32,
    /// This value indicates whether the timer is currently frequently being
    /// updated. This can be used for rendering optimizations.
    pub updates_frequently: bool,
}

#[cfg(feature = "std")]
impl State {
    /// Encodes the state object's information as JSON.
    pub fn write_json<W>(&self, writer: W) -> serde_json::Result<()>
    where
        W: std::io::Write,
    {
        serde_json::to_writer(writer, self)
    }
}

impl Component {
    /// Creates a new Timer Component.
    pub fn new() -> Self {
        Default::default()
    }

    /// Creates a new Timer Component with the given settings.
    pub const fn with_settings(settings: Settings) -> Self {
        Self { settings }
    }

    /// Accesses the settings of the component.
    pub const fn settings(&self) -> &Settings {
        &self.settings
    }

    /// Grants mutable access to the settings of the component.
    pub fn settings_mut(&mut self) -> &mut Settings {
        &mut self.settings
    }

    /// Accesses the name of the component.
    pub const fn name(&self) -> &'static str {
        if self.settings.is_segment_timer {
            "Segment Timer"
        } else {
            "Timer"
        }
    }

    /// Updates the component's state based on the timer and layout settings
    /// provided.
    pub fn update_state(
        &self,
        state: &mut State,
        timer: &Snapshot<'_>,
        layout_settings: &GeneralLayoutSettings,
    ) {
        let method = self
            .settings
            .timing_method
            .unwrap_or_else(|| timer.current_timing_method());

        let phase = timer.current_phase();

        let (time, semantic_color) = if self.settings.is_segment_timer {
            let last_split_index = if phase == TimerPhase::Ended {
                timer.run().len() - 1
            } else {
                timer.current_split_index().unwrap_or_default()
            };
            let mut segment_time = calculate_live_segment_time(timer, method, last_split_index);

            if segment_time.is_none() && method == TimingMethod::GameTime {
                segment_time =
                    calculate_live_segment_time(timer, TimingMethod::RealTime, last_split_index);
            }

            (segment_time, SemanticColor::Default)
        } else {
            let time = timer.current_time();
            let time = time[method].or(time.real_time).unwrap_or_default();
            let current_comparison = timer.current_comparison();

            let semantic_color = match phase {
                TimerPhase::Running if time >= TimeSpan::zero() => {
                    let pb_split_time = timer
                        .current_split()
                        .unwrap()
                        .comparison(current_comparison)[method];

                    if let Some(pb_split_time) = pb_split_time {
                        split_color(
                            timer,
                            Some(time - pb_split_time),
                            timer.current_split_index().unwrap(),
                            true,
                            false,
                            current_comparison,
                            method,
                        )
                        .or(SemanticColor::AheadGainingTime)
                    } else {
                        SemanticColor::AheadGainingTime
                    }
                }
                TimerPhase::Paused => SemanticColor::Paused,
                TimerPhase::Ended => {
                    let pb_time = timer
                        .run()
                        .segments()
                        .last()
                        .unwrap()
                        .comparison(current_comparison)[method];

                    if pb_time.map_or(true, |t| time < t) {
                        SemanticColor::PersonalBest
                    } else {
                        SemanticColor::BehindLosingTime
                    }
                }
                _ => SemanticColor::NotRunning,
            };

            (Some(time), semantic_color)
        };

        let not_overwritten_visual_color = semantic_color.visualize(layout_settings);
        let visual_color = if let Some(color) = self.settings.color_override {
            color
        } else {
            not_overwritten_visual_color
        };

        (state.top_color, state.bottom_color) = if self.settings.show_gradient {
            top_and_bottom_color(visual_color)
        } else {
            (visual_color, visual_color)
        };

        state.background = self
            .settings
            .background
            .gradient(not_overwritten_visual_color);

        state.time.clear();
        let _ = write!(
            state.time,
            "{}",
            formatter::Time::with_digits_format(self.settings.digits_format).format(time),
        );

        state.fraction.clear();
        let _ = write!(
            state.fraction,
            "{}",
            formatter::Fraction::with_accuracy(self.settings.accuracy).format(time),
        );

        state.updates_frequently = phase.is_running() && time.is_some();
        state.semantic_color = semantic_color;
        state.height = self.settings.height;
    }

    /// Calculates the component's state based on the timer and the layout
    /// settings provided.
    pub fn state(&self, timer: &Snapshot<'_>, layout_settings: &GeneralLayoutSettings) -> State {
        let mut state = Default::default();
        self.update_state(&mut state, timer, layout_settings);
        state
    }

    /// Accesses a generic description of the settings available for this
    /// component and their current values.
    pub fn settings_description(&self) -> SettingsDescription {
        SettingsDescription::with_fields(vec![
            Field::new("Background".into(), self.settings.background.into()),
            Field::new(
                "Segment Timer".into(),
                self.settings.is_segment_timer.into(),
            ),
            Field::new("Timing Method".into(), self.settings.timing_method.into()),
            Field::new("Height".into(), u64::from(self.settings.height).into()),
            Field::new("Text Color".into(), self.settings.color_override.into()),
            Field::new("Show Gradient".into(), self.settings.show_gradient.into()),
            Field::new("Digits Format".into(), self.settings.digits_format.into()),
            Field::new("Accuracy".into(), self.settings.accuracy.into()),
        ])
    }

    /// Sets a setting's value by its index to the given value.
    ///
    /// # Panics
    ///
    /// This panics if the type of the value to be set is not compatible with
    /// the type of the setting's value. A panic can also occur if the index of
    /// the setting provided is out of bounds.
    pub fn set_value(&mut self, index: usize, value: Value) {
        match index {
            0 => self.settings.background = value.into(),
            1 => self.settings.is_segment_timer = value.into(),
            2 => self.settings.timing_method = value.into(),
            3 => self.settings.height = value.into_uint().unwrap() as _,
            4 => self.settings.color_override = value.into(),
            5 => self.settings.show_gradient = value.into(),
            6 => self.settings.digits_format = value.into(),
            7 => self.settings.accuracy = value.into(),
            _ => panic!("Unsupported Setting Index"),
        }
    }
}

/// Calculates the top and bottom color the Timer Component would use for the
/// gradient of the times it is showing.
pub fn top_and_bottom_color(color: Color) -> (Color, Color) {
    let [h, s, v, a] = color.to_hsva();

    let top_color = Color::hsva(h, 0.5 * s, (1.5 * v + 0.1).min(1.0), a);
    let bottom_color = Color::hsva(h, s, 0.8 * v, a);

    (top_color, bottom_color)
}

fn calculate_live_segment_time(
    timer: &Snapshot<'_>,
    timing_method: TimingMethod,
    last_split_index: usize,
) -> Option<TimeSpan> {
    let last_split = if last_split_index > 0 {
        timer.run().segment(last_split_index - 1).split_time()[timing_method]
    } else {
        Some(TimeSpan::zero())
    };

    if timer.current_phase() == TimerPhase::NotRunning {
        Some(timer.run().offset())
    } else {
        Some(timer.current_time()[timing_method]? - last_split?)
    }
}

// FIXME: Workaround for #[serde(flatten)] not being a thing on enums.
mod serialize {
    #[derive(serde::Serialize, serde::Deserialize)]
    #[serde(untagged)]
    pub enum DeltaGradient {
        Gradient(super::Gradient),
        Delta(Delta),
    }

    #[derive(serde::Serialize, serde::Deserialize)]
    #[allow(clippy::enum_variant_names)]
    pub enum Delta {
        DeltaPlain,
        DeltaVertical,
        DeltaHorizontal,
    }

    impl From<DeltaGradient> for super::DeltaGradient {
        fn from(v: DeltaGradient) -> Self {
            match v {
                DeltaGradient::Gradient(g) => super::DeltaGradient::Gradient(g),
                DeltaGradient::Delta(d) => match d {
                    Delta::DeltaPlain => super::DeltaGradient::DeltaPlain,
                    Delta::DeltaVertical => super::DeltaGradient::DeltaVertical,
                    Delta::DeltaHorizontal => super::DeltaGradient::DeltaHorizontal,
                },
            }
        }
    }

    impl From<super::DeltaGradient> for DeltaGradient {
        fn from(v: super::DeltaGradient) -> Self {
            match v {
                super::DeltaGradient::Gradient(g) => DeltaGradient::Gradient(g),
                super::DeltaGradient::DeltaPlain => DeltaGradient::Delta(Delta::DeltaPlain),
                super::DeltaGradient::DeltaVertical => DeltaGradient::Delta(Delta::DeltaVertical),
                super::DeltaGradient::DeltaHorizontal => {
                    DeltaGradient::Delta(Delta::DeltaHorizontal)
                }
            }
        }
    }
}