blob: aa0f2cda68c807431fb0e58f8ae6e4ccae37d888 [file] [log] [blame]
Jack Jansend0fc42f2001-08-19 22:05:06 +00001"""Tools for use in AppleEvent clients and servers:
2conversion between AE types and python types
3
4pack(x) converts a Python object to an AEDesc object
5unpack(desc) does the reverse
6coerce(x, wanted_sample) coerces a python object to another python object
7"""
8
9#
10# This code was originally written by Guido, and modified/extended by Jack
11# to include the various types that were missing. The reference used is
12# Apple Event Registry, chapter 9.
13#
14
15import struct
Jack Jansen5a6fdcd2001-08-25 12:15:04 +000016from Carbon import AE
17from Carbon.AppleEvents import *
Jack Jansend0fc42f2001-08-19 22:05:06 +000018import MacOS
Jack Jansen2b88dec2003-01-28 23:53:40 +000019import Carbon.File
Jack Jansend0fc42f2001-08-19 22:05:06 +000020import StringIO
21import aetypes
Jack Jansenfc710262003-03-31 13:32:59 +000022from aetypes import mkenum, ObjectSpecifier
Jack Jansen8b777672002-08-07 14:49:00 +000023import os
Jack Jansend0fc42f2001-08-19 22:05:06 +000024
25# These ones seem to be missing from AppleEvents
26# (they're in AERegistry.h)
27
Guido van Rossumf7a94e42007-07-27 04:41:00 +000028#typeColorTable = b'clrt'
29#typeDrawingArea = b'cdrw'
30#typePixelMap = b'cpix'
31#typePixelMapMinus = b'tpmm'
32#typeRotation = b'trot'
33#typeTextStyles = b'tsty'
34#typeStyledText = b'STXT'
35#typeAEText = b'tTXT'
36#typeEnumeration = b'enum'
Jack Jansend0fc42f2001-08-19 22:05:06 +000037
Guido van Rossumf7a94e42007-07-27 04:41:00 +000038def b2i(byte_string):
39 result = 0
40 for byte in byte_string:
41 result <<= 8
42 result += byte
43 return result
Jack Jansend0fc42f2001-08-19 22:05:06 +000044#
45# Some AE types are immedeately coerced into something
46# we like better (and which is equivalent)
47#
48unpacker_coercions = {
Guido van Rossumf7a94e42007-07-27 04:41:00 +000049 b2i(typeComp) : typeFloat,
50 b2i(typeColorTable) : typeAEList,
51 b2i(typeDrawingArea) : typeAERecord,
52 b2i(typeFixed) : typeFloat,
53 b2i(typeExtended) : typeFloat,
54 b2i(typePixelMap) : typeAERecord,
55 b2i(typeRotation) : typeAERecord,
56 b2i(typeStyledText) : typeAERecord,
57 b2i(typeTextStyles) : typeAERecord,
Jack Jansend0fc42f2001-08-19 22:05:06 +000058};
59
60#
61# Some python types we need in the packer:
62#
Jack Jansenad5dcaf2002-03-30 23:44:58 +000063AEDescType = AE.AEDescType
Jack Jansen2b88dec2003-01-28 23:53:40 +000064FSSType = Carbon.File.FSSpecType
65FSRefType = Carbon.File.FSRefType
66AliasType = Carbon.File.AliasType
Jack Jansend0fc42f2001-08-19 22:05:06 +000067
Jack Jansen8b777672002-08-07 14:49:00 +000068def packkey(ae, key, value):
Jack Jansen0ae32202003-04-09 13:25:43 +000069 if hasattr(key, 'which'):
70 keystr = key.which
71 elif hasattr(key, 'want'):
72 keystr = key.want
73 else:
74 keystr = key
75 ae.AEPutParamDesc(keystr, pack(value))
Jack Jansen8b777672002-08-07 14:49:00 +000076
Jack Jansend0fc42f2001-08-19 22:05:06 +000077def pack(x, forcetype = None):
Jack Jansen0ae32202003-04-09 13:25:43 +000078 """Pack a python object into an AE descriptor"""
Tim Peters182b5ac2004-07-18 06:16:08 +000079
Jack Jansen0ae32202003-04-09 13:25:43 +000080 if forcetype:
Guido van Rossumf7a94e42007-07-27 04:41:00 +000081 if isinstance(x, bytes):
Jack Jansen0ae32202003-04-09 13:25:43 +000082 return AE.AECreateDesc(forcetype, x)
83 else:
84 return pack(x).AECoerceDesc(forcetype)
Tim Peters182b5ac2004-07-18 06:16:08 +000085
Jack Jansen0ae32202003-04-09 13:25:43 +000086 if x == None:
Guido van Rossumf7a94e42007-07-27 04:41:00 +000087 return AE.AECreateDesc(b'null', '')
Tim Peters182b5ac2004-07-18 06:16:08 +000088
Jack Jansen0ae32202003-04-09 13:25:43 +000089 if isinstance(x, AEDescType):
90 return x
91 if isinstance(x, FSSType):
Guido van Rossumf7a94e42007-07-27 04:41:00 +000092 return AE.AECreateDesc(b'fss ', x.data)
Jack Jansen0ae32202003-04-09 13:25:43 +000093 if isinstance(x, FSRefType):
Guido van Rossumf7a94e42007-07-27 04:41:00 +000094 return AE.AECreateDesc(b'fsrf', x.data)
Jack Jansen0ae32202003-04-09 13:25:43 +000095 if isinstance(x, AliasType):
Guido van Rossumf7a94e42007-07-27 04:41:00 +000096 return AE.AECreateDesc(b'alis', x.data)
Guido van Rossum13257902007-06-07 23:15:56 +000097 if isinstance(x, int):
Guido van Rossumf7a94e42007-07-27 04:41:00 +000098 return AE.AECreateDesc(b'long', struct.pack('l', x))
Guido van Rossum13257902007-06-07 23:15:56 +000099 if isinstance(x, float):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000100 return AE.AECreateDesc(b'doub', struct.pack('d', x))
101 if isinstance(x, (bytes, str8)):
102 return AE.AECreateDesc(b'TEXT', x)
Guido van Rossum13257902007-06-07 23:15:56 +0000103 if isinstance(x, str):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000104 # See http://developer.apple.com/documentation/Carbon/Reference/Apple_Event_Manager/Reference/reference.html#//apple_ref/doc/constant_group/typeUnicodeText
105 # for the possible encodings.
Jack Jansen0ae32202003-04-09 13:25:43 +0000106 data = x.encode('utf16')
107 if data[:2] == '\xfe\xff':
108 data = data[2:]
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000109 return AE.AECreateDesc(b'utxt', data)
Guido van Rossum13257902007-06-07 23:15:56 +0000110 if isinstance(x, list):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000111 lst = AE.AECreateList('', 0)
Jack Jansen0ae32202003-04-09 13:25:43 +0000112 for item in x:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000113 lst.AEPutDesc(0, pack(item))
114 return lst
Guido van Rossum13257902007-06-07 23:15:56 +0000115 if isinstance(x, dict):
Jack Jansen0ae32202003-04-09 13:25:43 +0000116 record = AE.AECreateList('', 1)
117 for key, value in x.items():
118 packkey(record, key, value)
119 #record.AEPutParamDesc(key, pack(value))
120 return record
Guido van Rossum13257902007-06-07 23:15:56 +0000121 if isinstance(x, type) and issubclass(x, ObjectSpecifier):
Jack Jansen0ae32202003-04-09 13:25:43 +0000122 # Note: we are getting a class object here, not an instance
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000123 return AE.AECreateDesc(b'type', x.want)
Jack Jansen0ae32202003-04-09 13:25:43 +0000124 if hasattr(x, '__aepack__'):
125 return x.__aepack__()
126 if hasattr(x, 'which'):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000127 return AE.AECreateDesc(b'TEXT', x.which)
Jack Jansen0ae32202003-04-09 13:25:43 +0000128 if hasattr(x, 'want'):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000129 return AE.AECreateDesc(b'TEXT', x.want)
130 return AE.AECreateDesc(b'TEXT', repr(x)) # Copout
Jack Jansend0fc42f2001-08-19 22:05:06 +0000131
Jack Jansen8b777672002-08-07 14:49:00 +0000132def unpack(desc, formodulename=""):
Jack Jansen0ae32202003-04-09 13:25:43 +0000133 """Unpack an AE descriptor to a python object"""
134 t = desc.type
Tim Peters182b5ac2004-07-18 06:16:08 +0000135
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000136 if b2i(t) in unpacker_coercions:
137 desc = desc.AECoerceDesc(unpacker_coercions[b2i(t)])
Jack Jansen0ae32202003-04-09 13:25:43 +0000138 t = desc.type # This is a guess by Jack....
Tim Peters182b5ac2004-07-18 06:16:08 +0000139
Jack Jansen0ae32202003-04-09 13:25:43 +0000140 if t == typeAEList:
141 l = []
142 for i in range(desc.AECountItems()):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000143 keyword, item = desc.AEGetNthDesc(i+1, b'****')
Jack Jansen0ae32202003-04-09 13:25:43 +0000144 l.append(unpack(item, formodulename))
145 return l
146 if t == typeAERecord:
147 d = {}
148 for i in range(desc.AECountItems()):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000149 keyword, item = desc.AEGetNthDesc(i+1, b'****')
150 d[b2i(keyword)] = unpack(item, formodulename)
Jack Jansen0ae32202003-04-09 13:25:43 +0000151 return d
152 if t == typeAEText:
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000153 record = desc.AECoerceDesc(b'reco')
Jack Jansen0ae32202003-04-09 13:25:43 +0000154 return mkaetext(unpack(record, formodulename))
155 if t == typeAlias:
156 return Carbon.File.Alias(rawdata=desc.data)
157 # typeAppleEvent returned as unknown
158 if t == typeBoolean:
159 return struct.unpack('b', desc.data)[0]
160 if t == typeChar:
161 return desc.data
162 if t == typeUnicodeText:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000163 return str(desc.data, 'utf16')
Jack Jansen0ae32202003-04-09 13:25:43 +0000164 # typeColorTable coerced to typeAEList
165 # typeComp coerced to extended
166 # typeData returned as unknown
167 # typeDrawingArea coerced to typeAERecord
168 if t == typeEnumeration:
169 return mkenum(desc.data)
170 # typeEPS returned as unknown
171 if t == typeFalse:
172 return 0
173 if t == typeFloat:
174 data = desc.data
175 return struct.unpack('d', data)[0]
176 if t == typeFSS:
177 return Carbon.File.FSSpec(rawdata=desc.data)
178 if t == typeFSRef:
179 return Carbon.File.FSRef(rawdata=desc.data)
180 if t == typeInsertionLoc:
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000181 record = desc.AECoerceDesc(b'reco')
Jack Jansen0ae32202003-04-09 13:25:43 +0000182 return mkinsertionloc(unpack(record, formodulename))
183 # typeInteger equal to typeLongInteger
184 if t == typeIntlText:
185 script, language = struct.unpack('hh', desc.data[:4])
186 return aetypes.IntlText(script, language, desc.data[4:])
187 if t == typeIntlWritingCode:
188 script, language = struct.unpack('hh', desc.data)
189 return aetypes.IntlWritingCode(script, language)
190 if t == typeKeyword:
191 return mkkeyword(desc.data)
192 if t == typeLongInteger:
193 return struct.unpack('l', desc.data)[0]
194 if t == typeLongDateTime:
195 a, b = struct.unpack('lL', desc.data)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000196 return (int(a) << 32) + b
Jack Jansen0ae32202003-04-09 13:25:43 +0000197 if t == typeNull:
198 return None
199 if t == typeMagnitude:
200 v = struct.unpack('l', desc.data)
201 if v < 0:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000202 v = 0x100000000 + v
Jack Jansen0ae32202003-04-09 13:25:43 +0000203 return v
204 if t == typeObjectSpecifier:
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000205 record = desc.AECoerceDesc(b'reco')
Jack Jansen0ae32202003-04-09 13:25:43 +0000206 # If we have been told the name of the module we are unpacking aedescs for,
207 # we can attempt to create the right type of python object from that module.
208 if formodulename:
209 return mkobjectfrommodule(unpack(record, formodulename), formodulename)
210 return mkobject(unpack(record, formodulename))
211 # typePict returned as unknown
212 # typePixelMap coerced to typeAERecord
213 # typePixelMapMinus returned as unknown
214 # typeProcessSerialNumber returned as unknown
215 if t == typeQDPoint:
216 v, h = struct.unpack('hh', desc.data)
217 return aetypes.QDPoint(v, h)
218 if t == typeQDRectangle:
219 v0, h0, v1, h1 = struct.unpack('hhhh', desc.data)
220 return aetypes.QDRectangle(v0, h0, v1, h1)
221 if t == typeRGBColor:
222 r, g, b = struct.unpack('hhh', desc.data)
223 return aetypes.RGBColor(r, g, b)
224 # typeRotation coerced to typeAERecord
225 # typeScrapStyles returned as unknown
226 # typeSessionID returned as unknown
227 if t == typeShortFloat:
228 return struct.unpack('f', desc.data)[0]
229 if t == typeShortInteger:
230 return struct.unpack('h', desc.data)[0]
231 # typeSMFloat identical to typeShortFloat
232 # typeSMInt indetical to typeShortInt
233 # typeStyledText coerced to typeAERecord
234 if t == typeTargetID:
235 return mktargetid(desc.data)
236 # typeTextStyles coerced to typeAERecord
237 # typeTIFF returned as unknown
238 if t == typeTrue:
239 return 1
240 if t == typeType:
241 return mktype(desc.data, formodulename)
242 #
243 # The following are special
244 #
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000245 if t == b'rang':
246 record = desc.AECoerceDesc(b'reco')
Jack Jansen0ae32202003-04-09 13:25:43 +0000247 return mkrange(unpack(record, formodulename))
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000248 if t == b'cmpd':
249 record = desc.AECoerceDesc(b'reco')
Jack Jansen0ae32202003-04-09 13:25:43 +0000250 return mkcomparison(unpack(record, formodulename))
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000251 if t == b'logi':
252 record = desc.AECoerceDesc(b'reco')
Jack Jansen0ae32202003-04-09 13:25:43 +0000253 return mklogical(unpack(record, formodulename))
254 return mkunknown(desc.type, desc.data)
Tim Peters182b5ac2004-07-18 06:16:08 +0000255
Jack Jansend0fc42f2001-08-19 22:05:06 +0000256def coerce(data, egdata):
Jack Jansen0ae32202003-04-09 13:25:43 +0000257 """Coerce a python object to another type using the AE coercers"""
258 pdata = pack(data)
259 pegdata = pack(egdata)
260 pdata = pdata.AECoerceDesc(pegdata.type)
261 return unpack(pdata)
Jack Jansend0fc42f2001-08-19 22:05:06 +0000262
263#
264# Helper routines for unpack
265#
266def mktargetid(data):
Jack Jansen0ae32202003-04-09 13:25:43 +0000267 sessionID = getlong(data[:4])
268 name = mkppcportrec(data[4:4+72])
269 location = mklocationnamerec(data[76:76+36])
270 rcvrName = mkppcportrec(data[112:112+72])
271 return sessionID, name, location, rcvrName
Jack Jansend0fc42f2001-08-19 22:05:06 +0000272
273def mkppcportrec(rec):
Jack Jansen0ae32202003-04-09 13:25:43 +0000274 namescript = getword(rec[:2])
275 name = getpstr(rec[2:2+33])
276 portkind = getword(rec[36:38])
277 if portkind == 1:
278 ctor = rec[38:42]
279 type = rec[42:46]
280 identity = (ctor, type)
281 else:
282 identity = getpstr(rec[38:38+33])
283 return namescript, name, portkind, identity
Jack Jansend0fc42f2001-08-19 22:05:06 +0000284
285def mklocationnamerec(rec):
Jack Jansen0ae32202003-04-09 13:25:43 +0000286 kind = getword(rec[:2])
287 stuff = rec[2:]
288 if kind == 0: stuff = None
289 if kind == 2: stuff = getpstr(stuff)
290 return kind, stuff
Jack Jansend0fc42f2001-08-19 22:05:06 +0000291
292def mkunknown(type, data):
Jack Jansen0ae32202003-04-09 13:25:43 +0000293 return aetypes.Unknown(type, data)
Jack Jansend0fc42f2001-08-19 22:05:06 +0000294
295def getpstr(s):
Jack Jansen0ae32202003-04-09 13:25:43 +0000296 return s[1:1+ord(s[0])]
Jack Jansend0fc42f2001-08-19 22:05:06 +0000297
298def getlong(s):
Jack Jansen0ae32202003-04-09 13:25:43 +0000299 return (ord(s[0])<<24) | (ord(s[1])<<16) | (ord(s[2])<<8) | ord(s[3])
Jack Jansend0fc42f2001-08-19 22:05:06 +0000300
301def getword(s):
Jack Jansen0ae32202003-04-09 13:25:43 +0000302 return (ord(s[0])<<8) | (ord(s[1])<<0)
Jack Jansend0fc42f2001-08-19 22:05:06 +0000303
304def mkkeyword(keyword):
Jack Jansen0ae32202003-04-09 13:25:43 +0000305 return aetypes.Keyword(keyword)
Jack Jansend0fc42f2001-08-19 22:05:06 +0000306
307def mkrange(dict):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000308 return aetypes.Range(dict[b2i(b'star')], dict[b2i(b'stop')])
Jack Jansend0fc42f2001-08-19 22:05:06 +0000309
310def mkcomparison(dict):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000311 return aetypes.Comparison(dict[b2i(b'obj1')],
312 dict[b2i(b'relo')].enum,
313 dict[b2i(b'obj2')])
Jack Jansend0fc42f2001-08-19 22:05:06 +0000314
315def mklogical(dict):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000316 return aetypes.Logical(dict[b2i(b'logc')], dict[b2i(b'term')])
Jack Jansend0fc42f2001-08-19 22:05:06 +0000317
318def mkstyledtext(dict):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000319 return aetypes.StyledText(dict[b2i(b'ksty')], dict[b2i(b'ktxt')])
Tim Peters182b5ac2004-07-18 06:16:08 +0000320
Jack Jansend0fc42f2001-08-19 22:05:06 +0000321def mkaetext(dict):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000322 return aetypes.AEText(dict[b2i(keyAEScriptTag)],
323 dict[b2i(keyAEStyles)],
324 dict[b2i(keyAEText)])
Tim Peters182b5ac2004-07-18 06:16:08 +0000325
Jack Jansend0fc42f2001-08-19 22:05:06 +0000326def mkinsertionloc(dict):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000327 return aetypes.InsertionLoc(dict[b2i(keyAEObject)],
328 dict[b2i(keyAEPosition)])
Jack Jansend0fc42f2001-08-19 22:05:06 +0000329
330def mkobject(dict):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000331 want = dict[b2i(b'want')].type
332 form = dict[b2i(b'form')].enum
333 seld = dict[b2i(b'seld')]
334 fr = dict[b2i(b'from')]
335 if form in (b'name', b'indx', b'rang', b'test'):
336 if want == b'text': return aetypes.Text(seld, fr)
337 if want == b'cha ': return aetypes.Character(seld, fr)
338 if want == b'cwor': return aetypes.Word(seld, fr)
339 if want == b'clin': return aetypes.Line(seld, fr)
340 if want == b'cpar': return aetypes.Paragraph(seld, fr)
341 if want == b'cwin': return aetypes.Window(seld, fr)
342 if want == b'docu': return aetypes.Document(seld, fr)
343 if want == b'file': return aetypes.File(seld, fr)
344 if want == b'cins': return aetypes.InsertionPoint(seld, fr)
345 if want == b'prop' and form == b'prop' and aetypes.IsType(seld):
Jack Jansen0ae32202003-04-09 13:25:43 +0000346 return aetypes.Property(seld.type, fr)
347 return aetypes.ObjectSpecifier(want, form, seld, fr)
Jack Jansend0fc42f2001-08-19 22:05:06 +0000348
Jack Jansen8b777672002-08-07 14:49:00 +0000349# Note by Jack: I'm not 100% sure of the following code. This was
350# provided by Donovan Preston, but I wonder whether the assignment
351# to __class__ is safe. Moreover, shouldn't there be a better
352# initializer for the classes in the suites?
353def mkobjectfrommodule(dict, modulename):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000354 if (isinstance(dict[b2i(b'want')], type) and
355 issubclass(dict[b2i(b'want')], ObjectSpecifier)):
Jack Jansen0ae32202003-04-09 13:25:43 +0000356 # The type has already been converted to Python. Convert back:-(
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000357 classtype = dict[b2i(b'want')]
358 dict[b2i(b'want')] = aetypes.mktype(classtype.want)
359 want = dict[b2i(b'want')].type
Jack Jansen0ae32202003-04-09 13:25:43 +0000360 module = __import__(modulename)
361 codenamemapper = module._classdeclarations
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000362 classtype = codenamemapper.get(b2i(want), None)
Jack Jansen0ae32202003-04-09 13:25:43 +0000363 newobj = mkobject(dict)
364 if classtype:
365 assert issubclass(classtype, ObjectSpecifier)
366 newobj.__class__ = classtype
367 return newobj
Tim Peters182b5ac2004-07-18 06:16:08 +0000368
Jack Jansenfc710262003-03-31 13:32:59 +0000369def mktype(typecode, modulename=None):
Jack Jansen0ae32202003-04-09 13:25:43 +0000370 if modulename:
371 module = __import__(modulename)
372 codenamemapper = module._classdeclarations
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000373 classtype = codenamemapper.get(b2i(typecode), None)
Jack Jansen0ae32202003-04-09 13:25:43 +0000374 if classtype:
375 return classtype
376 return aetypes.mktype(typecode)