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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
use binrw::{BinRead, BinReaderExt, BinResult, binread};
use packbits_rle::PackBitsReaderExt;
// Proper size
pub type Integer = u16; // 2 bytes
pub type Short = i16;
pub type UnsignedShort = u16;
pub type Word = u16; // TODO: Check
pub type Long = u32; // 4 bytes
pub type Mode = u16; // 2 bytes
#[derive(BinRead, Debug)]
#[br(big)]
pub struct Fixed {
pub int: i16,
pub fraction: i16,
}
#[derive(BinRead, Debug, Clone, PartialEq, Eq)]
#[br(big)]
pub enum PackType {
#[br(magic(0u16))]
/// Use default packing
Default,
#[br(magic(1u16))]
/// Use no packing
None,
#[br(magic(2u16))]
/// Remove pad byte - supported only for 32-bit pixels (24-bit data)
RemovePadByte,
#[br(magic(3u16))]
/// Run length encoding by pixelSize chunks, one scan line at a time - supported only for 16-bit pixels
RunLengthEncoding,
#[br(magic(4u16))]
/// Run length encoding one component at a time, one scan line at a time, red component first - supported only for 32-bit pixels (24-bit data)
RunLengthEncodedComponents,
Other(u16),
}
#[derive(BinRead, Debug, Copy, Clone)]
#[br(big)]
pub struct Rect {
pub top: Short,
pub left: Short,
pub bottom: Short,
pub right: Short,
}
impl Rect {
pub fn new_with_size(width: Short, height: Short) -> Self {
Self {
top: 0,
left: 0,
bottom: width,
right: height,
}
}
pub fn height(&self) -> Short {
self.bottom - self.top
}
pub fn width(&self) -> Short {
self.right - self.left
}
pub fn origin(&self) -> Point {
Point {
x: self.left,
y: self.top,
}
}
pub fn contains(&self, other: &Rect) -> bool {
self.min_x() <= other.min_x()
&& self.min_y() <= other.min_y()
&& self.max_x() >= other.max_x()
&& self.max_y() >= other.max_y()
}
pub fn includes(&self, x: i32, y: i32) -> bool {
self.min_x() as i32 <= x
&& self.max_x() as i32 >= x
&& self.min_y() as i32 <= y
&& self.max_y() as i32 >= y
}
pub fn min_x(&self) -> Short {
self.left
}
pub fn max_x(&self) -> Short {
self.right
}
pub fn min_y(&self) -> Short {
self.top
}
pub fn max_y(&self) -> Short {
self.bottom
}
}
#[derive(BinRead, Debug)]
#[br(big)]
pub struct Point {
pub x: i16,
pub y: i16,
}
impl std::fmt::Display for Point {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}x{}", self.x, self.y)
}
}
#[derive(BinRead, Debug)]
#[br(big)]
pub struct Pattern {
pub data: [u8; 8],
}
#[binread]
#[derive(Debug)]
pub struct ShortString {
#[br(temp)]
string_len: u8,
#[br(count = string_len)]
#[br(map = |s: Vec<u8>| String::from_utf8_lossy(&s).to_string())]
pub string: String,
}
impl From<ShortString> for String {
fn from(val: ShortString) -> Self {
val.string
}
}
pub type Angle = u16;
#[binread]
#[br(big)]
#[derive(Debug)]
pub struct Region {
#[br(temp)]
pub size: u16,
#[br(if(size >= 2 + 8))]
pub bounding_box: Option<Rect>,
#[br(count((std::cmp::max(10, size) - 10) / 2))]
pub data: Vec<i16>,
}
impl Region {
pub fn as_mask(&self) -> Vec<u8> {
// Decode `data` as run-length encoded sliding window mask as described by Hackerjack
// See https://info-mac.org/viewtopic.php?t=17328 for the post
if let Some(rect) = self.bounding_box {
let width = rect.width() as usize;
let height = rect.height() as usize;
if rect.left != 0 || rect.top != 0 {
log::warn!("Mask is offset: {:?}", rect);
}
if self.data.is_empty() {
log::warn!(
"It does not really make sense to force us to create a mask if you can just check the bounding box"
);
return vec![1u8; width * height];
}
log::info!("Allocating {}x{} mask", width, height);
let mut image: Vec<u8> = vec![0u8; width * height];
let mut cursor = self.data.iter();
let mut last_row = 0;
let mut scanline: Vec<u8> = vec![0u8; width];
loop {
match cursor.next() {
None => {
log::warn!("Unexpected end of data");
return image;
}
Some(0x7fffi16) => {
if last_row < height - 1 {
// apply mask row to rest of image
for row in last_row..height {
image[(row * width)..((row + 1) * width)]
.copy_from_slice(&scanline);
}
}
log::info!("Reached end of region");
return image;
}
Some(row) => loop {
let row = *row as usize;
// apply last row mask to all rows up until this new one
for row in last_row..row {
if image.len() < (row + 1) * width {
log::error!("OOB read prevented");
return image;
}
image[(row * width)..((row + 1) * width)].copy_from_slice(&scanline);
}
last_row = row;
match cursor.next() {
None => {
log::warn!("Unexpected end of data in row {}", row);
return image;
}
Some(0x7fffi16) => {
if row >= height {
log::warn!("Won't apply row that's out of range");
} else {
image[(row * width)..((row + 1) * width)]
.copy_from_slice(&scanline);
}
last_row = row;
break;
}
Some(start) => {
if row >= height {
log::warn!("Row {} is out of range", row);
continue;
}
let Some(end) = cursor.next() else {
log::warn!("Unexpected end of data in row {}", row);
return image;
};
let start = *start as usize;
let end = *end as usize;
for column in start..end {
if column >= width {
log::error!("Column {} is out of range", column);
continue;
}
scanline[column] = if scanline[column] == 0 { 1 } else { 0 };
}
}
}
},
}
}
} else {
log::warn!("Don't know how to create mask image without bounding box");
vec![]
}
}
pub fn contains(&self, x: i32, y: i32) -> bool {
if let Some(bounding_box) = self.bounding_box.as_ref() {
return bounding_box.includes(x, y);
}
true
}
}
#[derive(BinRead, Debug)]
#[br(big)]
pub struct Polygon {
pub size: u16,
#[br(count(size - 2))]
pub data: Vec<u8>,
}
#[repr(C)]
/// source modes for color graphics ports
pub enum SourceMode {
/// determine how close the color of the source pixel is
/// to black, and assign this relative amount of
/// foreground color to the destination pixel; determine
/// how close the color of the source pixel is to white,
/// and assign this relative amount of background color
/// to the destination pixel
SrcCopy = 0,
/// determine how close the color of the source pixel is
/// to black, and assign this relative amount of
/// foreground color to the destination pixel
SrcOr = 1,
/// where source pixel is black, invert the destination
/// pixel--for a colored destination pixel, use the
/// complement of its color if the pixel is direct,
/// invert its index if the pixel is indexed
SrcXor = 2,
/// determine how close the color of the source pixel is
/// to black, and assign this relative amount of
/// background color to the destination pixel
SrcBic = 3,
/// determine how close the color of the source pixel is
/// to black, and assign this relative amount of
/// background color to the destination pixel; determine
/// how close the color of the source pixel is to white,
/// and assign this relative amount of foreground color
/// to the destination pixel
NotSrcCopy = 4,
/// determine how close the color of the source pixel is
/// to white, and assign this relative amount of
/// foreground color to the destination pixel
NotSrcOr = 5,
/// where source pixel is white, invert destination
/// pixel--for a colored destination pixel, use the
/// complement of its color if the pixel is direct,
/// invert its index if the pixel is indexed
NotSrcXor = 6,
/// determine how close the color of the source pixel is
/// to white, and assign this relative amount of
/// background color to the destination pixel
NotSrcBic = 7,
}
#[derive(BinRead, Debug)]
#[br(big)]
pub struct RGBColor {
/// magnitude of red component
pub red: u16,
/// magnitude of green component
pub green: u16,
/// magnitude of blue component
pub blue: u16,
}
#[derive(BinRead, Debug)]
#[br(big)]
pub struct Buffer {
pub len: u16,
#[br(count(len))]
pub data: Vec<u8>,
}
#[derive(BinRead, Debug)]
#[br(big)]
pub struct ColorSpec {
/// index or other value
pub value: Short,
/// true color
pub rgb: RGBColor,
}
#[binread]
#[derive(Debug)]
#[br(big)]
pub struct ColorTable {
/// unique identifier for table
pub ct_seed: u32,
/// high bit: 0 = PixMap; 1 = device
pub ct_flags: u16,
/// number of entries in next field
#[br(temp)]
pub ct_size: u16,
/// array[0..0] of ColorSpec records
#[br(count(if ct_size == 0xFFFF {0} else { ct_size + 1 }))]
pub ct_table: Vec<ColorSpec>,
}
#[derive(Debug)]
pub enum CopyBits {
/// Four opcodes ($0090, $0091, $0098, $0099) are modifications of version 1 opcodes. The first word
/// following the opcode is rowBytes. If the high bit of rowBytes is set, then it is a pixel map
/// containing multiple bits per pixel; if it is not set, it is a bitmap containing 1 bit per pixel. In
/// general, the difference between version 2 and version 1 formats is that the pixel map replaces
/// the bitmap, a color table has been added, and pixData replaces bitData.
Pixmap {
pix_map: PixMap,
color_table: ColorTable,
src_rect: Rect,
dst_rect: Rect,
mode: Word,
mask_region: Option<Region>,
data: Vec<u8>,
},
Bitmap {
bytes_per_row: u16,
bounds: Rect,
src_rect: Rect,
dst_rect: Rect,
mask_region: Option<Region>,
data: Vec<u8>,
},
}
impl BinRead for CopyBits {
type Args<'a> = (bool, bool);
fn read_options<R: std::io::Read + std::io::Seek>(
reader: &mut R,
_endian: binrw::Endian,
(packed, masked): Self::Args<'_>,
) -> BinResult<Self> {
let row_bytes_and_flags_hi: u8 = reader.read_be()?;
let data_is_pixmap = row_bytes_and_flags_hi & 0x80 != 0;
if data_is_pixmap {
let pix_map: PixMap = reader.read_be_args((row_bytes_and_flags_hi,))?;
let color_table: ColorTable = reader.read_be()?;
let src_rect: Rect = reader.read_be()?;
let dst_rect: Rect = reader.read_be()?;
if src_rect.width() != dst_rect.width() {
return Err(binrw::Error::Custom {
pos: reader.stream_position().unwrap(),
err: Box::new("source and destination widths do not match"),
});
}
if src_rect.height() != dst_rect.height() {
return Err(binrw::Error::Custom {
pos: reader.stream_position().unwrap(),
err: Box::new("source and destination heights do not match"),
});
}
let mode: Word = reader.read_be()?;
let mask_region: Option<Region> = if masked {
Some(reader.read_be()?)
} else {
None
};
let scanline_count = pix_map.bounds.height() as usize;
let scanline_size = pix_map.bytes_per_row() as usize;
let unpacked_size = scanline_count * scanline_size;
let mut data = vec![0u8; unpacked_size];
if !packed || scanline_size <= 8 {
reader.read_exact(&mut data)?;
} else {
for y in 0..scanline_count {
#[allow(unused)]
let packed_scanline_size: usize = if scanline_size > 250 {
reader.read_be::<u16>()?.into()
} else {
reader.read_be::<u8>()?.into()
};
// TODO: Use packed_scanline_size to limit bytes read
let unpacked_scanline_range = (y * scanline_size)..((y + 1) * scanline_size);
reader.read_packbits(&mut data[unpacked_scanline_range])?;
}
};
Ok(CopyBits::Pixmap {
pix_map,
color_table,
src_rect,
dst_rect,
mode,
mask_region,
data,
})
} else {
let row_bytes_lo: u8 = reader.read_be()?;
let flags_and_row_bytes = ((row_bytes_and_flags_hi as u16) << 8) | row_bytes_lo as u16;
let bounds: Rect = reader.read_be()?;
let src_rect: Rect = reader.read_be()?;
let dst_rect: Rect = reader.read_be()?;
assert_eq!(
src_rect.width(),
dst_rect.width(),
"source and destination widths do not match"
);
assert_eq!(
src_rect.height(),
dst_rect.height(),
"source and destination heights do not match"
);
let _mode: Word = reader.read_be()?;
let mask_region: Option<Region> = if masked {
Some(reader.read_be()?)
} else {
None
};
let scanline_count = bounds.height() as usize;
let scanline_size = (flags_and_row_bytes & 0x7FFF) as usize;
let unpacked_size = scanline_count * scanline_size;
let mut data = vec![0u8; unpacked_size];
if !packed || scanline_size <= 8 {
reader.read_exact(&mut data)?;
} else {
for y in 0..scanline_count {
#[allow(unused)]
let packed_scanline_size: usize = if scanline_size > 250 {
reader.read_be::<u16>()?.into()
} else {
reader.read_be::<u8>()?.into()
};
let unpacked_scanline_range = (y * scanline_size)..((y + 1) * scanline_size);
// TODO: Use packed_scanline_size to limit bytes read
reader.read_packbits(&mut data[unpacked_scanline_range])?;
}
};
Ok(CopyBits::Bitmap {
bytes_per_row: flags_and_row_bytes,
bounds,
src_rect,
dst_rect,
mask_region,
data,
})
}
}
}
#[binread]
#[derive(Debug)]
#[br(big, import(row_bytes_and_flags_low_byte: u8))]
pub struct PixMap {
/// flags, and row width
#[br(map(|low_bytes:u8| (((row_bytes_and_flags_low_byte & 0x7f) as u16) <<8) | (low_bytes as u16) ))]
pub row_bytes_and_flags: u16,
/// boundary rectangle
pub bounds: Rect,
/// PixMap version number
pub pm_version: i16,
/// packing format
pub pack_type: PackType,
/// size of data in packed state
pub pack_size: u32,
/// horizontal resolution (dpi)
pub h_res: Fixed,
/// vertical resolution (dpi)
pub v_res: Fixed,
/// format of pixel image
pub pixel_type: i16,
/// physical bits per pixel
pub pixel_size: i16,
/// logical components per pixel
pub component_count: i16,
/// logical bits per component
pub component_size: i16,
/// offset to next plane
pub plane_bytes: u32,
/// handle to the ColorTable struct
pub pm_table: u32,
/// reserved for future expansion; must be 0
// #[br(temp, assert(pm_reserved==0))]
pub pm_reserved: u32,
}
impl PixMap {
pub fn bytes_per_row(&self) -> u16 {
self.row_bytes_and_flags & 0x7FFF
}
}
#[derive(Debug, BinRead)]
pub enum CommentKind {
/// Archaic grouping command
#[br(magic(0u16))]
LParen,
/// Ends group begun by RParen
#[br(magic(1u16))]
RParen,
/// Application-specific comment
#[br(magic(100u16))]
AppComment,
/// Begin MacDraw picture
#[br(magic(130u16))]
DwgBeg,
/// End MacDraw picture
#[br(magic(131u16))]
DwgEnd,
/// Begin grouped objects
#[br(magic(140u16))]
GrpBeg,
/// End grouped objects
#[br(magic(141u16))]
GrpEnd,
/// Begin series of bitmap bands
#[br(magic(142u16))]
BitBeg,
/// End of bitmap bands
#[br(magic(143u16))]
BitEnd,
/// Beginning of a text string
#[br(magic(150u16))]
TextBegin,
/// End of text string
#[br(magic(151u16))]
TextEnd,
/// Beginning of banded string
#[br(magic(152u16))]
StringBegin,
/// End of banded string
#[br(magic(153u16))]
StringEnd,
/// Center of rotation to TextBegin
#[br(magic(154u16))]
TextCenter,
/// Turns off line layout
#[br(magic(155u16))]
LineLayoutOff,
/// Turns on line layout
#[br(magic(156u16))]
LineLayoutOn,
/// Specify line layout for next text call
#[br(magic(157u16))]
LineLayout,
/// Following LineTo() operations are part of a polygon
#[br(magic(160u16))]
PolyBegin,
/// End of special MacDraw polygon
#[br(magic(161u16))]
PolyEnd,
/// Following data part of freehand curve
#[br(magic(162u16))]
PlyByt,
/// Ignore the following polygon
#[br(magic(163u16))]
PolyIgnore,
/// Close, fill, frame a polygon
#[br(magic(164u16))]
PolySmooth,
/// MacDraw polygon is closed
#[br(magic(165u16))]
PlyClose,
/// One arrow from point1 to point2
#[br(magic(170u16))]
Arrw1,
/// One arrow from point2 to point1
#[br(magic(171u16))]
Arrw2,
/// Two arrows, one on each end of a line
#[br(magic(172u16))]
Arrw3,
/// End of arrow comment
#[br(magic(173u16))]
ArrwEnd,
/// Subsequent lines are PostScript dashed lines
#[br(magic(180u16))]
DashedLine,
/// Ends picDashedLine comment
#[br(magic(181u16))]
DashedStop,
/// Mult. fraction for pen size
#[br(magic(182u16))]
SetLineWidth,
/// Saves QD state; and send PostScript
#[br(magic(190u16))]
PostScriptBegin,
/// Restore QD state
#[br(magic(191u16))]
PostScriptEnd,
/// Remaining data is PostScript
#[br(magic(192u16))]
PostScriptHandle,
/// Use filename to send 'POST' resources
#[br(magic(193u16))]
PostScriptFile,
/// QD text is PostScript until PostScriptEnd
#[br(magic(194u16))]
TextIsPostScript,
/// Send PostScript from 'STR ' or 'STR#' resources
#[br(magic(195u16))]
ResourcePS,
/// Like PostScriptBegin
#[br(magic(196u16))]
NewPostScriptBegin,
/// Set gray level from fixed-point number
#[br(magic(197u16))]
SetGrayLevel,
/// Begin rotation of the coordinate plane
#[br(magic(200u16))]
RotateBegin,
/// End rotated plane
#[br(magic(201u16))]
RotateEnd,
/// Specifies center of rotation
#[br(magic(202u16))]
RotateCenter,
/// DonÕt flush print buffer after each page
#[br(magic(210u16))]
FormsPrinting,
/// Ends forms printing
#[br(magic(211u16))]
EndFormsPrinting,
/// used by MacDraw II
#[br(magic(214u16))]
AutoNap,
/// used by MacDraw II
#[br(magic(215u16))]
AutoWake,
/// used by MacDraw II
#[br(magic(216u16))]
ManNap,
/// used by MacDraw II
#[br(magic(217u16))]
ManWake,
/// File creator for application
#[br(magic(498u16))]
Creator,
/// Scaling of image
#[br(magic(499u16))]
PICTScale,
/// Begin bitmap thinning
#[br(magic(1000u16))]
BegBitmapThin,
/// End bitmap thinning
#[br(magic(1001u16))]
EndBitmapThin,
/// Image in the scrap created using lasso
#[br(magic(12345u16))]
Lasso,
Unknown(u16),
}
/*
100 is an Application Comment (see below).
220 is used for ICC profile data.
498 appears to be related to Photoshop, though it might also be used for other things.
*/