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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
#[macro_use]
extern crate derive_error;
extern crate byteorder;

use byteorder::{ReadBytesExt, BigEndian};

use std::string;
use std::cmp;
use std::io;
use std::io::{Read, Seek, SeekFrom};

#[derive(Debug, Error)]
pub enum Error {
    Io(io::Error),
    Utf8(string::FromUtf8Error),
    InvalidFormat,
    UnkownVersion,
    NotSupported,
}

#[derive(Debug)]
pub struct Xcf {
    pub header: XcfHeader,
    layers: Vec<Layer>,
}

impl Xcf {
    pub fn parse<R: Read + Seek>(mut rdr: R) -> Result<Xcf, Error> {
        let header = XcfHeader::parse(&mut rdr)?;

        let mut layers = Vec::new();
        loop {
            let layer_pointer = rdr.read_u32::<BigEndian>()?;
            if layer_pointer == 0 {
                break;
            }
            let current_pos = rdr.seek(SeekFrom::Current(0))?;
            rdr.seek(SeekFrom::Start(layer_pointer as u64))?;
            layers.push( Layer::parse(&mut rdr)? );
            rdr.seek(SeekFrom::Start(current_pos))?;
        }

        // TODO: Read channels

        Ok(Xcf {
            header, layers,
        })
    }

    pub fn layer(&self, name: &str) -> Option<&Layer> {
        self.layers.iter()
            .find(|l| l.name == name)
    }

    pub fn layer_mut(&mut self, name: &str) -> Option<&mut Layer> {
        self.layers.iter_mut()
            .find(|l| l.name == name)
    }
}

#[derive(Debug, PartialEq)]
pub struct XcfHeader {
    pub version: Version,
    pub width: u32,
    pub height: u32,
    pub color_type: ColorType,
    pub properties: Vec<Property>,
}

impl XcfHeader {
    pub fn parse<R: Read>(mut rdr: R) -> Result<XcfHeader, Error> {
        let mut magic = [0u8; 9];
        rdr.read_exact(&mut magic)?;
        if magic != *b"gimp xcf " {
            return Err(Error::InvalidFormat);
        }

        let version = {
            let mut v = [0u8; 4];
            rdr.read_exact(&mut v)?;
            match &v {
                b"file" => Version::V0,
                b"v001" => Version::V1,
                b"v002" => Version::V2,
                b"v003" => Version::V3,
                _ => return Err(Error::UnkownVersion),
            }
        };

        rdr.read_exact(&mut [0u8])?;

        let width = rdr.read_u32::<BigEndian>()?;
        let height = rdr.read_u32::<BigEndian>()?;

        let color_type = ColorType::new(rdr.read_u32::<BigEndian>()?)?;

        if color_type != ColorType::Rgb {
            unimplemented!("Only RGB/RGBA color images supported");
        }

        let properties = Property::parse_list(&mut rdr)?;

        Ok(XcfHeader {
            version, width, height, color_type, properties,
        })
    }
}

#[derive(Debug, PartialEq)]
pub enum Version {
    V0,
    V1,
    V2,
    V3,
}

#[repr(u32)]
#[derive(Debug, PartialEq)]
pub enum ColorType {
    Rgb = 0,
    Grayscale = 1,
    Indexed = 2,
}

impl ColorType {
    pub fn new(kind: u32) -> Result<ColorType, Error> {
        use self::ColorType::*;
        Ok(match kind {
            0 => Rgb,
            1 => Grayscale,
            2 => Indexed,
            _ => return Err(Error::InvalidFormat),
        })
    }
}

#[derive(Debug, PartialEq)]
pub struct Property {
    pub kind: PropertyIdentifier,
    pub length: usize,
    pub payload: PropertyPayload,
}

impl Property {
    pub fn guess_size(&self) -> usize {
        match self.payload {
            PropertyPayload::ColorMap { colors, .. } => {
                /* apparently due to a GIMP bug sometimes self.length will be n + 4 */
                3 * colors + 4
            },
            // this is the best we can do otherwise
            _ => self.length,
        }
    }

    pub fn parse<R: Read>(mut rdr: R) -> Result<Property, Error> {
        let kind = PropertyIdentifier::new(rdr.read_u32::<BigEndian>()?);
        let length = rdr.read_u32::<BigEndian>()? as usize;
        let payload = PropertyPayload::parse(&mut rdr, kind, length)?;
        Ok(Property {
            kind, length, payload,
        })
    }

    pub fn parse_list<R: Read>(mut rdr: R) -> Result<Vec<Property>, Error> {
        let mut props = Vec::new();
        loop {
            let p = Property::parse(&mut rdr)?;
            if let PropertyIdentifier::PropEnd = p.kind {
                break;
            }
            // only push non end
            props.push(p);
        }
        Ok(props)
    }
}

macro_rules! prop_ident_gen {
    (
        pub enum PropertyIdentifier {
            Unknown,
            $(
                $prop:ident = $val:expr
            ),+,
        }
    ) => {
        #[derive(Debug, Clone, Copy, PartialEq)]
        #[repr(u32)]
        pub enum PropertyIdentifier {
            $(
                $prop = $val
            ),+,
            // we have to put this at the end, since otherwise it will try to have value zero,
            // we really don't care what it is as long as it doesn't conflict with anything else
            // (however in the macro we have to put it first since it's a parsing issue)
            Unknown,
        }

        impl PropertyIdentifier {
            pub fn new(prop: u32) -> PropertyIdentifier {
                match prop {
                    $(
                        $val => PropertyIdentifier::$prop
                    ),+,
                    _ => PropertyIdentifier::Unknown,
                }
            }
        }
    }
}

prop_ident_gen! {
    pub enum PropertyIdentifier {
        Unknown,
        PropEnd = 0,
        PropColormap = 1,
        PropOpacity = 6,
        PropVisible = 8,
        PropLinked = 9,
        PropCompression = 17,
        TypeIdentification = 18,
        PropResolution = 19,
        PropTattoo = 20,
        PropParasites = 21,
        PropPaths = 23,
        PropLockContent = 28,
    }
}

#[derive(Debug, PartialEq)]
pub enum PropertyPayload {
    ColorMap {
        colors: usize,
    },
    End,
    Unknown(Vec<u8>),
}

impl PropertyPayload {
    pub fn parse<R: Read>(mut rdr: R, kind: PropertyIdentifier, length: usize)
            -> Result<PropertyPayload, Error> {
        use self::PropertyIdentifier::*;
        Ok(match kind {
            PropEnd => PropertyPayload::End,
            _ => {
                let mut p = vec![0; length];
                rdr.read_exact(&mut p)?;
                PropertyPayload::Unknown(p)
            }
        })
    }
}

#[derive(Debug, PartialEq)]
pub struct Layer {
    pub width: u32,
    pub height: u32,
    pub kind: LayerColorType,
    pub name: String,
    pub properties: Vec<Property>,
    pub pixels: PixelData,
}

impl Layer {
    pub fn parse<R: Read + Seek>(mut rdr: R) -> Result<Layer, Error> {
        let width = rdr.read_u32::<BigEndian>()?;
        let height = rdr.read_u32::<BigEndian>()?;
        let kind = LayerColorType::new(rdr.read_u32::<BigEndian>()?)?;
        let name = read_gimp_string(&mut rdr)?;
        let properties = Property::parse_list(&mut rdr)?;
        let hptr = rdr.read_u32::<BigEndian>()?;
        let current_pos = rdr.seek(SeekFrom::Current(0))?;
        rdr.seek(SeekFrom::Start(hptr as u64))?;
        let pixels = PixelData::parse_heirarchy(&mut rdr)?;
        rdr.seek(SeekFrom::Start(current_pos))?;
        // TODO
        // let mptr = rdr.read_u32::<BigEndian>()?;
        Ok(Layer {
            width, height, kind, name, properties, pixels
        })
    }
}

#[derive(Debug, PartialEq)]
pub struct LayerColorType {
    pub kind: ColorType,
    pub alpha: bool,
}

impl LayerColorType {
    pub fn new(identifier: u32) -> Result<LayerColorType, Error> {
        let kind = ColorType::new(identifier / 2)?;
        let alpha = identifier % 2 == 1;
        Ok(LayerColorType {
            alpha, kind,
        })
    }
}

#[derive(Debug, PartialEq)]
pub struct PixelData {
    width: usize,
    height: usize,
    pixels: Vec<RgbaPixel>
}

impl PixelData {
    /// Parses the (silly?) heirarchy structure in the xcf file into a pixel array
    /// Makes lots of assumptions! Only supports RGBA for now.
    pub fn parse_heirarchy<R: Read + Seek>(mut rdr: R) -> Result<PixelData, Error> {
        // read the heirarchy
        let width = rdr.read_u32::<BigEndian>()? as usize;
        let height = rdr.read_u32::<BigEndian>()? as usize;
        let bpp = rdr.read_u32::<BigEndian>()? as usize;
        if bpp != 3 && bpp != 4 {
            return Err(Error::NotSupported);
        }
        let lptr = rdr.read_u32::<BigEndian>()?;
        let _dummpy_ptr_pos = rdr.seek(SeekFrom::Current(0))?;
        rdr.seek(SeekFrom::Start(lptr as u64))?;
        // read the level
        let level_width = rdr.read_u32::<BigEndian>()? as usize;
        let level_height = rdr.read_u32::<BigEndian>()? as usize;
        if level_width != width || level_height != height {
            return Err(Error::InvalidFormat);
        }

        let mut pixels = vec![RgbaPixel([0, 0, 0, 255]); (width * height) as usize];
        let mut next_tptr_pos;

        let tiles_x = (width as f32 / 64.0).ceil() as usize;
        let tiles_y = (height as f32 / 64.0).ceil() as usize;
        for ty in 0..tiles_y {
            for tx in 0..tiles_x {
                let tptr = rdr.read_u32::<BigEndian>()?;
                next_tptr_pos = rdr.seek(SeekFrom::Current(0))?;
                rdr.seek(SeekFrom::Start(tptr as u64))?;

                let mut cursor = TileCursor::new(width, height, tx, ty, bpp);
                cursor.feed(&mut rdr, &mut pixels)?;

                rdr.seek(SeekFrom::Start(next_tptr_pos))?;
            }
        }

        // rdr.seek(SeekFrom::Start(dummpy_ptr_pos))?;
        // TODO: dummy levels? do we need to consider them?
        // if we do:
        /*loop {
            let dummy_level_ptr = rdr.read_u32::<BigEndian>()?;
            if dummy_level_ptr == 0 {
                break;
            }
        }*/
        // we are now at the end of the heirarchy structure.

        Ok(PixelData { pixels, width, height })
    }

    pub fn pixel(&self, x: usize, y: usize) -> Option<RgbaPixel> {
        if x >= self.width || y >= self.height {
            return None;
        }
        Some(self.pixels[y * self.width + x])
    }
}

pub struct TileCursor {
    width: usize,
    height: usize,
    channels: usize,
    x: usize,
    y: usize,
    i: usize,
}

// TODO: I like the use of a struct but this isn't really any kind of cursor.
// The use of a struct allows us to seperate the state we need to refer to from the number of
// stuff we need to store within the "algorithm." A better design is very welcome! i should be
// moved into feed as a local.
impl TileCursor {
    pub fn new(width: usize, height: usize, tx: usize, ty: usize, channels: usize) -> TileCursor {
        TileCursor {
            width,
            height,
            channels,
            x: tx * 64,
            y: ty * 64,
            i: 0,
        }
    }

    /// Feed the cursor a stream starting at the beginning of an XCF tile structure.
    pub fn feed<R: Read>(&mut self, mut rdr: R, pixels: &mut [RgbaPixel]) -> Result<(), Error> {
        let twidth = cmp::min(self.x + 64, self.width) - self.x;
        let theight = cmp::min(self.y + 64, self.height) - self.y;
        let base_offset = self.y * self.width + self.x;
        // each channel is laid out one after the other
        let mut channel = 0;
        while channel < self.channels {
            while self.i < twidth * theight {
                let determinant = rdr.read_u8()? as u32;
                if determinant < 127 { // A short run of identical bytes
                    let run = (determinant + 1) as usize;
                    let v = rdr.read_u8()?;
                    for i in (self.i)..(self.i + run) {
                        let index = base_offset + (i / twidth) * self.width + i % twidth;
                        pixels[index].0[channel] = v;
                    }
                    self.i += run;
                } else if determinant == 127 { // A long run of identical bytes
                    let run = rdr.read_u16::<BigEndian>()? as usize;
                    let v = rdr.read_u8()?;
                    for i in (self.i)..(self.i + run) {
                        let index = base_offset + (i / twidth) * self.width + i % twidth;
                        pixels[index].0[channel] = v;
                    }
                    self.i += run;
                } else if determinant == 128 { // A long run of different bytes
                    let stream_run = rdr.read_u16::<BigEndian>()? as usize;
                    for i in (self.i)..(self.i + stream_run) {
                        let index = base_offset + (i / twidth) * self.width + i % twidth;
                        let v = rdr.read_u8()?;
                        pixels[index].0[channel] = v;
                    }
                    self.i += stream_run;
                } else { // A short run of different bytes
                    let stream_run = (256 - determinant) as usize;
                    for i in (self.i)..(self.i + stream_run) {
                        let index = base_offset + (i / twidth) * self.width + i % twidth;
                        let v = rdr.read_u8()?;
                        pixels[index].0[channel] = v;
                    }
                    self.i += stream_run;
                }
            }

            self.i = 0;
            channel += 1;
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RgbaPixel(pub [u8; 4]);

fn read_gimp_string<R: Read>(mut rdr: R) -> Result<String, Error> {
    let length = rdr.read_u32::<BigEndian>()?;
    let mut buffer = vec![0; length as usize - 1];
    rdr.read_exact(&mut buffer)?;
    // read the DUMB trailing null byte... uhh GIMP team RIIR already? ;p
    rdr.read_exact(&mut [0u8])?;
    Ok(String::from_utf8(buffer)?)
}