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
use crate::{
    decode::{DecodeBeatmap, DecodeState},
    util::{ParseNumber, ParseNumberError, StrExt},
    Beatmap,
};

use super::{BreakPeriod, EventType, ParseEventTypeError};

/// Struct containing all data from a `.osu` file's `[Events]` section.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Events {
    pub background_file: String,
    pub breaks: Vec<BreakPeriod>,
}

impl From<Events> for Beatmap {
    fn from(events: Events) -> Self {
        Self {
            background_file: events.background_file,
            breaks: events.breaks,
            ..Self::default()
        }
    }
}

thiserror! {
    /// All the ways that parsing a `.osu` file into [`Events`] can fail.
    #[derive(Debug)]
    pub enum ParseEventsError {
        #[error("failed to parse event type")]
        EventType(#[from] ParseEventTypeError),
        #[error("invalid line")]
        InvalidLine,
        #[error("failed to parse number")]
        Number(#[from] ParseNumberError),
    }
}

/// The parsing state for [`Events`] in [`DecodeBeatmap`].
pub type EventsState = Events;

impl DecodeState for EventsState {
    fn create(_: i32) -> Self {
        Self::default()
    }
}

impl DecodeBeatmap for Events {
    type Error = ParseEventsError;
    type State = EventsState;

    fn parse_general(_: &mut Self::State, _: &str) -> Result<(), Self::Error> {
        Ok(())
    }

    fn parse_editor(_: &mut Self::State, _: &str) -> Result<(), Self::Error> {
        Ok(())
    }

    fn parse_metadata(_: &mut Self::State, _: &str) -> Result<(), Self::Error> {
        Ok(())
    }

    fn parse_difficulty(_: &mut Self::State, _: &str) -> Result<(), Self::Error> {
        Ok(())
    }

    fn parse_events(state: &mut Self::State, line: &str) -> Result<(), Self::Error> {
        let mut split = line.trim_comment().split(',');

        let (Some(event_type), Some(start_time), Some(event_params)) =
            (split.next(), split.next(), split.next())
        else {
            return Err(ParseEventsError::InvalidLine);
        };

        match event_type.parse()? {
            EventType::Sprite => {
                if state.background_file.is_empty() {
                    state.background_file = split
                        .next()
                        .ok_or(ParseEventsError::InvalidLine)?
                        .clean_filename();
                }
            }
            EventType::Video => {
                const VIDEO_EXTENSIONS: &[[u8; 3]] = &[
                    *b"mp4", *b"mov", *b"avi", *b"flv", *b"mpg", *b"wmv", *b"m4v",
                ];

                let filename = event_params.clean_filename();

                if let [.., a, b, c] = filename.as_bytes() {
                    let extension = [
                        a.to_ascii_lowercase(),
                        b.to_ascii_lowercase(),
                        c.to_ascii_lowercase(),
                    ];

                    if !VIDEO_EXTENSIONS.contains(&extension) {
                        state.background_file = filename;
                    }
                }
            }
            EventType::Background => state.background_file = event_params.clean_filename(),
            EventType::Break => {
                let start_time = f64::parse(start_time)?;
                let end_time = start_time.max(f64::parse(event_params)?);

                state.breaks.push(BreakPeriod {
                    start_time,
                    end_time,
                });
            }
            EventType::Color | EventType::Sample | EventType::Animation => {}
        }

        Ok(())
    }

    fn parse_timing_points(_: &mut Self::State, _: &str) -> Result<(), Self::Error> {
        Ok(())
    }

    fn parse_colors(_: &mut Self::State, _: &str) -> Result<(), Self::Error> {
        Ok(())
    }

    fn parse_hit_objects(_: &mut Self::State, _: &str) -> Result<(), Self::Error> {
        Ok(())
    }

    fn parse_variables(_: &mut Self::State, _: &str) -> Result<(), Self::Error> {
        Ok(())
    }

    fn parse_catch_the_beat(_: &mut Self::State, _: &str) -> Result<(), Self::Error> {
        Ok(())
    }

    fn parse_mania(_: &mut Self::State, _: &str) -> Result<(), Self::Error> {
        Ok(())
    }
}