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
use yy_typings::RoomOrderId;

pub use super::yy_typings::{
    texture_group::TextureGroup, AudioGroup, FilesystemPath, ResourceVersion, Tags, Yyp, YypConfig,
    YypFolder, YypIncludedFile, YypMetaData, YypResource,
};

const BIG_NUMBER: usize = 2000;
const MEMBER_NUMBER: usize = 70;
const TWO_SPACES: &str = "  ";

pub trait YypSerialization {
    #[cfg(windows)]
    const LINE_ENDING: &'static str = "\r\n";
    #[cfg(not(windows))]
    const LINE_ENDING: &'static str = "\n";

    fn yyp_serialization(&self, indentation: usize) -> String;
}

impl YypSerialization for Yyp {
    fn yyp_serialization(&self, _: usize) -> String {
        let mut output = String::with_capacity(BIG_NUMBER);

        let output_ptr = &mut output;
        print_indentation(output_ptr, 1);
        print_yyp_line(output_ptr, "resources", self.resources.yyp_serialization(1));
        print_yyp_line(output_ptr, "Options", self.options.yyp_serialization(1));
        print_yyp_line(output_ptr, "isDnDProject", self.is_dn_d_project.to_string());
        print_yyp_line(output_ptr, "isEcma", self.is_ecma.to_string());
        // We need to do this here because Rust doesn't like empty strings
        if self.tutorial_path.is_empty() {
            output_ptr.push_str(&format!("\"tutorialPath\": \"\",{}", Self::LINE_ENDING));
            print_indentation(output_ptr, 1);
        } else {
            print_yyp_line(output_ptr, "tutorialPath", self.tutorial_path.to_string());
        }

        print_yyp_line(output_ptr, "configs", self.configs.yyp_serialization(1));
        print_yyp_line(
            output_ptr,
            "RoomOrderNodes",
            self.room_order_nodes.yyp_serialization(1),
        );
        print_yyp_line(output_ptr, "Folders", self.folders.yyp_serialization(1));
        print_yyp_line(
            output_ptr,
            "AudioGroups",
            self.audio_groups.yyp_serialization(1),
        );
        print_yyp_line(
            output_ptr,
            "TextureGroups",
            self.texture_groups.yyp_serialization(1),
        );
        print_yyp_line(
            output_ptr,
            "IncludedFiles",
            self.included_files.yyp_serialization(1),
        );
        print_yyp_line(output_ptr, "MetaData", self.meta_data.yyp_serialization(1));
        print_yyp_line(
            output_ptr,
            "resourceVersion",
            self.resource_version.yyp_serialization(1),
        );
        print_yyp_line(output_ptr, "name", self.name.yyp_serialization(1));
        print_yyp_line(output_ptr, "tags", self.tags.yyp_serialization(1));
        output_ptr.push_str("\"resourceType\": \"GMProject\",");

        format!(
            "{{{line}{output}{line}}}",
            line = Self::LINE_ENDING,
            output = output
        )
    }
}

fn print_yyp_line(string: &mut String, label: &str, value: String) {
    string.push_str(&format!("\"{}\": {},{}", label, value, Yyp::LINE_ENDING));
    print_indentation(string, 1);
}

impl YypSerialization for FilesystemPath {
    fn yyp_serialization(&self, _: usize) -> String {
        format!(
            r#"{{"name":"{}","path":"{}",}}"#,
            self.name,
            self.path.to_string_lossy(),
        )
    }
}

impl YypSerialization for YypResource {
    fn yyp_serialization(&self, indentation: usize) -> String {
        format!(
            r#"{{"id":{},"order":{},}}"#,
            self.id.yyp_serialization(indentation),
            self.order
        )
    }
}

impl YypSerialization for YypConfig {
    fn yyp_serialization(&self, mut indentation: usize) -> String {
        fn inner_config_print(string: &mut String, config: &YypConfig, indentation: &mut usize) {
            print_indentation(string, *indentation);
            string.push_str(&format!(r#"{{"name":"{}","children":["#, config.name));

            if config.children.is_empty() == false {
                // Get us to the write line...
                *indentation += 2;
                string.push_str(YypConfig::LINE_ENDING);

                for child in config.children.iter() {
                    let old_indentation = *indentation;

                    inner_config_print(string, child, indentation);
                    assert_eq!(
                        old_indentation, *indentation,
                        "Stack on inner children broken"
                    );
                }

                *indentation -= 1;
                print_indentation(string, *indentation);
                string.push_str("],},");
                string.push_str(YypConfig::LINE_ENDING);
                *indentation -= 1;
            } else {
                string.push_str("],},");
                string.push_str(YypConfig::LINE_ENDING);
            }
        }

        let mut output = String::with_capacity(MEMBER_NUMBER);

        // Outer Config
        output.push_str(&format!("{{{}", Self::LINE_ENDING));
        indentation += 1;
        print_indentation(&mut output, indentation);
        output.push_str(&format!(r#""name": "{}","#, self.name));

        output.push_str(YypConfig::LINE_ENDING);
        print_indentation(&mut output, indentation);
        let old_indentation = indentation;

        output.push_str(r#""children": ["#);
        if self.children.is_empty() == false {
            output.push_str(Self::LINE_ENDING);

            indentation += 1;

            for child in self.children.iter() {
                inner_config_print(&mut output, child, &mut indentation);
            }

            indentation -= 1;
            print_indentation(&mut output, indentation);
        }

        assert_eq!(
            old_indentation, indentation,
            "Child config stack must be balanced"
        );

        output.push_str(&format!("],{}", YypConfig::LINE_ENDING));
        indentation -= 1;

        assert_eq!(1, indentation, "Stack must be down to 1 indent.");
        print_indentation(&mut output, indentation);
        output.push('}');

        output
    }
}

impl YypSerialization for YypFolder {
    fn yyp_serialization(&self, indentation: usize) -> String {
        format!(
            r#"{{"folderPath":"{}","order":{},"resourceVersion":"{}","name":"{}","tags":{},"resourceType":"GMFolder",}}"#,
            self.folder_path.inner(),
            self.order,
            self.resource_version,
            self.name,
            self.tags.yyp_serialization(indentation)
        )
    }
}

impl YypSerialization for AudioGroup {
    fn yyp_serialization(&self, _: usize) -> String {
        json_trailing_comma(&self)
    }
}

impl YypSerialization for TextureGroup {
    fn yyp_serialization(&self, _: usize) -> String {
        json_trailing_comma(&self).replace("{,}", "{}")
    }
}

impl YypSerialization for YypIncludedFile {
    fn yyp_serialization(&self, _: usize) -> String {
        json_trailing_comma(&self)
    }
}

impl YypSerialization for YypMetaData {
    fn yyp_serialization(&self, _: usize) -> String {
        format!(
            "{{{line}{two}{two}\"IDEVersion\": \"{ide}\",{line}{two}}}",
            two = TWO_SPACES,
            ide = self.ide_version,
            line = Self::LINE_ENDING
        )
    }
}

impl YypSerialization for ResourceVersion {
    fn yyp_serialization(&self, _: usize) -> String {
        serde_json::to_string(self).unwrap()
    }
}

fn json_trailing_comma(t: &impl serde::Serialize) -> String {
    let output = serde_json::to_string(t).unwrap();
    // this is actually peak performance
    output.replace("}", ",}").replace("{,}", "{}")
}

impl<T: YypSerialization> YypSerialization for Vec<T> {
    fn yyp_serialization(&self, mut indentation: usize) -> String {
        if self.is_empty() {
            "[]".to_owned()
        } else {
            let mut output = String::with_capacity(MEMBER_NUMBER);

            output.push_str(&format!("[{}", Self::LINE_ENDING));
            indentation += 1;

            for value in self.iter() {
                print_indentation(&mut output, indentation);
                output.push_str(&format!(
                    "{},{}",
                    value.yyp_serialization(indentation),
                    Self::LINE_ENDING
                ));
            }
            indentation -= 1;

            print_indentation(&mut output, indentation);
            output.push(']');

            output
        }
    }
}

impl YypSerialization for String {
    fn yyp_serialization(&self, _: usize) -> String {
        format!("\"{}\"", self.to_string())
    }
}

fn print_indentation(string: &mut String, indentation: usize) {
    for _ in 0..indentation {
        string.push_str(TWO_SPACES);
    }
}

impl YypSerialization for RoomOrderId {
    fn yyp_serialization(&self, i: usize) -> String {
        format!("{{\"roomId\":{},}}", self.room_id.yyp_serialization(i))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq as pretty_assert_eq;
    use std::path::Path;
    use yy_typings::utils::TrailingCommaUtility;

    #[test]
    fn fsystem_path() {
        let fsystem_path = FilesystemPath {
            name: "Sprites".to_string(),
            path: Path::new("folders/Members/Sprites").to_owned(),
        };

        pretty_assert_eq!(
            fsystem_path.yyp_serialization(0),
            r#"{"name":"Sprites","path":"folders/Members/Sprites",}"#
        );
    }

    #[test]
    fn yyp_resource() {
        let yyp_resource = YypResource {
            id: FilesystemPath {
                name: "Sprites".to_string(),
                path: Path::new("folders/Members/Sprites.yy").to_owned(),
            },
            order: 1,
        };

        pretty_assert_eq!(
            yyp_resource.yyp_serialization(0),
            r#"{"id":{"name":"Sprites","path":"folders/Members/Sprites.yy",},"order":1,}"#
        );
    }

    #[test]
    fn yyp() {
        let yyp = include_str!("../../tests/examples/test_proj/test_proj.yyp");

        let parse_yyp: Yyp =
            serde_json::from_str(&TrailingCommaUtility::clear_trailing_comma_once(yyp)).unwrap();
        let no_mangled_yyp = parse_yyp.yyp_serialization(0);

        assert_eq!(yyp, no_mangled_yyp);
    }
}