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
use super::{Editor, SegmentRow, TimingMethod};
use crate::comparison::personal_best;
use crate::run::RunMetadata;
use crate::timing::formatter::none_wrapper::EmptyWrapper;
use crate::timing::formatter::{Accuracy, Short, TimeFormatter};
use crate::CachedImageId;
use serde_json::{to_writer, Result as JsonResult};
use std::io::Write;

/// Represents the current state of the Run Editor in order to visualize it
/// properly.
#[derive(Debug, Serialize, Deserialize)]
pub struct State {
    /// The game's icon encoded as a Data URL. This value is only specified
    /// whenever the icon changes. The String itself may be empty. This
    /// indicates that there is no icon.
    pub icon_change: Option<String>,
    /// The name of the game the Run is for.
    pub game: String,
    /// The name of the category the Run is for.
    pub category: String,
    /// The timer offset specifies the time that the timer starts at when
    /// starting a new attempt.
    pub offset: String,
    /// The number of times this Run has been attempted by the runner. This
    /// is mostly just a visual number and has no effect on any history.
    pub attempts: u32,
    /// The timing method that is currently selected to be visualized and
    /// edited.
    pub timing_method: TimingMethod,
    /// The state of all the segments.
    pub segments: Vec<Segment>,
    /// The names of all the custom comparisons that exist for this Run.
    pub comparison_names: Vec<String>,
    /// Describes which actions are currently available.
    pub buttons: Buttons,
    /// Additional metadata of this Run, like the platform and region of the
    /// game.
    pub metadata: RunMetadata,
}

/// Describes which actions are currently available. Depending on how many
/// segments exist and which ones are selected, only some actions can be
/// executed successfully.
#[derive(Debug, Serialize, Deserialize)]
pub struct Buttons {
    /// Describes whether the currently selected segments can be removed. If all
    /// segments are selected, they can't be removed.
    pub can_remove: bool,
    /// Describes whether the currently selected segments can be moved up. If
    /// any one of the selected segments is the first segment, then they can't
    /// be moved.
    pub can_move_up: bool,
    /// Describes whether the currently selected segments can be moved down. If
    /// any one of the selected segments is the last segment, then they can't be
    /// moved.
    pub can_move_down: bool,
}

/// Describes the current state of a segment.
#[derive(Debug, Serialize, Deserialize)]
pub struct Segment {
    /// The segment's icon encoded as a Data URL. This value is only specified
    /// whenever the icon changes. The String itself may be empty. This
    /// indicates that there is no icon.
    pub icon_change: Option<String>,
    /// The name of the segment.
    pub name: String,
    /// The segment's split time for the active timing method.
    pub split_time: String,
    /// The segment time for the active timing method.
    pub segment_time: String,
    /// The best segment time for the active timing method.
    pub best_segment_time: String,
    /// All of the times of the custom comparison for the active timing method.
    /// The order of these matches up with the order of the custom comparisons
    /// provided by the Run Editor's State object.
    pub comparison_times: Vec<String>,
    /// Describes the segment's selection state.
    pub selected: SelectionState,
}

/// Describes a segment's selection state.
#[derive(Debug, Serialize, Deserialize)]
pub enum SelectionState {
    /// The segment is not selected.
    NotSelected,
    /// The segment is selected.
    Selected,
    /// The segment is selected and active. There is only one active segment and
    /// it is the one that is being actively edited.
    Active,
}

impl State {
    /// Encodes the state object's information as JSON.
    pub fn write_json<W>(&self, writer: W) -> JsonResult<()>
    where
        W: Write,
    {
        to_writer(writer, self)
    }
}

impl Editor {
    /// Calculates the Run Editor's state in order to visualize it.
    pub fn state(&mut self) -> State {
        let formatter = EmptyWrapper::new(Short::with_accuracy(Accuracy::Hundredths));

        let icon_change = self
            .game_icon_id
            .update_with(self.run.game_icon().into())
            .map(str::to_owned);
        let game = self.game_name().to_string();
        let category = self.category_name().to_string();
        let offset = formatter.format(self.offset()).to_string();
        let attempts = self.attempt_count();
        let timing_method = self.selected_timing_method();
        let comparison_names = self
            .custom_comparisons()
            .iter()
            .cloned()
            .filter(|n| n != personal_best::NAME)
            .collect::<Vec<_>>();

        let buttons = Buttons {
            can_remove: self.can_remove_segments(),
            can_move_up: self.can_move_segments_up(),
            can_move_down: self.can_move_segments_down(),
        };
        let mut segments = Vec::with_capacity(self.run.len());

        self.segment_icon_ids
            .resize(self.run.len(), CachedImageId::default());

        for segment_index in 0..self.run.len() {
            let (name, split_time, segment_time, best_segment_time, comparison_times);
            {
                let row = SegmentRow::new(segment_index, self);
                name = row.name().to_string();
                split_time = formatter.format(row.split_time()).to_string();
                segment_time = formatter.format(row.segment_time()).to_string();
                best_segment_time = formatter.format(row.best_segment_time()).to_string();
                comparison_times = comparison_names
                    .iter()
                    .map(|c| formatter.format(row.comparison_time(c)).to_string())
                    .collect();
            }

            let icon_change = self.segment_icon_ids[segment_index]
                .update_with(self.run.segment(segment_index).icon().into())
                .map(str::to_owned);

            let selected = if self.active_segment_index() == segment_index {
                SelectionState::Active
            } else if self.selected_segments.contains(&segment_index) {
                SelectionState::Selected
            } else {
                SelectionState::NotSelected
            };

            segments.push(Segment {
                icon_change,
                name,
                split_time,
                segment_time,
                best_segment_time,
                comparison_times,
                selected,
            });
        }

        State {
            icon_change,
            game,
            category,
            offset,
            attempts,
            timing_method,
            segments,
            comparison_names,
            buttons,
            metadata: self.run.metadata().clone(),
        }
    }
}