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
//---------------------------------------------------------------------------//
// Copyright (c) 2017-2023 Ismael Gutiérrez González. All rights reserved.
//
// This file is part of the Rusted PackFile Manager (RPFM) project,
// which can be found here: https://github.com/Frodo45127/rpfm.
//
// This file is licensed under the MIT license, which can be found here:
// https://github.com/Frodo45127/rpfm/blob/master/LICENSE.
//---------------------------------------------------------------------------//

//! This is a module to read/write Text files.
//!
//! Text files are any kind of plain-text files, really. Encodings supported by this lib are:
//! - `ISO-8859-15`
//! - `UTF-8`
//! - `UTF-16` (LittleEndian)
//!
//! Also, the module automatically tries to guess the language of a Text file, so programs
//! can query the guess language format and apply extended functionality.
//!
//! The full list of file extension this lib supports as `Text` files is:
//!
//! | ------------------------ | -------- | ------------------------------------------- |
//! | Extension                | Language | Description                                 |
//! | ------------------------ | -------- | ------------------------------------------- |
//! | `.battle_speech_camera`  | `Plain`  | Camera settings file for battle speeches.   |
//! | `.benchmark`             | `Xml`    | Benchmark settings.                         |
//! | `.bob`                   | `Plain`  | BoB settings file.                          |
//! | `.cindyscene`            | `Xml`    | Cutscene editor data.                       |
//! | `.cindyscenemanager`     | `Xml`    | Cutscene editor data.                       |
//! | `.code-snippets`         | `Json`   | VSCode snippet file.                        |
//! | `.code-workspace`        | `Json`   | VSCode workspace file.                      |
//! | `.csv`                   | `Plain`  | Normal CSV file.                            |
//! | `.css`                   | `Css`    | Normal CSS file.                            |
//! | `.environment`           | `Xml`    |                                             |
//! | `.htm`                   | `Html`   | Normal HTML file.                           |
//! | `.html`                  | `Html`   | Normal HTML file.                           |
//! | `.inl`                   | `Cpp`    |                                             |
//! | `.json`                  | `Json`   | Normal JSON file.                           |
//! | `.js`                    | `Js`     | Normal Javascript file.                     |
//! | `.kfa`                   | `Xml`    | Battle Audio Event file.                    |
//! | `.kfe`                   | `Xml`    | Battle Effect file.                         |
//! | `.kfl`                   | `Xml`    | Battle Point Light file.                    |
//! | `.kfsl`                  | `Xml`    | Battle Spot Light file.                     |
//! | `.kfp`                   | `Xml`    | Battle Prop file.                           |
//! | `.kfcs`                  | `Xml`    | Battle Composite Scene file.                |
//! | `.lighting`              | `Xml`    |                                             |
//! | `.lua`                   | `Lua`    | LUA Script file.                            |
//! | `.material`              | `Xml`    |                                             |
//! | `.tai`                   | `Plain`  |                                             |
//! | `.technique`             | `Xml`    |                                             |
//! | `.texture_array`         | `Plain`  | List of Campaign Map textures.              |
//! | `.tsv`                   | `Plain`  | Normal TSV file.                            |
//! | `.twui`                  | `Lua`    | TWui file, in lua format.                   |
//! | `.txt`                   | `Plain`  | Plain TXT file.                             |
//! | `.variantmeshdefinition` | `Xml`    |                                             |
//! | `.wsmodel`               | `Xml`    |                                             |
//! | `.xml`                   | `Xml`    | Normal XML file.                            |
//! | `.xml.shader`            | `Xml`    | Shader setup metadata.                      |
//! | `.xml.material`          | `Xml`    |                                             |

use getset::*;
use serde_derive::{Serialize, Deserialize};

use std::io::SeekFrom;

use crate::binary::{ReadBytes, WriteBytes};
use crate::error::{Result, RLibError};
use crate::files::{Decodeable, EncodeableExtraData, Encodeable};

use super::DecodeableExtraData;

/// UTF-8 BOM (Byte Order Mark).
const BOM_UTF_8: [u8;3] = [0xEF,0xBB,0xBF];

/// UTF-16 BOM (Byte Order Mark), Little Endian.
const BOM_UTF_16_LE: [u8;2] = [0xFF,0xFE];

/// List of extensions we recognize as `Text` files, with their respective known format.
pub const EXTENSIONS: [(&str, TextFormat); 55] = [
    (".bat", TextFormat::Bat),
    (".battle_speech_camera", TextFormat::Plain),
    (".benchmark", TextFormat::Xml),
    (".bob", TextFormat::Plain),
    (".cco", TextFormat::Plain),
    (".cindyscene", TextFormat::Xml),
    (".cindyscenemanager", TextFormat::Xml),
    (".code-snippets", TextFormat::Json),
    (".code-workspace", TextFormat::Json),
    (".css", TextFormat::Css),
    (".csv", TextFormat::Plain),
    (".environment", TextFormat::Xml),
    (".environment_group", TextFormat::Xml),
    (".environment_group.override", TextFormat::Xml),
    (".fbx", TextFormat::Plain),
    (".fx", TextFormat::Cpp),
    (".fx_fragment", TextFormat::Cpp),
    (".h", TextFormat::Cpp),
    (".hlsl", TextFormat::Hlsl),
    (".htm", TextFormat::Html),
    (".html", TextFormat::Html),
    (".inl", TextFormat::Cpp),
    (".json", TextFormat::Json),
    (".js", TextFormat::Js),
    (".kfa", TextFormat::Xml),
    (".kfc", TextFormat::Xml),
    (".kfe", TextFormat::Xml),
    (".kfe_temp", TextFormat::Xml),
    (".kfl", TextFormat::Xml),
    (".kfl_temp", TextFormat::Xml),
    (".kfsl", TextFormat::Xml),
    (".kfp", TextFormat::Xml),
    (".kfcs", TextFormat::Xml),
    (".kfcs_temp", TextFormat::Xml),
    (".ktr", TextFormat::Xml),
    (".ktr_temp", TextFormat::Xml),
    (".lighting", TextFormat::Xml),
    (".lua", TextFormat::Lua),
    (".mvscene", TextFormat::Xml),
    (".py", TextFormat::Python),
    (".sbs", TextFormat::Xml),
    (".shader", TextFormat::Xml),
    (".tai", TextFormat::Plain),
    (".technique", TextFormat::Xml),
    (".texture_array", TextFormat::Plain),
    (".tsv", TextFormat::Plain),
    (".twui", TextFormat::Lua),
    (".txt", TextFormat::Plain),
    (".variantmeshdefinition", TextFormat::Xml),
    (".wsmodel", TextFormat::Xml),
    (".xml", TextFormat::Xml),
    (".xml_temp", TextFormat::Xml),
    (".xml.shader", TextFormat::Xml),
    (".xml.material", TextFormat::Xml),
    (".material", TextFormat::Xml),     // This has to be under xml.material
];

#[cfg(test)] mod text_test;

//---------------------------------------------------------------------------//
//                              Enum & Structs
//---------------------------------------------------------------------------//

/// This holds an entire `Text` file decoded in memory.
#[derive(Default, PartialEq, Eq, Clone, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)]
#[getset(get = "pub", get_mut = "pub", set = "pub")]
pub struct Text {

    /// The encoding used by the file.
    encoding: Encoding,

    /// The format of the file.
    format: TextFormat,

    /// The text inside the file.
    contents: String
}

/// This enum represents the multiple encodings we can read/write to.
#[derive(PartialEq, Eq, Clone, Copy, Debug, Serialize, Deserialize)]
pub enum Encoding {
    Iso8859_1,
    Utf8,
    Utf8Bom,
    Utf16Le,
}

/// This enum represents the formats we know.
#[derive(PartialEq, Eq, Clone, Copy, Debug, Serialize, Deserialize)]
pub enum TextFormat {
    Bat,
    Cpp,
    Html,
    Hlsl,
    Json,
    Js,
    Css,
    Lua,
    Markdown,
    Plain,
    Python,
    Xml,
}

//---------------------------------------------------------------------------//
//                           Implementation of Text
//---------------------------------------------------------------------------//

/// Implementation of `Default` for `Encoding`.
impl Default for Encoding {

    /// This returns `Encoding::Utf8`, as it's our default encoding.
    fn default() -> Self {
        Encoding::Utf8
    }
}

/// Implementation of `Default` for `TextFormat`.
impl Default for TextFormat {

    /// This returns `TextFormat::Plain`, as it's our default format.
    fn default() -> Self {
        TextFormat::Plain
    }
}

impl Text {

    pub fn detect_encoding<R: ReadBytes>(data: &mut R) -> Result<Encoding> {
        let len = data.len()?;

        // First, check for BOMs. 2 bytes for UTF-16 BOMs, 3 for UTF-8.
        if len > 2 && data.read_slice(3, true)? == BOM_UTF_8 {
            data.seek(SeekFrom::Start(3))?;
            return Ok(Encoding::Utf8Bom)
        }
        else if len > 1 && data.read_slice(2, true)? == BOM_UTF_16_LE {
            data.seek(SeekFrom::Start(2))?;
            return Ok(Encoding::Utf16Le)
        }

        // If no BOM is found, we assume UTF-8 if it decodes properly.
        else {
            let utf8_string = data.read_string_u8(len as usize);
            if utf8_string.is_ok() {
                data.rewind()?;
                return Ok(Encoding::Utf8)
            }

            data.rewind()?;
            let iso_8859_1_string = data.read_string_u8_iso_8859_15(len as usize);
            if iso_8859_1_string.is_ok() {
                data.rewind()?;
                return Ok(Encoding::Iso8859_1)
            }
        }

        // If we reach this, we do not support the format.
        data.rewind()?;
        Err(RLibError::DecodingTextUnsupportedEncodingOrNotATextFile)
    }
}

impl Decodeable for Text {

    fn decode<R: ReadBytes>(data: &mut R, extra_data: &Option<DecodeableExtraData>) -> Result<Self> {
        let len = data.len()?;
        let encoding = Self::detect_encoding(data)?;
        let contents = match encoding {
            Encoding::Iso8859_1 => data.read_string_u8_iso_8859_15(len as usize)
                .map_err(|_| RLibError::DecodingTextUnsupportedEncodingOrNotATextFile)?,

            Encoding::Utf8 |
            Encoding::Utf8Bom => {
                let curr_pos = data.stream_position()?;
                data.read_string_u8((len - curr_pos) as usize)
                    .map_err(|_| RLibError::DecodingTextUnsupportedEncodingOrNotATextFile)?
            },
            Encoding::Utf16Le => {
                let curr_pos = data.stream_position()?;
                data.read_string_u16((len - curr_pos) as usize)
                    .map_err(|_| RLibError::DecodingTextUnsupportedEncodingOrNotATextFile)?
            }
        };

        // Try to get the format of the file.
        let format = match extra_data {
            Some(extra_data) => match extra_data.file_name {
                Some(file_name) => {
                    match EXTENSIONS.iter().find_map(|(extension, format)| if file_name.ends_with(extension) { Some(format) } else { None }) {
                        Some(format) => *format,
                        None => TextFormat::Plain,
                    }
                }
                None => TextFormat::Plain,
            }

            None => TextFormat::Plain,
        };

        Ok(Self {
            encoding,
            format,
            contents,
        })
    }
}

impl Encodeable for Text {

    fn encode<W: WriteBytes>(&mut self, buffer: &mut W, _extra_data: &Option<EncodeableExtraData>) -> Result<()> {
        match self.encoding {
            Encoding::Iso8859_1 => buffer.write_string_u8_iso_8859_1(&self.contents),
            Encoding::Utf8 => buffer.write_string_u8(&self.contents),
            Encoding::Utf8Bom => {
                buffer.write_all(&BOM_UTF_8)?;
                buffer.write_string_u8(&self.contents)
            },

            // For UTF-16 we always have to add the BOM. Otherwise we have no way to easily tell what this file is.
            Encoding::Utf16Le => {
                buffer.write_all(&BOM_UTF_16_LE)?;
                buffer.write_string_u16(&self.contents)
            },
        }
    }
}