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
use crate::structs::{Header, Line, Note};
use regex::Regex;
use std::collections::HashMap;
use std::path::PathBuf;

error_chain! {
    errors {
        #[doc="duplicate header tag was found"]
        DuplicateHeader(line: u32, tag: &'static str) {
            description("duplicate header")
            display("additional {} tag found in line: {}", line, tag)
        }
        #[doc="an essential header is missing"]
        MissingEssential {
            description("essential header is missing")
        }

        #[doc="value could not be parsed"]
        ValueError(line: u32, field: &'static str) {
            description("could not parse value")
            display("could not parse {} in line: {}", line, field)
        }
        #[doc="an unknown note type was found"]
        UnknownNoteType(line: u32) {
            description("unknown note type")
            display("unknown note type in line: {}", line)
        }
        #[doc="could not parse the line at all"]
        ParserFailure(line: u32) {
            description("could not parse line")
            display("could not parse line: {}", line)
        }
        #[doc="song is missing the end terminator"]
        MissingEndIndicator {
            description("missing end indicator")
        }
        #[doc="song file uses a feature that is not implemented"]
        NotImplemented(line: u32, feature: &'static str) {
            description("not implemented")
            display("the feature {} in line {} is not implemented", line, feature)
        }
    }
}

/// Parses the Header of a given Ultrastar Song and returns a Header struct
///
/// # Arguments
/// * txt_str  - a &str that contains the song to parse
///
pub fn parse_txt_header_str(txt_str: &str) -> Result<Header> {
    let mut opt_title = None;
    let mut opt_artist = None;
    let mut opt_bpm = None;
    let mut opt_audio_path = None;

    let mut opt_gap = None;
    let mut opt_cover_path = None;
    let mut opt_background_path = None;
    let mut opt_video_path = None;
    let mut opt_video_gap = None;
    let mut opt_genre = None;
    let mut opt_edition = None;
    let mut opt_language = None;
    let mut opt_year = None;
    let mut opt_relative = None;
    let mut opt_unknown: Option<HashMap<String, String>> = None;

    lazy_static! {
        static ref RE: Regex = Regex::new(r"#([A-Z3a-z]*):(.*)").unwrap();
    }

    for (line, line_count) in txt_str.lines().zip(1..) {
        let cap = match RE.captures(line) {
            Some(x) => x,
            None => break,
        };
        let key = cap.get(1).unwrap().as_str();
        let value = cap.get(2).unwrap().as_str();

        if value == "" {
            //TODO: somehow warn about this
            continue;
        }

        match key {
            "TITLE" => {
                if opt_title.is_none() {
                    opt_title = Some(String::from(value));
                } else {
                    bail!(ErrorKind::DuplicateHeader(line_count, "TITLE"));
                }
            }
            "ARTIST" => {
                if opt_artist.is_none() {
                    opt_artist = Some(String::from(value));
                } else {
                    bail!(ErrorKind::DuplicateHeader(line_count, "ARTIST"));
                }
            }
            "MP3" => {
                if opt_audio_path.is_none() {
                    opt_audio_path = Some(PathBuf::from(value));
                } else {
                    bail!(ErrorKind::DuplicateHeader(line_count, "MP3"));
                }
            }
            "BPM" => {
                if opt_bpm.is_none() {
                    opt_bpm = match value.replace(",", ".").parse() {
                        Ok(x) => Some(x),
                        Err(_) => {
                            bail!(ErrorKind::ValueError(line_count, "BPM"));
                        }
                    };
                } else {
                    bail!(ErrorKind::DuplicateHeader(line_count, "BPM"));
                }
            }

            // Optional Header fields
            "GAP" => {
                if opt_gap.is_none() {
                    opt_gap = match value.replace(",", ".").parse() {
                        Ok(x) => Some(x),
                        Err(_) => {
                            bail!(ErrorKind::ValueError(line_count, "GAP"));
                        }
                    };
                } else {
                    bail!(ErrorKind::DuplicateHeader(line_count, "GAP"));
                }
            }
            "COVER" => {
                if opt_cover_path.is_none() {
                    opt_cover_path = Some(PathBuf::from(value));
                } else {
                    bail!(ErrorKind::DuplicateHeader(line_count, "COVER"));
                }
            }
            "BACKGROUND" => {
                if opt_background_path.is_none() {
                    opt_background_path = Some(PathBuf::from(value));
                } else {
                    bail!(ErrorKind::DuplicateHeader(line_count, "BACKGROUND"));
                }
            }
            "VIDEO" => {
                if opt_video_path.is_none() {
                    opt_video_path = Some(PathBuf::from(value));
                } else {
                    bail!(ErrorKind::DuplicateHeader(line_count, "VIDEO"));
                }
            }
            "VIDEOGAP" => {
                if opt_video_gap.is_none() {
                    opt_video_gap = match value.replace(",", ".").parse() {
                        Ok(x) => Some(x),
                        Err(_) => {
                            bail!(ErrorKind::ValueError(line_count, "VIDEOGAP"));
                        }
                    };
                } else {
                    bail!(ErrorKind::DuplicateHeader(line_count, "VIDEOGAP"));
                }
            }
            "GENRE" => {
                if opt_genre.is_none() {
                    opt_genre = Some(String::from(value));
                } else {
                    bail!(ErrorKind::DuplicateHeader(line_count, "GENRE"));
                }
            }
            "EDITION" => {
                if opt_edition.is_none() {
                    opt_edition = Some(String::from(value));
                } else {
                    bail!(ErrorKind::DuplicateHeader(line_count, "EDITION"));
                }
            }
            "LANGUAGE" => {
                if opt_language.is_none() {
                    opt_language = Some(String::from(value));
                } else {
                    bail!(ErrorKind::DuplicateHeader(line_count, "LANGUAGE"));
                }
            }
            "YEAR" => {
                if opt_year.is_none() {
                    opt_year = match value.parse() {
                        Ok(x) => Some(x),
                        Err(_) => {
                            bail!(ErrorKind::ValueError(line_count, "YEAR"));
                        }
                    };
                } else {
                    bail!(ErrorKind::DuplicateHeader(line_count, "YEAR"));
                }
            }
            //TODO: check if relative changes line breaks
            "RELATIVE" => {
                if opt_relative.is_none() {
                    opt_relative = match value {
                        "YES" | "yes" => Some(true),
                        "NO" | "no" => Some(false),
                        _ => {
                            bail!(ErrorKind::ValueError(line_count, "RELATIVE"));
                        }
                    }
                } else {
                    bail!(ErrorKind::DuplicateHeader(line_count, "RELATIVE"));
                }
            }
            // use hashmap to store unknown tags
            k => {
                opt_unknown = match opt_unknown {
                    Some(mut x) => {
                        if !x.contains_key(k) {
                            x.insert(String::from(k), String::from(value));
                            Some(x)
                        } else {
                            bail!(ErrorKind::DuplicateHeader(line_count, "UNKNOWN"));
                        }
                    }
                    None => {
                        let mut unknown = HashMap::new();
                        unknown.insert(String::from(k), String::from(value));
                        Some(unknown)
                    }
                };
            }
        };
    }

    // build header from Options
    if let (Some(title), Some(artist), Some(bpm), Some(audio_path)) =
        (opt_title, opt_artist, opt_bpm, opt_audio_path)
    {
        let header = Header {
            title,
            artist,
            bpm,
            audio_path,

            gap: opt_gap,
            cover_path: opt_cover_path,
            background_path: opt_background_path,
            video_path: opt_video_path,
            video_gap: opt_video_gap,
            genre: opt_genre,
            edition: opt_edition,
            language: opt_language,
            year: opt_year,
            relative: opt_relative,
            unknown: opt_unknown,
        };
        // header complete
        Ok(header)
    } else {
        // essential field is missing
        bail!(ErrorKind::MissingEssential)
    }
}

/// Parses the lyric lines of a given Ultarstar song and returns a vector of Line structs
///
/// # Arguments
/// * txt_str  - a &str that contains the song to parse
///
pub fn parse_txt_lines_str(txt_str: &str) -> Result<Vec<Line>> {
    lazy_static! {
        static ref LINE_RE: Regex = Regex::new("^-\\s?(-?[0-9]+)\\s*$").unwrap();
        static ref LREL_RE: Regex = Regex::new("^-\\s?(-?[0-9]+)\\s+(-?[0-9]+)").unwrap();
        static ref NOTE_RE: Regex =
            Regex::new("^(.)\\s*(-?[0-9]+)\\s+(-?[0-9]+)\\s+(-?[0-9]+)\\s?(.*)").unwrap();
        static ref DUET_RE: Regex = Regex::new("^P\\s?(-?[0-9]+)").unwrap();
    }

    let mut lines_vec = Vec::new();
    let mut current_line = Line {
        start: 0,
        rel: None,
        notes: Vec::new(),
    };

    let mut found_end_indicator = false;
    for (line, line_count) in txt_str.lines().zip(1..) {
        let first_char = match line.chars().nth(0) {
            Some(x) => x,
            None => bail!(ErrorKind::ParserFailure(line_count)),
        };

        // ignore header
        if first_char == '#' {
            continue;
        }

        // not implemented
        if first_char == 'B' {
            bail!(ErrorKind::NotImplemented(line_count, "variable bpm"));
        }

        // stop parsing after end symbol
        if first_char == 'E' {
            lines_vec.push(current_line);
            found_end_indicator = true;
            break;
        }

        // current line is a note
        if NOTE_RE.is_match(line) {
            let cap = NOTE_RE.captures(line).unwrap();

            let note_start = match cap.get(2).unwrap().as_str().parse() {
                Ok(x) => x,
                Err(_) => {
                    bail!(ErrorKind::ValueError(line_count, "note start"));
                }
            };
            let note_duration = match cap.get(3).unwrap().as_str().parse() {
                Ok(x) => {
                    if x >= 0 {
                        x
                    } else {
                        bail!(ErrorKind::ValueError(line_count, "note duration"));
                    }
                }
                Err(_) => {
                    bail!(ErrorKind::ValueError(line_count, "note duration"));
                }
            };
            let note_pitch = match cap.get(4).unwrap().as_str().parse() {
                Ok(x) => x,
                Err(_) => {
                    bail!(ErrorKind::ValueError(line_count, "note pitch"));
                }
            };
            let note_text = cap.get(5).unwrap().as_str();

            let note = match cap.get(1).unwrap().as_str() {
                ":" => Note::Regular {
                    start: note_start,
                    duration: note_duration,
                    pitch: note_pitch,
                    text: String::from(note_text),
                },
                "*" => Note::Golden {
                    start: note_start,
                    duration: note_duration,
                    pitch: note_pitch,
                    text: String::from(note_text),
                },
                "F" => Note::Freestyle {
                    start: note_start,
                    duration: note_duration,
                    pitch: note_pitch,
                    text: String::from(note_text),
                },
                _ => bail!(ErrorKind::UnknownNoteType(line_count)),
            };

            current_line.notes.push(note);
            continue;
        }

        // current line is a line break
        if LINE_RE.is_match(line) {
            // push old line to the Line vector and prepare new line
            lines_vec.push(current_line);
            let cap = LINE_RE.captures(line).unwrap();
            let line_start = match cap.get(1).unwrap().as_str().parse() {
                Ok(x) => x,
                Err(_) => {
                    bail!(ErrorKind::ValueError(line_count, "line start"));
                }
            };
            current_line = Line {
                start: line_start,
                rel: None,
                notes: Vec::new(),
            };
            continue;
        }

        // current line is a relative line break
        if LREL_RE.is_match(line) {
            // push old line to the Line vector and prepare new line
            lines_vec.push(current_line);
            let cap = LREL_RE.captures(line).unwrap();
            let line_start = match cap.get(1).unwrap().as_str().parse() {
                Ok(x) => x,
                Err(_) => {
                    bail!(ErrorKind::ValueError(line_count, "line start"));
                }
            };
            let line_rel = match cap.get(2).unwrap().as_str().parse() {
                Ok(x) => x,
                Err(_) => {
                    bail!(ErrorKind::ValueError(line_count, "line rel"));
                }
            };
            current_line = Line {
                start: line_start,
                rel: Some(line_rel),
                notes: Vec::new(),
            };
            continue;
        }

        if DUET_RE.is_match(line) {
            let cap = DUET_RE.captures(line).unwrap();
            let note = match cap.get(1).unwrap().as_str().parse() {
                Ok(x) => {
                    if x >= 1 && x <= 3 {
                        Note::PlayerChange { player: x }
                    } else {
                        bail!(ErrorKind::ValueError(line_count, "player change"));
                    }
                }
                Err(_) => {
                    bail!(ErrorKind::ValueError(line_count, "player change"));
                }
            };
            current_line.notes.push(note);
            continue;
        } else {
            // unknown line
            bail!(ErrorKind::ParserFailure(line_count));
        }
    }
    if found_end_indicator {
        Ok(lines_vec)
    } else {
        bail!(ErrorKind::MissingEndIndicator);
    }
}