osu-file-parser 1.1.0

A crate to parse an osu! beatmap file
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
pub mod audio_sample;
pub mod error;
pub mod normal_event;
pub mod storyboard;

use nom::branch::alt;
use nom::combinator::{cut, eof, peek, success};
use nom::sequence::tuple;
use nom::Parser;
use nom::{bytes::complete::tag, combinator::rest, sequence::preceded};

use crate::events::storyboard::cmds::CommandProperties;
use crate::helper::trait_ext::MapOptStringNewLine;
use crate::osb::Variable;
use crate::parsers::comma;

use self::storyboard::cmds::Command;
use self::storyboard::error::CommandPushError;
use self::storyboard::{error::ParseObjectError, sprites::Object};

use super::Version;
use super::{types::Error, Integer, VersionedDefault, VersionedFromStr, VersionedToString};

pub use audio_sample::*;
pub use error::*;
pub use normal_event::*;

#[derive(Default, Clone, Debug, Hash, PartialEq, Eq)]
pub struct Events(pub Vec<Event>);

const OLD_VERSION_TIME_OFFSET: Integer = 24;

impl VersionedFromStr for Events {
    type Err = Error<ParseError>;

    fn from_str(s: &str, version: Version) -> std::result::Result<Option<Self>, Self::Err> {
        Events::from_str_variables(s, version, &[])
    }
}

impl Events {
    pub fn from_str_variables(
        s: &str,
        version: Version,
        variables: &[Variable],
    ) -> std::result::Result<Option<Self>, Error<ParseError>> {
        let mut events = Events(Vec::new());

        #[derive(Clone)]
        enum NormalEventType {
            Background,
            Video,
            Break,
            ColourTransformation,
            SpriteLegacy,
            AnimationLegacy,
            SampleLegacy,
            Other,
        }

        let mut comment = preceded::<_, _, _, nom::error::Error<_>, _, _>(tag("//"), rest);
        let background = || {
            peek(tuple((
                tag::<_, _, nom::error::Error<_>>(normal_event::BACKGROUND_HEADER),
                cut(alt((eof, comma()))),
            )))
            .map(|_| NormalEventType::Background)
        };
        let video = || {
            peek(tuple((
                alt((
                    tag(normal_event::VIDEO_HEADER),
                    tag(normal_event::VIDEO_HEADER_LONG),
                )),
                cut(alt((eof, comma()))),
            )))
            .map(|_| NormalEventType::Video)
        };
        let break_ = || {
            peek(tuple((
                alt((
                    tag(normal_event::BREAK_HEADER),
                    tag(normal_event::BREAK_HEADER_LONG),
                )),
                cut(alt((eof, comma()))),
            )))
            .map(|_| NormalEventType::Break)
        };
        let colour_transformation = || {
            peek(tuple((
                tag(normal_event::COLOUR_TRANSFORMATION_HEADER),
                cut(alt((eof, comma()))),
            )))
            .map(|_| NormalEventType::ColourTransformation)
        };
        let sprite_legacy = || {
            peek(tuple((
                tag(normal_event::SPRITE_LEGACY_HEADER),
                cut(alt((eof, comma()))),
            )))
            .map(|_| NormalEventType::SpriteLegacy)
        };
        let animation_legacy = || {
            peek(tuple((
                tag(normal_event::ANIMATION_LEGACY_HEADER),
                cut(alt((eof, comma()))),
            )))
            .map(|_| NormalEventType::AnimationLegacy)
        };
        let sample_legacy = || {
            peek(tuple((
                tag(normal_event::SAMPLE_LEGACY_HEADER),
                cut(alt((eof, comma()))),
            )))
            .map(|_| NormalEventType::SampleLegacy)
        };

        for (line_index, line) in s.lines().enumerate() {
            if line.trim().is_empty() {
                continue;
            }

            if let Ok((_, comment)) = comment(line) {
                events.0.push(Event::Comment(comment.to_string()));
                continue;
            }

            let indent = line.chars().take_while(|c| *c == ' ' || *c == '_').count();

            // its a storyboard command
            if indent > 0 {
                let cmd_parse = || {
                    let line_without_header = match line.chars().position(|c| c == ',') {
                        Some(i) => &line[i + 1..],
                        None => line,
                    };

                    let mut line_with_variable: Option<String> = None;
                    for variable in variables {
                        let variable_full = format!("${}", variable.name);

                        if line_without_header.contains(&variable_full) {
                            let new_line = match line_with_variable {
                                Some(line_with_variable) => {
                                    line_with_variable.replace(&variable_full, &variable.value)
                                }
                                None => line.replace(&variable_full, &variable.value),
                            };

                            line_with_variable = Some(new_line);
                        }
                    }

                    match line_with_variable {
                        Some(line_with_variable) => Error::new_from_result_into(
                            Command::from_str(&line_with_variable, version),
                            line_index,
                        ),
                        None => Error::new_from_result_into(
                            Command::from_str(line, version),
                            line_index,
                        ),
                    }
                };

                match events.0.last_mut() {
                    Some(event) => match event {
                        Event::Background(bg) => {
                            if let Some(cmd) = cmd_parse()? {
                                Error::new_from_result_into(
                                    bg.try_push_cmd(cmd, indent),
                                    line_index,
                                )?
                            }
                        }
                        Event::Video(video) => {
                            if let Some(cmd) = cmd_parse()? {
                                Error::new_from_result_into(
                                    video.try_push_cmd(cmd, indent),
                                    line_index,
                                )?
                            }
                        }
                        Event::SpriteLegacy(sprite) => {
                            if let Some(cmd) = cmd_parse()? {
                                Error::new_from_result_into(
                                    sprite.try_push_cmd(cmd, indent),
                                    line_index,
                                )?
                            }
                        }
                        Event::AnimationLegacy(animation) => {
                            if let Some(cmd) = cmd_parse()? {
                                Error::new_from_result_into(
                                    animation.try_push_cmd(cmd, indent),
                                    line_index,
                                )?
                            }
                        }
                        Event::SampleLegacy(sample) => {
                            if let Some(cmd) = cmd_parse()? {
                                Error::new_from_result_into(
                                    sample.try_push_cmd(cmd, indent),
                                    line_index,
                                )?
                            }
                        }
                        Event::StoryboardObject(obj) => {
                            if let Some(cmd) = cmd_parse()? {
                                Error::new_from_result_into(
                                    obj.try_push_cmd(cmd, indent),
                                    line_index,
                                )?
                            }
                        }
                        _ => {
                            return Err(Error::new(
                                ParseError::StoryboardCmdWithNoSprite,
                                line_index,
                            ))
                        }
                    },
                    _ => {
                        return Err(Error::new(
                            ParseError::StoryboardCmdWithNoSprite,
                            line_index,
                        ))
                    }
                }
                continue;
            }

            // normal event trying
            let (_, type_) = alt((
                background(),
                video(),
                break_(),
                colour_transformation(),
                sprite_legacy(),
                animation_legacy(),
                sample_legacy(),
                success(NormalEventType::Other),
            ))(line)
            .unwrap();

            let res = match type_ {
                NormalEventType::Background => Background::from_str(line, version)
                    .map(|e| e.map(Event::Background))
                    .map_err(ParseError::ParseBackgroundError),
                NormalEventType::Video => Video::from_str(line, version)
                    .map(|e| e.map(Event::Video))
                    .map_err(ParseError::ParseVideoError),
                NormalEventType::Break => Break::from_str(line, version)
                    .map(|e| e.map(Event::Break))
                    .map_err(ParseError::ParseBreakError),
                NormalEventType::ColourTransformation => {
                    ColourTransformation::from_str(line, version)
                        .map(|e| e.map(Event::ColourTransformation))
                        .map_err(ParseError::ParseColourTransformationError)
                }
                NormalEventType::SpriteLegacy => SpriteLegacy::from_str(line, version)
                    .map(|e| e.map(Event::SpriteLegacy))
                    .map_err(ParseError::ParseSpriteLegacyError),
                NormalEventType::AnimationLegacy => AnimationLegacy::from_str(line, version)
                    .map(|e| e.map(Event::AnimationLegacy))
                    .map_err(ParseError::ParseAnimationLegacyError),
                NormalEventType::SampleLegacy => SampleLegacy::from_str(line, version)
                    .map(|e| e.map(Event::SampleLegacy))
                    .map_err(ParseError::ParseSampleLegacyError),
                NormalEventType::Other => {
                    // is it a storyboard object?
                    match Object::from_str(line, version) {
                        Ok(e) => Ok(e.map(Event::StoryboardObject)),
                        Err(err) => {
                            if let ParseObjectError::UnknownObjectType = err {
                                // try AudioSample
                                AudioSample::from_str(line, version)
                                    .map(|e| e.map(Event::AudioSample))
                                    .map_err(|e| {
                                        if let ParseAudioSampleError::WrongEvent = e {
                                            ParseError::UnknownEventType
                                        } else {
                                            ParseError::ParseAudioSampleError(e)
                                        }
                                    })
                            } else {
                                Err(ParseError::ParseStoryboardObjectError(err))
                            }
                        }
                    }
                }
            };

            match res {
                Ok(event) => {
                    if let Some(event) = event {
                        events.0.push(event)
                    }
                }
                Err(e) => return Err(Error::new(e, line_index)),
            }
        }

        Ok(Some(events))
    }

    pub fn to_string_variables(&self, version: Version, variables: &[Variable]) -> Option<String> {
        let mut s = self
            .0
            .iter()
            .map(|event| event.to_string_variables(version, variables));

        Some(s.map_string_new_line())
    }
}

impl VersionedToString for Events {
    fn to_string(&self, version: Version) -> Option<String> {
        self.to_string_variables(version, &[])
    }
}

impl VersionedDefault for Events {
    fn default(_: Version) -> Option<Self> {
        Some(Events(Vec::new()))
    }
}

#[derive(Clone, Debug, Hash, PartialEq, Eq)]
#[non_exhaustive]
/// All possible events types.
pub enum Event {
    Comment(String),
    Background(Background),
    Video(Video),
    Break(Break),
    ColourTransformation(ColourTransformation),
    SpriteLegacy(SpriteLegacy),
    AnimationLegacy(AnimationLegacy),
    SampleLegacy(SampleLegacy),
    StoryboardObject(Object),
    AudioSample(AudioSample),
}

impl VersionedToString for Event {
    fn to_string(&self, version: Version) -> Option<String> {
        self.to_string_variables(version, &[])
    }
}

impl Event {
    pub fn to_string_variables(&self, version: Version, variables: &[Variable]) -> Option<String> {
        match self {
            Event::Comment(comment) => Some(format!("//{comment}")),
            Event::Background(background) => background.to_string(version),
            Event::Video(video) => video.to_string(version),
            Event::Break(break_) => break_.to_string(version),
            Event::ColourTransformation(colour_trans) => colour_trans.to_string(version),
            Event::SpriteLegacy(sprite) => sprite.to_string_variables(version, variables),
            Event::AnimationLegacy(animation) => animation.to_string_variables(version, variables),
            Event::SampleLegacy(sample) => sample.to_string_variables(version, variables),
            Event::StoryboardObject(object) => object.to_string_variables(version, variables),
            Event::AudioSample(audio_sample) => Some(audio_sample.to_string(version).unwrap()),
        }
    }
}

fn commands_to_string_variables(
    cmds: &[Command],
    version: Version,
    variables: &[Variable],
) -> Option<String> {
    let mut builder = Vec::new();
    let mut indentation = 1usize;

    for cmd in cmds {
        builder.push(format!(
            "{}{}",
            " ".repeat(indentation),
            cmd.to_string_variables(version, variables).unwrap()
        ));

        if let CommandProperties::Loop { commands, .. }
        | CommandProperties::Trigger { commands, .. } = &cmd.properties
        {
            if commands.is_empty() {
                continue;
            }

            let starting_indentation = indentation;
            indentation += 1;

            let mut current_cmds = commands;
            let mut current_index = 0;
            // stack of commands, index, and indentation
            let mut cmds_stack = Vec::new();

            loop {
                let cmd = &current_cmds[current_index];
                current_index += 1;

                builder.push(format!(
                    "{}{}",
                    " ".repeat(indentation),
                    cmd.to_string_variables(version, variables).unwrap()
                ));
                match &cmd.properties {
                    CommandProperties::Loop { commands, .. }
                    | CommandProperties::Trigger { commands, .. }
                        if !commands.is_empty() =>
                    {
                        // save the current cmds and index
                        // ignore if index is already at the end of the current cmds
                        if current_index < current_cmds.len() {
                            cmds_stack.push((current_cmds, current_index, indentation));
                        }

                        current_cmds = commands;
                        current_index = 0;
                        indentation += 1;
                    }
                    _ => {
                        if current_index >= current_cmds.len() {
                            // check for end of commands
                            match cmds_stack.pop() {
                                Some((last_cmds, last_index, last_indentation)) => {
                                    current_cmds = last_cmds;
                                    current_index = last_index;
                                    indentation = last_indentation;
                                }
                                None => break,
                            }
                        }
                    }
                }
            }

            indentation = starting_indentation;
        }
    }

    Some(builder.join("\n"))
}

pub trait EventWithCommands {
    fn try_push_cmd(&mut self, cmd: Command, indentation: usize) -> Result<(), CommandPushError> {
        if indentation == 1 {
            // first match no loop required
            self.commands_mut().push(cmd);
            Ok(())
        } else {
            let mut last_cmd = match self.commands_mut().last_mut() {
                Some(last_cmd) => last_cmd,
                None => return Err(CommandPushError::InvalidIndentation(1, indentation)),
            };

            for i in 1..indentation {
                last_cmd = if let CommandProperties::Loop { commands, .. }
                | CommandProperties::Trigger { commands, .. } =
                    &mut last_cmd.properties
                {
                    if i + 1 == indentation {
                        // last item
                        commands.push(cmd);
                        return Ok(());
                    } else {
                        match commands.last_mut() {
                            Some(sub_cmd) => sub_cmd,
                            None => {
                                return Err(CommandPushError::InvalidIndentation(
                                    i - 1,
                                    indentation,
                                ))
                            }
                        }
                    }
                } else {
                    return Err(CommandPushError::InvalidIndentation(1, indentation));
                };
            }

            unreachable!();
        }
    }

    fn commands(&self) -> &[Command];

    fn commands_mut(&mut self) -> &mut Vec<Command>;

    /// Returns the command as a `String`.
    /// - Instead of making the command into a string using `Display` or `VersionedToString`, use this to get the command as a string.
    fn to_string_cmd(&self, version: Version) -> Option<String>;

    /// Returns the command as a `String`.
    /// - Contains the commands as a string as well.
    /// - Use this in the `to_string` method with an empty `variables` array.
    fn to_string_variables(&self, version: Version, variables: &[Variable]) -> Option<String> {
        match self.to_string_cmd(version) {
            Some(s) => {
                let cmds = match commands_to_string_variables(self.commands(), version, variables) {
                    Some(mut cmds) => {
                        if !cmds.is_empty() {
                            cmds = format!("\n{cmds}");
                        }

                        cmds
                    }
                    None => return None,
                };

                Some(format!("{s}{cmds}"))
            }
            None => None,
        }
    }
}