blob: b0301409dedea846359dd1b873e52d7f6687e6fb [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
Guido van Rossum34d19282007-08-09 01:03:29 +000020import io
Jack Jansend0fc42f2001-08-19 22:05:06 +000021import aetypes
Jack Jansenfc710262003-03-31 13:32:59 +000022from aetypes import mkenum, ObjectSpecifier
Jack Jansend0fc42f2001-08-19 22:05:06 +000023
24# These ones seem to be missing from AppleEvents
25# (they're in AERegistry.h)
26
Guido van Rossumf7a94e42007-07-27 04:41:00 +000027#typeColorTable = b'clrt'
28#typeDrawingArea = b'cdrw'
29#typePixelMap = b'cpix'
30#typePixelMapMinus = b'tpmm'
31#typeRotation = b'trot'
32#typeTextStyles = b'tsty'
33#typeStyledText = b'STXT'
34#typeAEText = b'tTXT'
35#typeEnumeration = b'enum'
Jack Jansend0fc42f2001-08-19 22:05:06 +000036
Guido van Rossumf7a94e42007-07-27 04:41:00 +000037def b2i(byte_string):
38 result = 0
39 for byte in byte_string:
40 result <<= 8
41 result += byte
42 return result
Jack Jansend0fc42f2001-08-19 22:05:06 +000043#
44# Some AE types are immedeately coerced into something
45# we like better (and which is equivalent)
46#
47unpacker_coercions = {
Guido van Rossumf7a94e42007-07-27 04:41:00 +000048 b2i(typeComp) : typeFloat,
49 b2i(typeColorTable) : typeAEList,
50 b2i(typeDrawingArea) : typeAERecord,
51 b2i(typeFixed) : typeFloat,
52 b2i(typeExtended) : typeFloat,
53 b2i(typePixelMap) : typeAERecord,
54 b2i(typeRotation) : typeAERecord,
55 b2i(typeStyledText) : typeAERecord,
56 b2i(typeTextStyles) : typeAERecord,
Jack Jansend0fc42f2001-08-19 22:05:06 +000057};
58
59#
60# Some python types we need in the packer:
61#
Jack Jansenad5dcaf2002-03-30 23:44:58 +000062AEDescType = AE.AEDescType
Jack Jansen2b88dec2003-01-28 23:53:40 +000063FSSType = Carbon.File.FSSpecType
64FSRefType = Carbon.File.FSRefType
65AliasType = Carbon.File.AliasType
Jack Jansend0fc42f2001-08-19 22:05:06 +000066
Jack Jansen8b777672002-08-07 14:49:00 +000067def packkey(ae, key, value):
Jack Jansen0ae32202003-04-09 13:25:43 +000068 if hasattr(key, 'which'):
69 keystr = key.which
70 elif hasattr(key, 'want'):
71 keystr = key.want
72 else:
73 keystr = key
74 ae.AEPutParamDesc(keystr, pack(value))
Jack Jansen8b777672002-08-07 14:49:00 +000075
Jack Jansend0fc42f2001-08-19 22:05:06 +000076def pack(x, forcetype = None):
Jack Jansen0ae32202003-04-09 13:25:43 +000077 """Pack a python object into an AE descriptor"""
Tim Peters182b5ac2004-07-18 06:16:08 +000078
Jack Jansen0ae32202003-04-09 13:25:43 +000079 if forcetype:
Guido van Rossumf7a94e42007-07-27 04:41:00 +000080 if isinstance(x, bytes):
Jack Jansen0ae32202003-04-09 13:25:43 +000081 return AE.AECreateDesc(forcetype, x)
82 else:
83 return pack(x).AECoerceDesc(forcetype)
Tim Peters182b5ac2004-07-18 06:16:08 +000084
Jack Jansen0ae32202003-04-09 13:25:43 +000085 if x == None:
Guido van Rossumf7a94e42007-07-27 04:41:00 +000086 return AE.AECreateDesc(b'null', '')
Tim Peters182b5ac2004-07-18 06:16:08 +000087
Jack Jansen0ae32202003-04-09 13:25:43 +000088 if isinstance(x, AEDescType):
89 return x
90 if isinstance(x, FSSType):
Guido van Rossumf7a94e42007-07-27 04:41:00 +000091 return AE.AECreateDesc(b'fss ', x.data)
Jack Jansen0ae32202003-04-09 13:25:43 +000092 if isinstance(x, FSRefType):
Guido van Rossumf7a94e42007-07-27 04:41:00 +000093 return AE.AECreateDesc(b'fsrf', x.data)
Jack Jansen0ae32202003-04-09 13:25:43 +000094 if isinstance(x, AliasType):
Guido van Rossumf7a94e42007-07-27 04:41:00 +000095 return AE.AECreateDesc(b'alis', x.data)
Guido van Rossum13257902007-06-07 23:15:56 +000096 if isinstance(x, int):
Guido van Rossumf7a94e42007-07-27 04:41:00 +000097 return AE.AECreateDesc(b'long', struct.pack('l', x))
Guido van Rossum13257902007-06-07 23:15:56 +000098 if isinstance(x, float):
Guido van Rossumf7a94e42007-07-27 04:41:00 +000099 return AE.AECreateDesc(b'doub', struct.pack('d', x))
Guido van Rossum254348e2007-11-21 19:29:53 +0000100 if isinstance(x, (bytes, bytearray)):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000101 return AE.AECreateDesc(b'TEXT', x)
Guido van Rossum13257902007-06-07 23:15:56 +0000102 if isinstance(x, str):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000103 # See http://developer.apple.com/documentation/Carbon/Reference/Apple_Event_Manager/Reference/reference.html#//apple_ref/doc/constant_group/typeUnicodeText
104 # for the possible encodings.
Jack Jansen0ae32202003-04-09 13:25:43 +0000105 data = x.encode('utf16')
Neal Norwitzf40080f2007-08-30 06:32:09 +0000106 if data[:2] == b'\xfe\xff':
Jack Jansen0ae32202003-04-09 13:25:43 +0000107 data = data[2:]
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000108 return AE.AECreateDesc(b'utxt', data)
Guido van Rossum13257902007-06-07 23:15:56 +0000109 if isinstance(x, list):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000110 lst = AE.AECreateList('', 0)
Jack Jansen0ae32202003-04-09 13:25:43 +0000111 for item in x:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000112 lst.AEPutDesc(0, pack(item))
113 return lst
Guido van Rossum13257902007-06-07 23:15:56 +0000114 if isinstance(x, dict):
Jack Jansen0ae32202003-04-09 13:25:43 +0000115 record = AE.AECreateList('', 1)
116 for key, value in x.items():
117 packkey(record, key, value)
118 #record.AEPutParamDesc(key, pack(value))
119 return record
Guido van Rossum13257902007-06-07 23:15:56 +0000120 if isinstance(x, type) and issubclass(x, ObjectSpecifier):
Jack Jansen0ae32202003-04-09 13:25:43 +0000121 # Note: we are getting a class object here, not an instance
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000122 return AE.AECreateDesc(b'type', x.want)
Jack Jansen0ae32202003-04-09 13:25:43 +0000123 if hasattr(x, '__aepack__'):
124 return x.__aepack__()
125 if hasattr(x, 'which'):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000126 return AE.AECreateDesc(b'TEXT', x.which)
Jack Jansen0ae32202003-04-09 13:25:43 +0000127 if hasattr(x, 'want'):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000128 return AE.AECreateDesc(b'TEXT', x.want)
129 return AE.AECreateDesc(b'TEXT', repr(x)) # Copout
Jack Jansend0fc42f2001-08-19 22:05:06 +0000130
Jack Jansen8b777672002-08-07 14:49:00 +0000131def unpack(desc, formodulename=""):
Jack Jansen0ae32202003-04-09 13:25:43 +0000132 """Unpack an AE descriptor to a python object"""
133 t = desc.type
Tim Peters182b5ac2004-07-18 06:16:08 +0000134
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000135 if b2i(t) in unpacker_coercions:
136 desc = desc.AECoerceDesc(unpacker_coercions[b2i(t)])
Jack Jansen0ae32202003-04-09 13:25:43 +0000137 t = desc.type # This is a guess by Jack....
Tim Peters182b5ac2004-07-18 06:16:08 +0000138
Jack Jansen0ae32202003-04-09 13:25:43 +0000139 if t == typeAEList:
140 l = []
141 for i in range(desc.AECountItems()):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000142 keyword, item = desc.AEGetNthDesc(i+1, b'****')
Jack Jansen0ae32202003-04-09 13:25:43 +0000143 l.append(unpack(item, formodulename))
144 return l
145 if t == typeAERecord:
146 d = {}
147 for i in range(desc.AECountItems()):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000148 keyword, item = desc.AEGetNthDesc(i+1, b'****')
149 d[b2i(keyword)] = unpack(item, formodulename)
Jack Jansen0ae32202003-04-09 13:25:43 +0000150 return d
151 if t == typeAEText:
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000152 record = desc.AECoerceDesc(b'reco')
Jack Jansen0ae32202003-04-09 13:25:43 +0000153 return mkaetext(unpack(record, formodulename))
154 if t == typeAlias:
155 return Carbon.File.Alias(rawdata=desc.data)
156 # typeAppleEvent returned as unknown
157 if t == typeBoolean:
158 return struct.unpack('b', desc.data)[0]
159 if t == typeChar:
160 return desc.data
161 if t == typeUnicodeText:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000162 return str(desc.data, 'utf16')
Jack Jansen0ae32202003-04-09 13:25:43 +0000163 # typeColorTable coerced to typeAEList
164 # typeComp coerced to extended
165 # typeData returned as unknown
166 # typeDrawingArea coerced to typeAERecord
167 if t == typeEnumeration:
168 return mkenum(desc.data)
169 # typeEPS returned as unknown
170 if t == typeFalse:
171 return 0
172 if t == typeFloat:
173 data = desc.data
174 return struct.unpack('d', data)[0]
175 if t == typeFSS:
176 return Carbon.File.FSSpec(rawdata=desc.data)
177 if t == typeFSRef:
178 return Carbon.File.FSRef(rawdata=desc.data)
179 if t == typeInsertionLoc:
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000180 record = desc.AECoerceDesc(b'reco')
Jack Jansen0ae32202003-04-09 13:25:43 +0000181 return mkinsertionloc(unpack(record, formodulename))
182 # typeInteger equal to typeLongInteger
183 if t == typeIntlText:
184 script, language = struct.unpack('hh', desc.data[:4])
185 return aetypes.IntlText(script, language, desc.data[4:])
186 if t == typeIntlWritingCode:
187 script, language = struct.unpack('hh', desc.data)
188 return aetypes.IntlWritingCode(script, language)
189 if t == typeKeyword:
190 return mkkeyword(desc.data)
191 if t == typeLongInteger:
192 return struct.unpack('l', desc.data)[0]
193 if t == typeLongDateTime:
194 a, b = struct.unpack('lL', desc.data)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000195 return (int(a) << 32) + b
Jack Jansen0ae32202003-04-09 13:25:43 +0000196 if t == typeNull:
197 return None
198 if t == typeMagnitude:
199 v = struct.unpack('l', desc.data)
200 if v < 0:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000201 v = 0x100000000 + v
Jack Jansen0ae32202003-04-09 13:25:43 +0000202 return v
203 if t == typeObjectSpecifier:
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000204 record = desc.AECoerceDesc(b'reco')
Jack Jansen0ae32202003-04-09 13:25:43 +0000205 # If we have been told the name of the module we are unpacking aedescs for,
206 # we can attempt to create the right type of python object from that module.
207 if formodulename:
208 return mkobjectfrommodule(unpack(record, formodulename), formodulename)
209 return mkobject(unpack(record, formodulename))
210 # typePict returned as unknown
211 # typePixelMap coerced to typeAERecord
212 # typePixelMapMinus returned as unknown
213 # typeProcessSerialNumber returned as unknown
214 if t == typeQDPoint:
215 v, h = struct.unpack('hh', desc.data)
216 return aetypes.QDPoint(v, h)
217 if t == typeQDRectangle:
218 v0, h0, v1, h1 = struct.unpack('hhhh', desc.data)
219 return aetypes.QDRectangle(v0, h0, v1, h1)
220 if t == typeRGBColor:
221 r, g, b = struct.unpack('hhh', desc.data)
222 return aetypes.RGBColor(r, g, b)
223 # typeRotation coerced to typeAERecord
224 # typeScrapStyles returned as unknown
225 # typeSessionID returned as unknown
226 if t == typeShortFloat:
227 return struct.unpack('f', desc.data)[0]
228 if t == typeShortInteger:
229 return struct.unpack('h', desc.data)[0]
230 # typeSMFloat identical to typeShortFloat
231 # typeSMInt indetical to typeShortInt
232 # typeStyledText coerced to typeAERecord
233 if t == typeTargetID:
234 return mktargetid(desc.data)
235 # typeTextStyles coerced to typeAERecord
236 # typeTIFF returned as unknown
237 if t == typeTrue:
238 return 1
239 if t == typeType:
240 return mktype(desc.data, formodulename)
241 #
242 # The following are special
243 #
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000244 if t == b'rang':
245 record = desc.AECoerceDesc(b'reco')
Jack Jansen0ae32202003-04-09 13:25:43 +0000246 return mkrange(unpack(record, formodulename))
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000247 if t == b'cmpd':
248 record = desc.AECoerceDesc(b'reco')
Jack Jansen0ae32202003-04-09 13:25:43 +0000249 return mkcomparison(unpack(record, formodulename))
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000250 if t == b'logi':
251 record = desc.AECoerceDesc(b'reco')
Jack Jansen0ae32202003-04-09 13:25:43 +0000252 return mklogical(unpack(record, formodulename))
253 return mkunknown(desc.type, desc.data)
Tim Peters182b5ac2004-07-18 06:16:08 +0000254
Jack Jansend0fc42f2001-08-19 22:05:06 +0000255def coerce(data, egdata):
Jack Jansen0ae32202003-04-09 13:25:43 +0000256 """Coerce a python object to another type using the AE coercers"""
257 pdata = pack(data)
258 pegdata = pack(egdata)
259 pdata = pdata.AECoerceDesc(pegdata.type)
260 return unpack(pdata)
Jack Jansend0fc42f2001-08-19 22:05:06 +0000261
262#
263# Helper routines for unpack
264#
265def mktargetid(data):
Jack Jansen0ae32202003-04-09 13:25:43 +0000266 sessionID = getlong(data[:4])
267 name = mkppcportrec(data[4:4+72])
268 location = mklocationnamerec(data[76:76+36])
269 rcvrName = mkppcportrec(data[112:112+72])
270 return sessionID, name, location, rcvrName
Jack Jansend0fc42f2001-08-19 22:05:06 +0000271
272def mkppcportrec(rec):
Jack Jansen0ae32202003-04-09 13:25:43 +0000273 namescript = getword(rec[:2])
274 name = getpstr(rec[2:2+33])
275 portkind = getword(rec[36:38])
276 if portkind == 1:
277 ctor = rec[38:42]
278 type = rec[42:46]
279 identity = (ctor, type)
280 else:
281 identity = getpstr(rec[38:38+33])
282 return namescript, name, portkind, identity
Jack Jansend0fc42f2001-08-19 22:05:06 +0000283
284def mklocationnamerec(rec):
Jack Jansen0ae32202003-04-09 13:25:43 +0000285 kind = getword(rec[:2])
286 stuff = rec[2:]
287 if kind == 0: stuff = None
288 if kind == 2: stuff = getpstr(stuff)
289 return kind, stuff
Jack Jansend0fc42f2001-08-19 22:05:06 +0000290
291def mkunknown(type, data):
Jack Jansen0ae32202003-04-09 13:25:43 +0000292 return aetypes.Unknown(type, data)
Jack Jansend0fc42f2001-08-19 22:05:06 +0000293
294def getpstr(s):
Jack Jansen0ae32202003-04-09 13:25:43 +0000295 return s[1:1+ord(s[0])]
Jack Jansend0fc42f2001-08-19 22:05:06 +0000296
297def getlong(s):
Jack Jansen0ae32202003-04-09 13:25:43 +0000298 return (ord(s[0])<<24) | (ord(s[1])<<16) | (ord(s[2])<<8) | ord(s[3])
Jack Jansend0fc42f2001-08-19 22:05:06 +0000299
300def getword(s):
Jack Jansen0ae32202003-04-09 13:25:43 +0000301 return (ord(s[0])<<8) | (ord(s[1])<<0)
Jack Jansend0fc42f2001-08-19 22:05:06 +0000302
303def mkkeyword(keyword):
Jack Jansen0ae32202003-04-09 13:25:43 +0000304 return aetypes.Keyword(keyword)
Jack Jansend0fc42f2001-08-19 22:05:06 +0000305
306def mkrange(dict):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000307 return aetypes.Range(dict[b2i(b'star')], dict[b2i(b'stop')])
Jack Jansend0fc42f2001-08-19 22:05:06 +0000308
309def mkcomparison(dict):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000310 return aetypes.Comparison(dict[b2i(b'obj1')],
311 dict[b2i(b'relo')].enum,
312 dict[b2i(b'obj2')])
Jack Jansend0fc42f2001-08-19 22:05:06 +0000313
314def mklogical(dict):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000315 return aetypes.Logical(dict[b2i(b'logc')], dict[b2i(b'term')])
Jack Jansend0fc42f2001-08-19 22:05:06 +0000316
317def mkstyledtext(dict):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000318 return aetypes.StyledText(dict[b2i(b'ksty')], dict[b2i(b'ktxt')])
Tim Peters182b5ac2004-07-18 06:16:08 +0000319
Jack Jansend0fc42f2001-08-19 22:05:06 +0000320def mkaetext(dict):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000321 return aetypes.AEText(dict[b2i(keyAEScriptTag)],
322 dict[b2i(keyAEStyles)],
323 dict[b2i(keyAEText)])
Tim Peters182b5ac2004-07-18 06:16:08 +0000324
Jack Jansend0fc42f2001-08-19 22:05:06 +0000325def mkinsertionloc(dict):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000326 return aetypes.InsertionLoc(dict[b2i(keyAEObject)],
327 dict[b2i(keyAEPosition)])
Jack Jansend0fc42f2001-08-19 22:05:06 +0000328
329def mkobject(dict):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000330 want = dict[b2i(b'want')].type
331 form = dict[b2i(b'form')].enum
332 seld = dict[b2i(b'seld')]
333 fr = dict[b2i(b'from')]
334 if form in (b'name', b'indx', b'rang', b'test'):
335 if want == b'text': return aetypes.Text(seld, fr)
336 if want == b'cha ': return aetypes.Character(seld, fr)
337 if want == b'cwor': return aetypes.Word(seld, fr)
338 if want == b'clin': return aetypes.Line(seld, fr)
339 if want == b'cpar': return aetypes.Paragraph(seld, fr)
340 if want == b'cwin': return aetypes.Window(seld, fr)
341 if want == b'docu': return aetypes.Document(seld, fr)
342 if want == b'file': return aetypes.File(seld, fr)
343 if want == b'cins': return aetypes.InsertionPoint(seld, fr)
344 if want == b'prop' and form == b'prop' and aetypes.IsType(seld):
Jack Jansen0ae32202003-04-09 13:25:43 +0000345 return aetypes.Property(seld.type, fr)
346 return aetypes.ObjectSpecifier(want, form, seld, fr)
Jack Jansend0fc42f2001-08-19 22:05:06 +0000347
Jack Jansen8b777672002-08-07 14:49:00 +0000348# Note by Jack: I'm not 100% sure of the following code. This was
349# provided by Donovan Preston, but I wonder whether the assignment
350# to __class__ is safe. Moreover, shouldn't there be a better
351# initializer for the classes in the suites?
352def mkobjectfrommodule(dict, modulename):
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000353 if (isinstance(dict[b2i(b'want')], type) and
354 issubclass(dict[b2i(b'want')], ObjectSpecifier)):
Jack Jansen0ae32202003-04-09 13:25:43 +0000355 # The type has already been converted to Python. Convert back:-(
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000356 classtype = dict[b2i(b'want')]
357 dict[b2i(b'want')] = aetypes.mktype(classtype.want)
358 want = dict[b2i(b'want')].type
Jack Jansen0ae32202003-04-09 13:25:43 +0000359 module = __import__(modulename)
360 codenamemapper = module._classdeclarations
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000361 classtype = codenamemapper.get(b2i(want), None)
Jack Jansen0ae32202003-04-09 13:25:43 +0000362 newobj = mkobject(dict)
363 if classtype:
364 assert issubclass(classtype, ObjectSpecifier)
365 newobj.__class__ = classtype
366 return newobj
Tim Peters182b5ac2004-07-18 06:16:08 +0000367
Jack Jansenfc710262003-03-31 13:32:59 +0000368def mktype(typecode, modulename=None):
Jack Jansen0ae32202003-04-09 13:25:43 +0000369 if modulename:
370 module = __import__(modulename)
371 codenamemapper = module._classdeclarations
Guido van Rossumf7a94e42007-07-27 04:41:00 +0000372 classtype = codenamemapper.get(b2i(typecode), None)
Jack Jansen0ae32202003-04-09 13:25:43 +0000373 if classtype:
374 return classtype
375 return aetypes.mktype(typecode)