ag-psd 0.1.0

Read and write Adobe Photoshop (.psd/.psb) files — a from-scratch Rust port of the ag-psd TypeScript library.
Documentation
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
/*
File: crates/ag-psd/src/ase.rs

Purpose:
чтение/запись палитр Adobe Swatch Exchange (.ase).

Source compatibility:
- порт upstream-файла `test/ag-psd/src/ase.ts`.
- upstream предоставляет ТОЛЬКО `readAse` (read-only). `write_ase` добавлен здесь
  как симметричная функция (нужна для round-trip теста); upstream-аналога нет.

Main responsibilities:
- декодировать/кодировать блоки ASEF (цвета, группы) с типами RGB/CMYK/Gray/LAB.
*/

use crate::reader::{
    read_float32, read_signature, read_uint16, read_uint32, read_unicode_string_with_length,
    PsdReader, ReadError, ReadResult,
};
use crate::writer::{
    create_writer, get_writer_buffer, write_float32, write_signature, write_uint16, write_uint32,
    PsdWriter,
};

/// TS `AseColorType`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AseColorType {
    /// "global"
    Global,
    /// "spot"
    Spot,
    /// "normal"
    Normal,
}

impl AseColorType {
    /// `colorTypes[index]` — индекс из файла -> тип.
    fn from_index(index: u16) -> Option<AseColorType> {
        match index {
            0 => Some(AseColorType::Global),
            1 => Some(AseColorType::Spot),
            2 => Some(AseColorType::Normal),
            _ => None,
        }
    }

    fn to_index(self) -> u16 {
        match self {
            AseColorType::Global => 0,
            AseColorType::Spot => 1,
            AseColorType::Normal => 2,
        }
    }
}

/// TS `AseColor.color` union (RGB / CMYK / Gray / LAB), несёт `type`.
#[derive(Debug, Clone, PartialEq)]
pub enum AseColorValue {
    /// 'RGB '
    Rgb {
        r: f32,
        g: f32,
        b: f32,
        type_: AseColorType,
    },
    /// 'CMYK'
    Cmyk {
        c: f32,
        m: f32,
        y: f32,
        k: f32,
        type_: AseColorType,
    },
    /// 'Gray'
    Gray { k: f32, type_: AseColorType },
    /// 'LAB '
    Lab {
        l: f32,
        a: f32,
        b: f32,
        type_: AseColorType,
    },
}

/// TS `AseColor`.
#[derive(Debug, Clone, PartialEq)]
pub struct AseColor {
    pub name: String,
    pub color: AseColorValue,
}

/// TS `AseGroup`.
#[derive(Debug, Clone, PartialEq)]
pub struct AseGroup {
    pub name: String,
    pub colors: Vec<AseColor>,
}

/// TS `Ase.colors` union элемент (`AseGroup | AseColor`).
#[derive(Debug, Clone, PartialEq)]
pub enum AseEntry {
    Color(AseColor),
    Group(AseGroup),
}

/// TS `Ase`.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Ase {
    pub colors: Vec<AseEntry>,
}

/// Порт `readAse(buffer)`.
pub fn read_ase(buffer: &[u8]) -> ReadResult<Ase> {
    let reader = &mut PsdReader::new(buffer, None, None);

    let signature = read_signature(reader)?; // ASEF
    if signature != "ASEF" {
        return Err(ReadError::StrictViolation("Invalid signature".to_string()));
    }
    let version_major = read_uint16(reader)?; // 1
    let version_minor = read_uint16(reader)?; // 0
    if version_major != 1 || version_minor != 0 {
        return Err(ReadError::StrictViolation("Invalid version".to_string()));
    }
    let blocks_count = read_uint32(reader)?;

    let mut ase = Ase { colors: Vec::new() };
    // `group` в upstream указывает либо в корень `ase`, либо в последнюю
    // открытую группу. Здесь — индекс открытой группы в `ase.colors` (None = корень).
    let mut current_group: Option<usize> = None;

    for _ in 0..blocks_count {
        let type_ = read_uint16(reader)?;
        let length = read_uint32(reader)? as usize;
        let end = reader.offset + length;

        match type_ {
            0x0001 => {
                // color
                let name_length = read_uint16(reader)? as usize;
                let name = read_unicode_string_with_length(reader, name_length)?;
                let color_mode = read_signature(reader)?;
                let color = match color_mode.as_str() {
                    "RGB " => AseColorValue::Rgb {
                        r: read_float32(reader)?,
                        g: read_float32(reader)?,
                        b: read_float32(reader)?,
                        type_: read_color_type(reader)?,
                    },
                    "CMYK" => AseColorValue::Cmyk {
                        c: read_float32(reader)?,
                        m: read_float32(reader)?,
                        y: read_float32(reader)?,
                        k: read_float32(reader)?,
                        type_: read_color_type(reader)?,
                    },
                    "Gray" => AseColorValue::Gray {
                        k: read_float32(reader)?,
                        type_: read_color_type(reader)?,
                    },
                    "LAB " => AseColorValue::Lab {
                        l: read_float32(reader)?,
                        a: read_float32(reader)?,
                        b: read_float32(reader)?,
                        type_: read_color_type(reader)?,
                    },
                    _ => {
                        return Err(ReadError::StrictViolation("Invalid color mode".to_string()))
                    }
                };
                let entry = AseColor { name, color };
                match current_group {
                    Some(gi) => {
                        if let AseEntry::Group(g) = &mut ase.colors[gi] {
                            g.colors.push(entry);
                        }
                    }
                    None => ase.colors.push(AseEntry::Color(entry)),
                }
            }
            0xC001 => {
                // group start
                let name_length = read_uint16(reader)? as usize;
                let name = read_unicode_string_with_length(reader, name_length)?;
                ase.colors.push(AseEntry::Group(AseGroup {
                    name,
                    colors: Vec::new(),
                }));
                current_group = Some(ase.colors.len() - 1);
            }
            0xC002 => {
                // group end
                current_group = None;
            }
            _ => return Err(ReadError::StrictViolation("Invalid block type".to_string())),
        }

        reader.offset = end;
    }

    Ok(ase)
}

fn read_color_type(reader: &mut PsdReader) -> ReadResult<AseColorType> {
    let index = read_uint16(reader)?;
    AseColorType::from_index(index)
        .ok_or_else(|| ReadError::StrictViolation(format!("Invalid color type: {}", index)))
}

/// Запись палитры в формат ASEF (симметрия `read_ase`; upstream-аналога нет).
///
/// Каждый блок пишется как `uint16 type` + `uint32 length` + payload длины
/// `length`; имена кодируются как `uint16 codeUnitCount` (включая завершающий 0)
/// и затем UTF-16 BE code units (как `readUnicodeStringWithLength`).
pub fn write_ase(ase: &Ase) -> Vec<u8> {
    let mut writer = create_writer(4096);

    write_signature(&mut writer, "ASEF");
    write_uint16(&mut writer, 1); // version major
    write_uint16(&mut writer, 0); // version minor

    // Считаем блоки: каждая группа = group-start + N цветов + group-end.
    let mut blocks_count: u32 = 0;
    for entry in &ase.colors {
        match entry {
            AseEntry::Color(_) => blocks_count += 1,
            AseEntry::Group(g) => blocks_count += 2 + g.colors.len() as u32,
        }
    }
    write_uint32(&mut writer, blocks_count);

    for entry in &ase.colors {
        match entry {
            AseEntry::Color(c) => write_color_block(&mut writer, c),
            AseEntry::Group(g) => {
                write_block(&mut writer, 0xC001, |w| write_name(w, &g.name));
                for c in &g.colors {
                    write_color_block(&mut writer, c);
                }
                write_block(&mut writer, 0xC002, |_| {});
            }
        }
    }

    get_writer_buffer(&writer)
}

fn write_name(writer: &mut PsdWriter, name: &str) {
    // длина в code units включает завершающий ноль (readUnicodeStringWithLength
    // отбрасывает хвостовой \0 на последней позиции).
    let units: Vec<u16> = name.encode_utf16().collect();
    write_uint16(writer, (units.len() + 1) as u16);
    for u in &units {
        write_uint16(writer, *u);
    }
    write_uint16(writer, 0); // trailing null
}

fn write_color_block(writer: &mut PsdWriter, c: &AseColor) {
    write_block(writer, 0x0001, |w| {
        write_name(w, &c.name);
        match &c.color {
            AseColorValue::Rgb { r, g, b, type_ } => {
                write_signature(w, "RGB ");
                write_float32(w, *r);
                write_float32(w, *g);
                write_float32(w, *b);
                write_uint16(w, type_.to_index());
            }
            AseColorValue::Cmyk { c, m, y, k, type_ } => {
                write_signature(w, "CMYK");
                write_float32(w, *c);
                write_float32(w, *m);
                write_float32(w, *y);
                write_float32(w, *k);
                write_uint16(w, type_.to_index());
            }
            AseColorValue::Gray { k, type_ } => {
                write_signature(w, "Gray");
                write_float32(w, *k);
                write_uint16(w, type_.to_index());
            }
            AseColorValue::Lab { l, a, b, type_ } => {
                write_signature(w, "LAB ");
                write_float32(w, *l);
                write_float32(w, *a);
                write_float32(w, *b);
                write_uint16(w, type_.to_index());
            }
        }
    });
}

/// Пишет блок `uint16 type` + `uint32 length` + payload, бэкпатчит длину.
fn write_block<F: FnOnce(&mut PsdWriter)>(writer: &mut PsdWriter, type_: u16, func: F) {
    write_uint16(writer, type_);
    let length_offset = writer.offset;
    write_uint32(writer, 0); // placeholder
    let start = writer.offset;
    func(writer);
    let length = (writer.offset - start) as u32;
    writer.buffer[length_offset..length_offset + 4].copy_from_slice(&length.to_be_bytes());
}

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

    fn sample() -> Ase {
        Ase {
            colors: vec![
                AseEntry::Color(AseColor {
                    name: "Red".to_string(),
                    color: AseColorValue::Rgb {
                        r: 1.0,
                        g: 0.0,
                        b: 0.0,
                        type_: AseColorType::Global,
                    },
                }),
                AseEntry::Group(AseGroup {
                    name: "Grays".to_string(),
                    colors: vec![
                        AseColor {
                            name: "Mid".to_string(),
                            color: AseColorValue::Gray {
                                k: 0.5,
                                type_: AseColorType::Normal,
                            },
                        },
                        AseColor {
                            name: "Cyanish".to_string(),
                            color: AseColorValue::Cmyk {
                                c: 1.0,
                                m: 0.0,
                                y: 0.0,
                                k: 0.0,
                                type_: AseColorType::Spot,
                            },
                        },
                    ],
                }),
                AseEntry::Color(AseColor {
                    name: "Lab".to_string(),
                    color: AseColorValue::Lab {
                        l: 50.0,
                        a: 10.0,
                        b: -20.0,
                        type_: AseColorType::Normal,
                    },
                }),
            ],
        }
    }

    #[test]
    fn ase_round_trip() {
        let ase = sample();
        let bytes = write_ase(&ase);
        let decoded = read_ase(&bytes).expect("read_ase");
        assert_eq!(ase, decoded);
    }

    #[test]
    fn ase_rejects_bad_signature() {
        let bytes = b"XXXX\x00\x01\x00\x00\x00\x00\x00\x00";
        assert!(read_ase(bytes).is_err());
    }

    fn fixture(sub: &str) -> std::path::PathBuf {
        let mut p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        p.pop();
        p.pop();
        p.push("test/ag-psd/test/ase-read");
        p.push(sub);
        p.push("src.ase");
        p
    }

    #[test]
    fn ase_decodes_photoshop_fixture() {
        let path = fixture("from-photoshop");
        if !path.exists() {
            eprintln!("ase fixture missing, skipping");
            return;
        }
        let data = std::fs::read(&path).unwrap();
        let ase = read_ase(&data).expect("decode ase fixture");
        assert!(!ase.colors.is_empty());
        // first entry is an RGB color "#FFCCCC" global
        match &ase.colors[0] {
            AseEntry::Color(c) => {
                assert_eq!(c.name, "#FFCCCC");
                match &c.color {
                    AseColorValue::Rgb { r, g, b, type_ } => {
                        assert_eq!(*r, 1.0);
                        assert!((*g - 0.79998779).abs() < 1e-4);
                        assert!((*b - 0.79998779).abs() < 1e-4);
                        assert_eq!(*type_, AseColorType::Global);
                    }
                    other => panic!("expected rgb, got {:?}", other),
                }
            }
            other => panic!("expected color entry, got {:?}", other),
        }
    }

    #[test]
    fn ase_fixture_round_trip() {
        let path = fixture("piratetrousle-dusk");
        if !path.exists() {
            eprintln!("ase fixture missing, skipping");
            return;
        }
        let data = std::fs::read(&path).unwrap();
        let ase = read_ase(&data).expect("decode");
        // re-encode then decode again must match the decoded structure
        let bytes = write_ase(&ase);
        let again = read_ase(&bytes).expect("re-decode");
        assert_eq!(ase, again);
    }

    #[test]
    fn ase_smoke_header() {
        let bytes = write_ase(&Ase { colors: vec![] });
        // ASEF + version(1,0) + blocksCount(0)
        assert_eq!(&bytes[0..4], b"ASEF");
        let decoded = read_ase(&bytes).unwrap();
        assert!(decoded.colors.is_empty());
    }
}