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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
use crate::{
    analysis::{self, possible_time_save, split_color},
    comparison,
    component::splits::Settings as SplitsSettings,
    platform::prelude::*,
    settings::{Color, SemanticColor},
    timing::{
        formatter::{Delta, Regular, SegmentTime, TimeFormatter},
        Snapshot,
    },
    util::Clear,
    GeneralLayoutSettings, Segment, TimeSpan, TimingMethod,
};
use core::fmt::Write;
use serde::{Deserialize, Serialize};

/// The settings of an individual column showing timing information on each
/// split.
#[derive(Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ColumnSettings {
    /// The name of the column.
    pub name: String,
    /// The kind of the column.
    #[serde(flatten)]
    pub kind: ColumnKind,
}

/// The kind of a column. It can either be a column that shows a variable or a
/// time.
#[derive(Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ColumnKind {
    /// A column that shows a variable.
    Variable(VariableColumn),
    /// A column that shows a time.
    Time(TimeColumn),
}

/// A column that shows a time.
#[derive(Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct TimeColumn {
    /// Specifies the value a segment starts out with before it gets replaced
    /// with the current attempt's information when splitting.
    pub start_with: ColumnStartWith,
    /// Once a certain condition is met, which is usually being on the split or
    /// already having completed the split, the time gets updated with the value
    /// specified here.
    pub update_with: ColumnUpdateWith,
    /// Specifies when a column's value gets updated.
    pub update_trigger: ColumnUpdateTrigger,
    /// The comparison chosen. Uses the Timer's current comparison if set to
    /// `None`.
    pub comparison_override: Option<String>,
    /// 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>,
}

/// A column that shows a variable.
#[derive(Default, Clone, Serialize, Deserialize)]
pub struct VariableColumn {
    /// The name of the variable to visualize.
    pub variable_name: String,
}

/// Specifies the value a segment starts out with before it gets replaced
/// with the current attempt's information when splitting.
#[derive(Copy, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum ColumnStartWith {
    /// The column starts out with an empty value.
    Empty,
    /// The column starts out with the times stored in the comparison that is
    /// being compared against.
    ComparisonTime,
    /// The column starts out with the segment times stored in the comparison
    /// that is being compared against.
    ComparisonSegmentTime,
    /// The column starts out with the time that can be saved on each individual
    /// segment stored in the comparison that is being compared against.
    PossibleTimeSave,
}

/// Once a certain condition is met, which is usually being on the split or
/// already having completed the split, the time gets updated with the value
/// specified here.
#[derive(Copy, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum ColumnUpdateWith {
    /// The value doesn't get updated and stays on the value it started out
    /// with.
    DontUpdate,
    /// The value gets replaced by the current attempt's split time.
    SplitTime,
    /// The value gets replaced by the delta of the current attempt's and the
    /// comparison's split time.
    Delta,
    /// The value gets replaced by the delta of the current attempt's and the
    /// comparison's split time. If there is no delta, the value gets replaced
    /// by the current attempt's split time instead.
    DeltaWithFallback,
    /// The value gets replaced by the current attempt's segment time.
    SegmentTime,
    /// The value gets replaced by the current attempt's time saved or lost,
    /// which is how much faster or slower the current attempt's segment time is
    /// compared to the comparison's segment time. This matches the Previous
    /// Segment component.
    SegmentDelta,
    /// The value gets replaced by the current attempt's time saved or lost,
    /// which is how much faster or slower the current attempt's segment time is
    /// compared to the comparison's segment time. This matches the Previous
    /// Segment component. If there is no time saved or lost, then value gets
    /// replaced by the current attempt's segment time instead.
    SegmentDeltaWithFallback,
}

/// Specifies when a column's value gets updated.
#[derive(Copy, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum ColumnUpdateTrigger {
    /// The value gets updated as soon as the segment is started. The value
    /// constantly updates until the segment ends.
    OnStartingSegment,
    /// The value doesn't immediately get updated when the segment is started.
    /// Instead the value constantly gets updated once the segment time is
    /// longer than the best segment time. The final update to the value happens
    /// when the segment ends.
    Contextual,
    /// The value of a segment gets updated once the segment ends.
    OnEndingSegment,
}

impl Default for ColumnSettings {
    fn default() -> Self {
        ColumnSettings {
            name: String::from("Column"),
            kind: ColumnKind::Time(TimeColumn::default()),
        }
    }
}

impl Default for TimeColumn {
    fn default() -> Self {
        TimeColumn {
            start_with: ColumnStartWith::Empty,
            update_with: ColumnUpdateWith::DontUpdate,
            update_trigger: ColumnUpdateTrigger::Contextual,
            comparison_override: None,
            timing_method: None,
        }
    }
}

/// Describes the state of a single segment's column to visualize.
#[derive(Debug, Serialize, Deserialize)]
pub struct ColumnState {
    /// The value shown in the column.
    pub value: String,
    /// The semantic coloring information the value carries.
    pub semantic_color: SemanticColor,
    /// The visual color of the value.
    pub visual_color: Color,
    /// This value indicates whether the column is currently frequently being
    /// updated. This can be used for rendering optimizations.
    pub updates_frequently: bool,
}

impl Clear for ColumnState {
    fn clear(&mut self) {
        self.value.clear();
    }
}

enum ColumnFormatter {
    Time,
    Delta,
    SegmentTime,
}

pub fn update_state(
    state: &mut ColumnState,
    column_settings: &ColumnSettings,
    timer: &Snapshot<'_>,
    splits_settings: &SplitsSettings,
    layout_settings: &GeneralLayoutSettings,
    segment: &Segment,
    segment_index: usize,
    current_split: Option<usize>,
    method: TimingMethod,
) {
    match &column_settings.kind {
        ColumnKind::Variable(column) => {
            state.value.clear();
            if let Some(value) = segment.variables().get(column.variable_name.as_str()) {
                state.value.push_str(value);
            } else if Some(segment_index) == current_split {
                if let Some(value) = timer
                    .run()
                    .metadata()
                    .custom_variable_value(column.variable_name.as_str())
                {
                    // FIXME: We show the live value of the variable, which means it
                    // might update frequently. So we possibly should mark it as
                    // such. However it's currently impossible to tell if it
                    // actually does update frequently. On top of that, the text
                    // component would need to support this as well, as it also
                    // shows the live value of the variable.
                    state.value.push_str(value);
                }
            }
            state.semantic_color = SemanticColor::Default;
            state.visual_color = layout_settings.text_color;
            state.updates_frequently = false;
        }
        ColumnKind::Time(column) => {
            update_time_column(
                state,
                column,
                timer,
                splits_settings,
                layout_settings,
                segment,
                segment_index,
                current_split,
                method,
            );
        }
    }
}

fn update_time_column(
    state: &mut ColumnState,
    column_settings: &TimeColumn,
    timer: &Snapshot<'_>,
    splits_settings: &SplitsSettings,
    layout_settings: &GeneralLayoutSettings,
    segment: &Segment,
    segment_index: usize,
    current_split: Option<usize>,
    method: TimingMethod,
) {
    let method = column_settings.timing_method.unwrap_or(method);
    let resolved_comparison = comparison::resolve(&column_settings.comparison_override, timer);
    let comparison = comparison::or_current(resolved_comparison, timer);
    let update_value = time_column_update_value(
        column_settings,
        timer,
        segment,
        segment_index,
        current_split,
        method,
        comparison,
    );
    let updated = update_value.is_some();
    let ((column_value, semantic_color, formatter), is_live) = update_value.unwrap_or_else(|| {
        (
            match column_settings.start_with {
                ColumnStartWith::Empty => (None, SemanticColor::Default, ColumnFormatter::Time),
                ColumnStartWith::ComparisonTime => (
                    segment.comparison(comparison)[method],
                    SemanticColor::Default,
                    ColumnFormatter::Time,
                ),
                ColumnStartWith::ComparisonSegmentTime => (
                    analysis::comparison_combined_segment_time(
                        timer.run(),
                        segment_index,
                        comparison,
                        method,
                    ),
                    SemanticColor::Default,
                    ColumnFormatter::SegmentTime,
                ),
                ColumnStartWith::PossibleTimeSave => (
                    possible_time_save::calculate(timer, segment_index, comparison, false).0,
                    SemanticColor::Default,
                    ColumnFormatter::SegmentTime,
                ),
            },
            false,
        )
    });
    let is_empty = column_settings.start_with == ColumnStartWith::Empty && !updated;
    state.updates_frequently = is_live && column_value.is_some();
    state.value.clear();
    if !is_empty {
        let _ = match formatter {
            ColumnFormatter::Time => write!(
                state.value,
                "{}",
                Regular::with_accuracy(splits_settings.split_time_accuracy).format(column_value)
            ),
            ColumnFormatter::Delta => write!(
                state.value,
                "{}",
                Delta::custom(
                    splits_settings.delta_drop_decimals,
                    splits_settings.delta_time_accuracy,
                )
                .format(column_value)
            ),
            ColumnFormatter::SegmentTime => {
                write!(
                    state.value,
                    "{}",
                    SegmentTime::with_accuracy(splits_settings.segment_time_accuracy)
                        .format(column_value)
                )
            }
        };
    }
    state.semantic_color = semantic_color;
    state.visual_color = semantic_color.visualize(layout_settings);
}

fn time_column_update_value(
    column: &TimeColumn,
    timer: &Snapshot<'_>,
    segment: &Segment,
    segment_index: usize,
    current_split: Option<usize>,
    method: TimingMethod,
    comparison: &str,
) -> Option<((Option<TimeSpan>, SemanticColor, ColumnFormatter), bool)> {
    use self::{ColumnUpdateTrigger::*, ColumnUpdateWith::*};

    if current_split < Some(segment_index) {
        // Didn't reach the segment yet.
        return None;
    }

    let is_current_split = current_split == Some(segment_index);

    if is_current_split {
        if column.update_trigger == OnEndingSegment {
            // The trigger wants the value to be updated when splitting, not before.
            return None;
        }

        if column.update_trigger == Contextual
            && analysis::check_live_delta(
                timer,
                !column.update_with.is_segment_based(),
                comparison,
                method,
            )
            .is_none()
        {
            // It's contextual and the live delta shouldn't be shown yet.
            return None;
        }
    }

    let is_live = is_current_split;

    let value = match (column.update_with, is_live) {
        (DontUpdate, _) => return None,

        (SplitTime, false) => (
            segment.split_time()[method],
            SemanticColor::Default,
            ColumnFormatter::Time,
        ),
        (SplitTime, true) => (
            timer.current_time()[method],
            SemanticColor::Default,
            ColumnFormatter::Time,
        ),

        (Delta | DeltaWithFallback, false) => {
            let split_time = segment.split_time()[method];
            let delta = catch! {
                split_time? -
                segment.comparison(comparison)[method]?
            };
            let (value, formatter) = if delta.is_none() && column.update_with.has_fallback() {
                (split_time, ColumnFormatter::Time)
            } else {
                (delta, ColumnFormatter::Delta)
            };
            (
                value,
                split_color(timer, delta, segment_index, true, true, comparison, method),
                formatter,
            )
        }
        (Delta | DeltaWithFallback, true) => (
            catch! {
                timer.current_time()[method]? -
                segment.comparison(comparison)[method]?
            },
            SemanticColor::Default,
            ColumnFormatter::Delta,
        ),

        (SegmentTime, false) => (
            analysis::previous_segment_time(timer, segment_index, method),
            SemanticColor::Default,
            ColumnFormatter::SegmentTime,
        ),
        (SegmentTime, true) => (
            analysis::live_segment_time(timer, segment_index, method),
            SemanticColor::Default,
            ColumnFormatter::SegmentTime,
        ),

        (SegmentDelta | SegmentDeltaWithFallback, false) => {
            let delta = analysis::previous_segment_delta(timer, segment_index, comparison, method);
            let (value, formatter) = if delta.is_none() && column.update_with.has_fallback() {
                (
                    analysis::previous_segment_time(timer, segment_index, method),
                    ColumnFormatter::SegmentTime,
                )
            } else {
                (delta, ColumnFormatter::Delta)
            };
            (
                value,
                split_color(timer, delta, segment_index, false, true, comparison, method),
                formatter,
            )
        }
        (SegmentDelta | SegmentDeltaWithFallback, true) => (
            analysis::live_segment_delta(timer, segment_index, comparison, method),
            SemanticColor::Default,
            ColumnFormatter::Delta,
        ),
    };

    Some((value, is_live))
}

impl ColumnUpdateWith {
    const fn is_segment_based(self) -> bool {
        use ColumnUpdateWith::*;
        matches!(self, SegmentDelta | SegmentTime | SegmentDeltaWithFallback)
    }

    const fn has_fallback(self) -> bool {
        use ColumnUpdateWith::*;
        matches!(self, DeltaWithFallback | SegmentDeltaWithFallback)
    }
}