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
// Copyright (c) 2021 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

//! Describes the style of each shape.

use crate::Transform;
use bitflags::bitflags;
use nom::{multi::many_m_n, number::complete::u8, sequence::tuple, IResult};

/// Represents one colour, with optimisations in the cases there is no alpha,
/// or all three components are equal (that is, grey).
#[derive(Debug, Clone, PartialEq)]
pub enum Colour {
    /// Contains all four components.
    Rgba(u8, u8, u8, u8),

    /// Completely opaque RGB.
    Rgb(u8, u8, u8),

    /// All three colours are equal.
    Grey(u8, u8),

    /// Completely opaque grey.
    GreyNoAlpha(u8),
}

impl Colour {
    fn parse_rgba(i: &[u8]) -> IResult<&[u8], Colour> {
        let (i, (r, g, b, a)) = tuple((u8, u8, u8, u8))(i)?;
        Ok((i, Colour::Rgba(r, g, b, a)))
    }

    fn parse_rgb(i: &[u8]) -> IResult<&[u8], Colour> {
        let (i, (r, g, b)) = tuple((u8, u8, u8))(i)?;
        Ok((i, Colour::Rgb(r, g, b)))
    }

    fn parse_grey(i: &[u8]) -> IResult<&[u8], Colour> {
        let (i, (grey, alpha)) = tuple((u8, u8))(i)?;
        Ok((i, Colour::Grey(grey, alpha)))
    }

    fn parse_grey_no_alpha(i: &[u8]) -> IResult<&[u8], Colour> {
        let (i, grey) = u8(i)?;
        Ok((i, Colour::GreyNoAlpha(grey)))
    }

    /// Returns whether a colour is opaque, that is no alpha value is present.
    pub fn is_opaque(&self) -> bool {
        match *self {
            Colour::Rgba(_, _, _, a) | Colour::Grey(_, a) => a == 255,
            Colour::Rgb(_, _, _) | Colour::GreyNoAlpha(_) => true,
        }
    }

    /// Converts this colour to its rgb components.
    ///
    /// Safety: it must be called only on opaque colours.
    pub fn to_rgb(&self) -> (u8, u8, u8) {
        match *self {
            Colour::Rgba(r, g, b, a) if a == 255 => (r, g, b),
            Colour::Rgb(r, g, b) => (r, g, b),
            Colour::Grey(grey, alpha) if alpha == 255 => (grey, grey, grey),
            Colour::GreyNoAlpha(grey) => (grey, grey, grey),
            _ => panic!("This function must only be called on opaque colours."),
        }
    }

    /// Converts this colour to its rgba components.
    pub fn to_rgba(&self) -> (u8, u8, u8, u8) {
        match *self {
            Colour::Rgba(r, g, b, a) => (r, g, b, a),
            Colour::Rgb(r, g, b) => (r, g, b, 255),
            Colour::Grey(grey, alpha) => (grey, grey, grey, alpha),
            Colour::GreyNoAlpha(grey) => (grey, grey, grey, 255),
        }
    }
}

enum StyleType {
    SolidColour = 1,
    Gradient = 2,
    SolidColourNoAlpha = 3,
    SolidGrey = 4,
    SolidGreyNoAlpha = 5,
}

impl StyleType {
    fn parse(i: &[u8]) -> IResult<&[u8], StyleType> {
        let (i, type_) = u8(i)?;
        use StyleType::*;
        Ok((
            i,
            match type_ {
                1 => SolidColour,
                2 => Gradient,
                3 => SolidColourNoAlpha,
                4 => SolidGrey,
                5 => SolidGreyNoAlpha,
                _ => {
                    unreachable!("Unknown style type {}", type_);
                }
            },
        ))
    }
}

/// The type of the gradient, for use for rendering.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum GradientType {
    /// A linear gradient, interpolating linearly alongside the vector.
    Linear = 0,

    /// A circular gradient.
    Circular = 1,

    /// A gradient in a diamond shape.
    Diamond = 2,

    /// A conic gradient.
    Conic = 3,

    /// What is this even?
    Xy = 4,

    /// Aaaaah!
    SqrtXy = 5,
}

impl GradientType {
    fn parse(i: &[u8]) -> IResult<&[u8], GradientType> {
        let (i, type_) = u8(i)?;
        use GradientType::*;
        Ok((
            i,
            match type_ {
                0 => Linear,
                1 => Circular,
                2 => Diamond,
                3 => Conic,
                4 => Xy,
                5 => SqrtXy,
                _ => unreachable!("Unknown gradient type {}", type_),
            },
        ))
    }
}

bitflags! {
    /// Flags affecting a gradient.
    pub struct GradientFlags: u8 {
        /// This gradient contains a 3×2 transformation matrix.
        const TRANSFORM = 0b00000010;

        /// This gradient is fully opaque.
        const NO_ALPHA = 0b00000100;

        // Unused.
        //const SIXTEEN_BIT_COLOURS = 0b00001000;

        /// This gradient only uses greys, no other colours.
        const GREYS = 0b00010000;
    }
}

impl GradientFlags {
    fn parse(i: &[u8]) -> IResult<&[u8], GradientFlags> {
        let (i, flags) = u8(i)?;
        Ok((i, GradientFlags::from_bits_truncate(flags)))
    }
}

/// A point in a gradient.
#[derive(Debug, Clone, PartialEq)]
pub struct Stop {
    /// The offset of this stop, interpolated.
    pub offset: u8,

    /// The colour of this stop.
    pub colour: Colour,
}

impl Stop {
    fn parse_rgba(i: &[u8]) -> IResult<&[u8], Stop> {
        let (i, (offset, colour)) = tuple((u8, Colour::parse_rgba))(i)?;
        Ok((i, Stop { offset, colour }))
    }

    fn parse_rgb(i: &[u8]) -> IResult<&[u8], Stop> {
        let (i, (offset, colour)) = tuple((u8, Colour::parse_rgb))(i)?;
        Ok((i, Stop { offset, colour }))
    }

    fn parse_grey(i: &[u8]) -> IResult<&[u8], Stop> {
        let (i, (offset, colour)) = tuple((u8, Colour::parse_grey))(i)?;
        Ok((i, Stop { offset, colour }))
    }

    fn parse_grey_no_alpha(i: &[u8]) -> IResult<&[u8], Stop> {
        let (i, (offset, colour)) = tuple((u8, Colour::parse_grey_no_alpha))(i)?;
        Ok((i, Stop { offset, colour }))
    }
}

/// A gradient.
#[derive(Debug, Clone, PartialEq)]
pub struct Gradient {
    /// The type of this gradient.
    pub type_: GradientType,

    /// The flags of this gradient.
    pub flags: GradientFlags,

    /// Contains up to 255 different stops in this gradient.
    pub stops: Vec<Stop>,

    /// An optional 3×2 transformation matrix applied to this gradient.
    pub transform: Option<Transform>,
}

impl Gradient {
    fn parse(i: &[u8]) -> IResult<&[u8], Gradient> {
        let (i, (type_, flags)) = tuple((GradientType::parse, GradientFlags::parse))(i)?;
        // length_count() can’t be used here, since we could have a transform matrix in-between.
        let (i, num_stops) = u8(i)?;
        let num_stops = num_stops as usize;
        let (i, transform) = if flags.contains(GradientFlags::TRANSFORM) {
            let (i, transform) = Transform::parse(i)?;
            (i, Some(transform))
        } else {
            (i, None)
        };
        let (i, stops) = if flags.contains(GradientFlags::NO_ALPHA) {
            if flags.contains(GradientFlags::GREYS) {
                many_m_n(num_stops, num_stops, Stop::parse_grey_no_alpha)(i)?
            } else {
                many_m_n(num_stops, num_stops, Stop::parse_rgb)(i)?
            }
        } else if flags.contains(GradientFlags::GREYS) {
            many_m_n(num_stops, num_stops, Stop::parse_grey)(i)?
        } else {
            many_m_n(num_stops, num_stops, Stop::parse_rgba)(i)?
        };
        Ok((
            i,
            Gradient {
                type_,
                flags,
                stops,
                transform,
            },
        ))
    }
}

/// A style, to be applied to one or more shapes.
#[derive(Debug, Clone, PartialEq)]
pub enum Style {
    /// This style is a solid colour.
    SolidColour(Colour),

    /// This style is a gradient.
    Gradient(Gradient),
}

impl Style {
    /// Parse a Style from its HVIF serialisation.
    pub fn parse(i: &[u8]) -> IResult<&[u8], Style> {
        let (i, type_) = StyleType::parse(i)?;
        match type_ {
            StyleType::SolidColour => {
                let (i, colour) = Colour::parse_rgba(i)?;
                Ok((i, Style::SolidColour(colour)))
            }
            StyleType::Gradient => {
                let (i, gradient) = Gradient::parse(i)?;
                Ok((i, Style::Gradient(gradient)))
            }
            StyleType::SolidColourNoAlpha => {
                let (i, colour) = Colour::parse_rgb(i)?;
                Ok((i, Style::SolidColour(colour)))
            }
            StyleType::SolidGrey => {
                let (i, colour) = Colour::parse_grey(i)?;
                Ok((i, Style::SolidColour(colour)))
            }
            StyleType::SolidGreyNoAlpha => {
                let (i, colour) = Colour::parse_grey_no_alpha(i)?;
                Ok((i, Style::SolidColour(colour)))
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    macro_rules! assert_size (
        ($t:ty, $sz:expr) => (
            assert_eq!(::std::mem::size_of::<$t>(), $sz);
        );
    );

    #[test]
    fn sizes() {
        assert_size!(Colour, 5);
        assert_size!(GradientType, 1);
        assert_size!(GradientFlags, 1);
        assert_size!(Stop, 6);
        assert_size!(Gradient, 56);
        assert_size!(Style, 64);
    }

    #[test]
    fn solid_grey() {
        let grey = b"\x05\x80";
        let (i, style) = Style::parse(grey).unwrap();
        assert!(i.is_empty());
        assert_eq!(style, Style::SolidColour(Colour::GreyNoAlpha(128)));
    }

    #[test]
    fn solid_colour() {
        let red = b"\x01\xff\x00\x00\x80";
        let (i, style) = Style::parse(red).unwrap();
        assert!(i.is_empty());
        assert_eq!(style, Style::SolidColour(Colour::Rgba(255, 0, 0, 128)));
    }

    #[test]
    fn gradient() {
        let data = b"\x02\x00\x04\x02\x00\x20\x40\x60\xff\x60\x40\x20";
        let (i, style) = Style::parse(data).unwrap();
        println!("{:?}", i);
        assert!(i.is_empty());
        if let Style::Gradient(gradient) = style {
            assert_eq!(gradient.type_, GradientType::Linear);
            assert_eq!(gradient.flags, GradientFlags::NO_ALPHA);
            assert_eq!(
                gradient.stops,
                [
                    Stop {
                        offset: 0,
                        colour: Colour::Rgb(32, 64, 96)
                    },
                    Stop {
                        offset: 255,
                        colour: Colour::Rgb(96, 64, 32)
                    },
                ]
            );
            assert_eq!(gradient.transform, None);
        } else {
            panic!("Parsed style isn’t a gradient.");
        }
    }

    #[test]
    fn gradient_matrix() {
        let data = b"\x02\x00\x02\x00\x40\x00\x00\x00\x00\x00\x00\x00\x00\x40\x00\x00\x00\x00\x00\x00\x00\x00";
        let (i, style) = Style::parse(data).unwrap();
        println!("{:?}", i);
        assert!(i.is_empty());
        if let Style::Gradient(gradient) = style {
            assert_eq!(gradient.type_, GradientType::Linear);
            assert_eq!(gradient.flags, GradientFlags::TRANSFORM);
            assert_eq!(gradient.stops, []);
            assert_eq!(gradient.transform.unwrap(), Transform::IDENTITY);
        } else {
            panic!("Parsed style isn’t a gradient.");
        }
    }
}