1 """Macintosh binhex compression/decompression.
4 binhex(inputfilename, outputfilename)
5 hexbin(inputfilename, outputfilename)
9 # Jack Jansen, CWI, August 1995.
11 # The module is supposed to be as compatible as possible. Especially the
12 # easy interface should work "as expected" on any platform.
13 # XXXX Note: currently, textfiles appear in mac-form on all platforms.
14 # We seem to lack a simple character-translate in python.
15 # (we should probably use ISO-Latin-1 on all but the mac platform).
16 # XXXX The simple routines are too simple: they expect to hold the complete
17 # files in-core. Should be fixed.
18 # XXXX It would be nice to handle AppleDouble format on unix
19 # (for servers serving macs).
20 # XXXX I don't understand what happens when you get 0x90 times the same byte on
21 # input. The resulting code (xx 90 90) would appear to be interpreted as an
22 # escaped *value* of 0x90. All coders I've seen appear to ignore this nicety...
29 __all__
= ["binhex","hexbin","Error"]
31 class Error(Exception):
34 # States (what have we written)
35 [_DID_HEADER
, _DID_DATA
, _DID_RSRC
] = range(3)
38 REASONABLY_LARGE
=32768 # Minimal amount we pass the rle-coder
40 RUNCHAR
=chr(0x90) # run-length introducer
43 # This code is no longer byte-order dependent
46 # Workarounds for non-mac machines.
48 from Carbon
.File
import FSSpec
, FInfo
49 from MacOS
import openrf
51 def getfileinfo(name
):
52 finfo
= FSSpec(name
).FSpGetFInfo()
53 dir, file = os
.path
.split(name
)
54 # XXX Get resource/data sizes
58 fp
= openrf(name
, '*rb')
61 return file, finfo
, dlen
, rlen
63 def openrsrc(name
, *mode
):
68 return openrf(name
, mode
)
72 # Glue code for non-macintosh usage
81 def getfileinfo(name
):
83 # Quick check for textfile
85 data
= open(name
).read(256)
87 if not c
.isspace() and (c
<' ' or ord(c
) > 0x7f):
94 dir, file = os
.path
.split(name
)
95 file = file.replace(':', '-', 1)
96 return file, finfo
, dsize
, 0
99 def __init__(self
, *args
):
102 def read(self
, *args
):
105 def write(self
, *args
):
111 class _Hqxcoderengine
:
112 """Write data to the coder in 3-byte chunks"""
114 def __init__(self
, ofp
):
118 self
.linelen
= LINELEN
-1
120 def write(self
, data
):
121 self
.data
= self
.data
+ data
122 datalen
= len(self
.data
)
123 todo
= (datalen
//3)*3
124 data
= self
.data
[:todo
]
125 self
.data
= self
.data
[todo
:]
128 self
.hqxdata
= self
.hqxdata
+ binascii
.b2a_hqx(data
)
131 def _flush(self
, force
):
133 while first
<= len(self
.hqxdata
)-self
.linelen
:
134 last
= first
+ self
.linelen
135 self
.ofp
.write(self
.hqxdata
[first
:last
]+'\n')
136 self
.linelen
= LINELEN
138 self
.hqxdata
= self
.hqxdata
[first
:]
140 self
.ofp
.write(self
.hqxdata
+ ':\n')
145 self
.hqxdata
+ binascii
.b2a_hqx(self
.data
)
150 class _Rlecoderengine
:
151 """Write data to the RLE-coder in suitably large chunks"""
153 def __init__(self
, ofp
):
157 def write(self
, data
):
158 self
.data
= self
.data
+ data
159 if len(self
.data
) < REASONABLY_LARGE
:
161 rledata
= binascii
.rlecode_hqx(self
.data
)
162 self
.ofp
.write(rledata
)
167 rledata
= binascii
.rlecode_hqx(self
.data
)
168 self
.ofp
.write(rledata
)
173 def __init__(self
, name_finfo_dlen_rlen
, ofp
):
174 name
, finfo
, dlen
, rlen
= name_finfo_dlen_rlen
175 if type(ofp
) == type(''):
177 ofp
= open(ofname
, 'w')
180 fss
.SetCreatorType('BnHq', 'TEXT')
181 ofp
.write('(This file must be converted with BinHex 4.0)\n\n:')
182 hqxer
= _Hqxcoderengine(ofp
)
183 self
.ofp
= _Rlecoderengine(hqxer
)
189 self
._writeinfo
(name
, finfo
)
190 self
.state
= _DID_HEADER
192 def _writeinfo(self
, name
, finfo
):
195 raise Error
, 'Filename too long'
196 d
= chr(nl
) + name
+ '\0'
197 d2
= finfo
.Type
+ finfo
.Creator
199 # Force all structs to be packed with big-endian
200 d3
= struct
.pack('>h', finfo
.Flags
)
201 d4
= struct
.pack('>ii', self
.dlen
, self
.rlen
)
202 info
= d
+ d2
+ d3
+ d4
206 def _write(self
, data
):
207 self
.crc
= binascii
.crc_hqx(data
, self
.crc
)
211 # XXXX Should this be here??
212 # self.crc = binascii.crc_hqx('\0\0', self.crc)
217 self
.ofp
.write(struct
.pack(fmt
, self
.crc
))
220 def write(self
, data
):
221 if self
.state
!= _DID_HEADER
:
222 raise Error
, 'Writing data at the wrong time'
223 self
.dlen
= self
.dlen
- len(data
)
226 def close_data(self
):
228 raise Error
, 'Incorrect data size, diff=%r' % (self
.rlen
,)
230 self
.state
= _DID_DATA
232 def write_rsrc(self
, data
):
233 if self
.state
< _DID_DATA
:
235 if self
.state
!= _DID_DATA
:
236 raise Error
, 'Writing resource data at the wrong time'
237 self
.rlen
= self
.rlen
- len(data
)
241 if self
.state
< _DID_DATA
:
243 if self
.state
!= _DID_DATA
:
244 raise Error
, 'Close at the wrong time'
247 "Incorrect resource-datasize, diff=%r" % (self
.rlen
,)
253 def binhex(inp
, out
):
254 """(infilename, outfilename) - Create binhex-encoded copy of a file"""
255 finfo
= getfileinfo(inp
)
256 ofp
= BinHex(finfo
, out
)
258 ifp
= open(inp
, 'rb')
259 # XXXX Do textfile translation on non-mac systems
267 ifp
= openrsrc(inp
, 'rb')
275 class _Hqxdecoderengine
:
276 """Read data via the decoder in 4-byte chunks"""
278 def __init__(self
, ifp
):
282 def read(self
, totalwtd
):
283 """Read at least wtd bytes (or until EOF)"""
287 # The loop here is convoluted, since we don't really now how
288 # much to decode: there may be newlines in the incoming data.
290 if self
.eof
: return decdata
292 data
= self
.ifp
.read(wtd
)
294 # Next problem: there may not be a complete number of
295 # bytes in what we pass to a2b. Solve by yet another
300 decdatacur
, self
.eof
= \
301 binascii
.a2b_hqx(data
)
303 except binascii
.Incomplete
:
305 newdata
= self
.ifp
.read(1)
308 'Premature EOF on binhex file'
309 data
= data
+ newdata
310 decdata
= decdata
+ decdatacur
311 wtd
= totalwtd
- len(decdata
)
312 if not decdata
and not self
.eof
:
313 raise Error
, 'Premature EOF on binhex file'
319 class _Rledecoderengine
:
320 """Read data via the RLE-coder"""
322 def __init__(self
, ifp
):
325 self
.post_buffer
= ''
329 if wtd
> len(self
.post_buffer
):
330 self
._fill
(wtd
-len(self
.post_buffer
))
331 rv
= self
.post_buffer
[:wtd
]
332 self
.post_buffer
= self
.post_buffer
[wtd
:]
335 def _fill(self
, wtd
):
336 self
.pre_buffer
= self
.pre_buffer
+ self
.ifp
.read(wtd
+4)
338 self
.post_buffer
= self
.post_buffer
+ \
339 binascii
.rledecode_hqx(self
.pre_buffer
)
344 # Obfuscated code ahead. We have to take care that we don't
345 # end up with an orphaned RUNCHAR later on. So, we keep a couple
346 # of bytes in the buffer, depending on what the end of
347 # the buffer looks like:
348 # '\220\0\220' - Keep 3 bytes: repeated \220 (escaped as \220\0)
349 # '?\220' - Keep 2 bytes: repeated something-else
350 # '\220\0' - Escaped \220: Keep 2 bytes.
351 # '?\220?' - Complete repeat sequence: decode all
352 # otherwise: keep 1 byte.
354 mark
= len(self
.pre_buffer
)
355 if self
.pre_buffer
[-3:] == RUNCHAR
+ '\0' + RUNCHAR
:
357 elif self
.pre_buffer
[-1] == RUNCHAR
:
359 elif self
.pre_buffer
[-2:] == RUNCHAR
+ '\0':
361 elif self
.pre_buffer
[-2] == RUNCHAR
:
366 self
.post_buffer
= self
.post_buffer
+ \
367 binascii
.rledecode_hqx(self
.pre_buffer
[:mark
])
368 self
.pre_buffer
= self
.pre_buffer
[mark
:]
374 def __init__(self
, ifp
):
375 if type(ifp
) == type(''):
378 # Find initial colon.
383 raise Error
, "No binhex data found"
384 # Cater for \r\n terminated lines (which show up as \n\r, hence
385 # all lines start with \r)
391 dummy
= ifp
.readline()
393 hqxifp
= _Hqxdecoderengine(ifp
)
394 self
.ifp
= _Rledecoderengine(hqxifp
)
398 def _read(self
, len):
399 data
= self
.ifp
.read(len)
400 self
.crc
= binascii
.crc_hqx(data
, self
.crc
)
404 filecrc
= struct
.unpack('>h', self
.ifp
.read(2))[0] & 0xffff
405 #self.crc = binascii.crc_hqx('\0\0', self.crc)
406 # XXXX Is this needed??
407 self
.crc
= self
.crc
& 0xffff
408 if filecrc
!= self
.crc
:
409 raise Error
, 'CRC error, computed %x, read %x' \
413 def _readheader(self
):
415 fname
= self
._read
(ord(len))
416 rest
= self
._read
(1+4+4+2+4+4)
421 flags
= struct
.unpack('>h', rest
[9:11])[0]
422 self
.dlen
= struct
.unpack('>l', rest
[11:15])[0]
423 self
.rlen
= struct
.unpack('>l', rest
[15:19])[0]
427 self
.FInfo
.Creator
= creator
428 self
.FInfo
.Type
= type
429 self
.FInfo
.Flags
= flags
431 self
.state
= _DID_HEADER
434 if self
.state
!= _DID_HEADER
:
435 raise Error
, 'Read data at wrong time'
438 n
= min(n
, self
.dlen
)
443 rv
= rv
+ self
._read
(n
-len(rv
))
444 self
.dlen
= self
.dlen
- n
447 def close_data(self
):
448 if self
.state
!= _DID_HEADER
:
449 raise Error
, 'close_data at wrong time'
451 dummy
= self
._read
(self
.dlen
)
453 self
.state
= _DID_DATA
455 def read_rsrc(self
, *n
):
456 if self
.state
== _DID_HEADER
:
458 if self
.state
!= _DID_DATA
:
459 raise Error
, 'Read resource data at wrong time'
462 n
= min(n
, self
.rlen
)
465 self
.rlen
= self
.rlen
- n
470 dummy
= self
.read_rsrc(self
.rlen
)
472 self
.state
= _DID_RSRC
475 def hexbin(inp
, out
):
476 """(infilename, outfilename) - Decode binhexed file"""
483 out
= ofss
.as_pathname()
485 ofp
= open(out
, 'wb')
486 # XXXX Do translation on non-mac systems
494 d
= ifp
.read_rsrc(128000)
496 ofp
= openrsrc(out
, 'wb')
499 d
= ifp
.read_rsrc(128000)
505 nfinfo
= ofss
.GetFInfo()
506 nfinfo
.Creator
= finfo
.Creator
507 nfinfo
.Type
= finfo
.Type
508 nfinfo
.Flags
= finfo
.Flags
509 ofss
.SetFInfo(nfinfo
)
515 binhex(fname
, fname
+'.hqx')
516 hexbin(fname
+'.hqx', fname
+'.viahqx')
517 #hexbin(fname, fname+'.unpacked')
520 if __name__
== '__main__':