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
use std::{
    fmt::Debug,
    io::{Cursor, Read, Seek, Write},
};

use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};

use crate::{
    cursor_ext::{ReadExt, WriteExt},
    error::{DeserializeError, Error},
};

use super::{impl_write, PropertyOptions, PropertyTrait};

/// A property that stores GVAS Text.
#[derive(Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TextProperty {
    /// An empty `TextProperty`.
    Empty(
        // Workaround for https://github.com/serde-rs/json/issues/664
        [u8; 0],
    ),
    /// A rich `TextProperty`.
    Rich(RichText),
    /// A simple `TextProperty`.
    Simple(Vec<String>),
}

/// A struct describing a rich `TextProperty`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RichText {
    /// A unique identifier.
    pub id: String,
    /// Text pattern.
    pub pattern: String,
    /// Text pattern substitutions.
    pub text_format: Vec<RichTextFormat>,
}

/// A struct describing a text_format entry in a rich `TextProperty`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RichTextFormat {
    /// Substituation key.
    pub format_key: String,
    /// Content type.
    pub content_type: u32,
    /// Substitution value.
    pub values: Vec<String>,
}

const RTF_UNKNOWN: u64 = 0x100000000;

macro_rules! validate {
    ($cursor:expr, $cond:expr, $($arg:tt)+) => {{
        if !$cond {
            Err(DeserializeError::InvalidProperty(
                format!($($arg)+),
                $cursor.stream_position()?,
            ))?
        }
    }};
}

impl_write!(TextProperty, options);

impl TextProperty {
    /// Creates a new `TextProperty` instance.
    #[inline]
    pub fn new(value: Option<RichText>, values: Option<Vec<String>>) -> Self {
        if let Some(rich) = value {
            TextProperty::Rich(rich)
        } else if let Some(simple) = values {
            TextProperty::Simple(simple)
        } else {
            TextProperty::Empty([])
        }
    }

    #[inline]
    pub(crate) fn read<R: Read + Seek>(
        cursor: &mut R,
        include_header: bool,
        options: &mut PropertyOptions,
    ) -> Result<Self, Error> {
        validate!(
            cursor,
            !include_header,
            "TextProperty only supported in arrays"
        );

        let component_type = cursor.read_u32::<LittleEndian>()?;
        validate!(
            cursor,
            component_type <= 2,
            "Unexpected component {component_type}"
        );

        let expect_indicator = if component_type == 1 { 3 } else { 255 };
        let indicator = cursor.read_u8()?;
        validate!(
            cursor,
            indicator == expect_indicator,
            "Unexpected indicator {} for component {}, expected {}",
            indicator,
            component_type,
            expect_indicator
        );

        if component_type == 0 {
            // Empty text
            let count = cursor.read_u32::<LittleEndian>()?;
            validate!(cursor, count == 0, "Unexpected count {count}");

            Ok(TextProperty::Empty([]))
        } else if component_type == 1 {
            // Rich text
            let num_flags = cursor.read_u8()?;
            validate!(cursor, num_flags == 8, "Unexpected num_flags {num_flags}");
            let flags = cursor.read_u64::<LittleEndian>()?;
            let expect_flags = if options.large_world_coordinates {
                RTF_UNKNOWN
            } else {
                0
            };
            validate!(cursor, flags == expect_flags, "Unexpected flags {flags:X}");

            if flags == RTF_UNKNOWN {
                let b = cursor.read_u8()?;
                assert_eq!(b, 0);
            }

            let id = cursor.read_string()?;
            let pattern = cursor.read_string()?;
            let arg_count = cursor.read_u32::<LittleEndian>()?;

            let mut text_format = vec![];
            for _ in 0..arg_count {
                let format_key = cursor.read_string()?;
                let separator = cursor.read_u8()?;
                validate!(cursor, separator == 4, "Unexpected separator {separator}");
                let content_type = cursor.read_u32::<LittleEndian>()?;
                let indicator = cursor.read_u8()?;
                validate!(cursor, indicator == 255, "Unexpected indicator {indicator}");
                let count = cursor.read_u32::<LittleEndian>()?;

                let mut values = vec![];
                for _ in 0..count {
                    let value = cursor.read_string()?;
                    values.push(value);
                }

                text_format.push(RichTextFormat {
                    format_key,
                    content_type,
                    values,
                });
            }

            Ok(TextProperty::Rich(RichText {
                id,
                pattern,
                text_format,
            }))
        } else if component_type == 2 {
            // Simple text
            let count = cursor.read_u32::<LittleEndian>()?;
            validate!(cursor, count > 0, "Unexpected count {count}");

            let mut strings: Vec<String> = vec![];
            for _ in 0..count {
                let str = cursor.read_string()?;
                strings.push(str)
            }

            Ok(TextProperty::Simple(strings))
        } else {
            // Unknown text
            Err(DeserializeError::InvalidProperty(
                format!("Unexpected component_type {}", component_type),
                cursor.stream_position()?,
            ))?
        }
    }

    #[inline]
    fn write_body<W: Write>(
        &self,
        cursor: &mut W,
        options: &mut PropertyOptions,
    ) -> Result<(), Error> {
        match self {
            TextProperty::Empty(_) => {
                cursor.write_u32::<LittleEndian>(0)?;
                cursor.write_u8(255)?;
                cursor.write_u32::<LittleEndian>(0)?;
            }

            TextProperty::Rich(value) => {
                cursor.write_u32::<LittleEndian>(1)?;
                cursor.write_u8(3)?;
                cursor.write_u8(8)?;
                if options.large_world_coordinates {
                    cursor.write_u64::<LittleEndian>(RTF_UNKNOWN)?;
                    cursor.write_u8(0)?;
                } else {
                    cursor.write_u64::<LittleEndian>(0)?;
                }
                cursor.write_string(&value.id)?;
                cursor.write_string(&value.pattern)?;
                cursor.write_u32::<LittleEndian>(value.text_format.len() as u32)?;
                for rtf in &value.text_format {
                    cursor.write_string(&rtf.format_key)?;
                    cursor.write_u8(4)?;
                    cursor.write_u32::<LittleEndian>(rtf.content_type)?;
                    cursor.write_u8(255)?;
                    cursor.write_u32::<LittleEndian>(rtf.values.len() as u32)?;
                    for value in &rtf.values {
                        cursor.write_string(value)?;
                    }
                }
            }

            TextProperty::Simple(values) => {
                cursor.write_u32::<LittleEndian>(2)?;
                cursor.write_u8(255)?;
                cursor.write_u32::<LittleEndian>(values.len() as u32)?;
                for value in values {
                    cursor.write_string(value)?;
                }
            }
        }

        Ok(())
    }
}

impl Debug for TextProperty {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TextProperty::Rich(value) => value.fmt(f),
            TextProperty::Simple(values) => f.debug_list().entries(values).finish(),
            TextProperty::Empty(_) => f.write_str("Empty"),
        }
    }
}

impl RichText {
    /// Creates a new `RichText` instance.
    #[inline]
    pub fn new(id: String, pattern: String, text_format: Vec<RichTextFormat>) -> Self {
        RichText {
            id,
            pattern,
            text_format,
        }
    }
}

impl RichTextFormat {
    /// Creates a new `RichTextFormat` instance.
    #[inline]
    pub fn new(format_key: String, content_type: u32, values: Vec<String>) -> Self {
        RichTextFormat {
            format_key,
            content_type,
            values,
        }
    }
}