blob: 9be242cf9d76f9b13a9c58ccb51fe917f16e8425 [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 Jansend0fc42f2001-08-19 22:05:06 +000016import types
Jack Jansend0fc42f2001-08-19 22:05:06 +000017from types import *
Jack Jansen5a6fdcd2001-08-25 12:15:04 +000018from Carbon import AE
19from Carbon.AppleEvents import *
Jack Jansend0fc42f2001-08-19 22:05:06 +000020import MacOS
Jack Jansen2b88dec2003-01-28 23:53:40 +000021import Carbon.File
Jack Jansend0fc42f2001-08-19 22:05:06 +000022import StringIO
23import aetypes
Jack Jansenfc710262003-03-31 13:32:59 +000024from aetypes import mkenum, ObjectSpecifier
Jack Jansen8b777672002-08-07 14:49:00 +000025import os
Jack Jansend0fc42f2001-08-19 22:05:06 +000026
27# These ones seem to be missing from AppleEvents
28# (they're in AERegistry.h)
29
30#typeColorTable = 'clrt'
31#typeDrawingArea = 'cdrw'
32#typePixelMap = 'cpix'
33#typePixelMapMinus = 'tpmm'
34#typeRotation = 'trot'
35#typeTextStyles = 'tsty'
36#typeStyledText = 'STXT'
37#typeAEText = 'tTXT'
38#typeEnumeration = 'enum'
39
40#
41# Some AE types are immedeately coerced into something
42# we like better (and which is equivalent)
43#
44unpacker_coercions = {
Jack Jansen0ae32202003-04-09 13:25:43 +000045 typeComp : typeFloat,
46 typeColorTable : typeAEList,
47 typeDrawingArea : typeAERecord,
48 typeFixed : typeFloat,
49 typeExtended : typeFloat,
50 typePixelMap : typeAERecord,
51 typeRotation : typeAERecord,
52 typeStyledText : typeAERecord,
53 typeTextStyles : typeAERecord,
Jack Jansend0fc42f2001-08-19 22:05:06 +000054};
55
56#
57# Some python types we need in the packer:
58#
Jack Jansenad5dcaf2002-03-30 23:44:58 +000059AEDescType = AE.AEDescType
Jack Jansen2b88dec2003-01-28 23:53:40 +000060FSSType = Carbon.File.FSSpecType
61FSRefType = Carbon.File.FSRefType
62AliasType = Carbon.File.AliasType
Jack Jansend0fc42f2001-08-19 22:05:06 +000063
Jack Jansen8b777672002-08-07 14:49:00 +000064def packkey(ae, key, value):
Jack Jansen0ae32202003-04-09 13:25:43 +000065 if hasattr(key, 'which'):
66 keystr = key.which
67 elif hasattr(key, 'want'):
68 keystr = key.want
69 else:
70 keystr = key
71 ae.AEPutParamDesc(keystr, pack(value))
Jack Jansen8b777672002-08-07 14:49:00 +000072
Jack Jansend0fc42f2001-08-19 22:05:06 +000073def pack(x, forcetype = None):
Jack Jansen0ae32202003-04-09 13:25:43 +000074 """Pack a python object into an AE descriptor"""
Tim Peters182b5ac2004-07-18 06:16:08 +000075
Jack Jansen0ae32202003-04-09 13:25:43 +000076 if forcetype:
77 if type(x) is StringType:
78 return AE.AECreateDesc(forcetype, x)
79 else:
80 return pack(x).AECoerceDesc(forcetype)
Tim Peters182b5ac2004-07-18 06:16:08 +000081
Jack Jansen0ae32202003-04-09 13:25:43 +000082 if x == None:
83 return AE.AECreateDesc('null', '')
Tim Peters182b5ac2004-07-18 06:16:08 +000084
Jack Jansen0ae32202003-04-09 13:25:43 +000085 if isinstance(x, AEDescType):
86 return x
87 if isinstance(x, FSSType):
88 return AE.AECreateDesc('fss ', x.data)
89 if isinstance(x, FSRefType):
90 return AE.AECreateDesc('fsrf', x.data)
91 if isinstance(x, AliasType):
92 return AE.AECreateDesc('alis', x.data)
93 if isinstance(x, IntType):
94 return AE.AECreateDesc('long', struct.pack('l', x))
95 if isinstance(x, FloatType):
96 return AE.AECreateDesc('doub', struct.pack('d', x))
97 if isinstance(x, StringType):
98 return AE.AECreateDesc('TEXT', x)
99 if isinstance(x, UnicodeType):
100 data = x.encode('utf16')
101 if data[:2] == '\xfe\xff':
102 data = data[2:]
103 return AE.AECreateDesc('utxt', data)
104 if isinstance(x, ListType):
105 list = AE.AECreateList('', 0)
106 for item in x:
107 list.AEPutDesc(0, pack(item))
108 return list
109 if isinstance(x, DictionaryType):
110 record = AE.AECreateList('', 1)
111 for key, value in x.items():
112 packkey(record, key, value)
113 #record.AEPutParamDesc(key, pack(value))
114 return record
115 if type(x) == types.ClassType and issubclass(x, ObjectSpecifier):
116 # Note: we are getting a class object here, not an instance
117 return AE.AECreateDesc('type', x.want)
118 if hasattr(x, '__aepack__'):
119 return x.__aepack__()
120 if hasattr(x, 'which'):
121 return AE.AECreateDesc('TEXT', x.which)
122 if hasattr(x, 'want'):
123 return AE.AECreateDesc('TEXT', x.want)
124 return AE.AECreateDesc('TEXT', repr(x)) # Copout
Jack Jansend0fc42f2001-08-19 22:05:06 +0000125
Jack Jansen8b777672002-08-07 14:49:00 +0000126def unpack(desc, formodulename=""):
Jack Jansen0ae32202003-04-09 13:25:43 +0000127 """Unpack an AE descriptor to a python object"""
128 t = desc.type
Tim Peters182b5ac2004-07-18 06:16:08 +0000129
Neal Norwitzf1a69c12006-08-20 16:25:10 +0000130 if t in unpacker_coercions:
Jack Jansen0ae32202003-04-09 13:25:43 +0000131 desc = desc.AECoerceDesc(unpacker_coercions[t])
132 t = desc.type # This is a guess by Jack....
Tim Peters182b5ac2004-07-18 06:16:08 +0000133
Jack Jansen0ae32202003-04-09 13:25:43 +0000134 if t == typeAEList:
135 l = []
136 for i in range(desc.AECountItems()):
137 keyword, item = desc.AEGetNthDesc(i+1, '****')
138 l.append(unpack(item, formodulename))
139 return l
140 if t == typeAERecord:
141 d = {}
142 for i in range(desc.AECountItems()):
143 keyword, item = desc.AEGetNthDesc(i+1, '****')
144 d[keyword] = unpack(item, formodulename)
145 return d
146 if t == typeAEText:
147 record = desc.AECoerceDesc('reco')
148 return mkaetext(unpack(record, formodulename))
149 if t == typeAlias:
150 return Carbon.File.Alias(rawdata=desc.data)
151 # typeAppleEvent returned as unknown
152 if t == typeBoolean:
153 return struct.unpack('b', desc.data)[0]
154 if t == typeChar:
155 return desc.data
156 if t == typeUnicodeText:
157 return unicode(desc.data, 'utf16')
158 # typeColorTable coerced to typeAEList
159 # typeComp coerced to extended
160 # typeData returned as unknown
161 # typeDrawingArea coerced to typeAERecord
162 if t == typeEnumeration:
163 return mkenum(desc.data)
164 # typeEPS returned as unknown
165 if t == typeFalse:
166 return 0
167 if t == typeFloat:
168 data = desc.data
169 return struct.unpack('d', data)[0]
170 if t == typeFSS:
171 return Carbon.File.FSSpec(rawdata=desc.data)
172 if t == typeFSRef:
173 return Carbon.File.FSRef(rawdata=desc.data)
174 if t == typeInsertionLoc:
175 record = desc.AECoerceDesc('reco')
176 return mkinsertionloc(unpack(record, formodulename))
177 # typeInteger equal to typeLongInteger
178 if t == typeIntlText:
179 script, language = struct.unpack('hh', desc.data[:4])
180 return aetypes.IntlText(script, language, desc.data[4:])
181 if t == typeIntlWritingCode:
182 script, language = struct.unpack('hh', desc.data)
183 return aetypes.IntlWritingCode(script, language)
184 if t == typeKeyword:
185 return mkkeyword(desc.data)
186 if t == typeLongInteger:
187 return struct.unpack('l', desc.data)[0]
188 if t == typeLongDateTime:
189 a, b = struct.unpack('lL', desc.data)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000190 return (int(a) << 32) + b
Jack Jansen0ae32202003-04-09 13:25:43 +0000191 if t == typeNull:
192 return None
193 if t == typeMagnitude:
194 v = struct.unpack('l', desc.data)
195 if v < 0:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000196 v = 0x100000000 + v
Jack Jansen0ae32202003-04-09 13:25:43 +0000197 return v
198 if t == typeObjectSpecifier:
199 record = desc.AECoerceDesc('reco')
200 # If we have been told the name of the module we are unpacking aedescs for,
201 # we can attempt to create the right type of python object from that module.
202 if formodulename:
203 return mkobjectfrommodule(unpack(record, formodulename), formodulename)
204 return mkobject(unpack(record, formodulename))
205 # typePict returned as unknown
206 # typePixelMap coerced to typeAERecord
207 # typePixelMapMinus returned as unknown
208 # typeProcessSerialNumber returned as unknown
209 if t == typeQDPoint:
210 v, h = struct.unpack('hh', desc.data)
211 return aetypes.QDPoint(v, h)
212 if t == typeQDRectangle:
213 v0, h0, v1, h1 = struct.unpack('hhhh', desc.data)
214 return aetypes.QDRectangle(v0, h0, v1, h1)
215 if t == typeRGBColor:
216 r, g, b = struct.unpack('hhh', desc.data)
217 return aetypes.RGBColor(r, g, b)
218 # typeRotation coerced to typeAERecord
219 # typeScrapStyles returned as unknown
220 # typeSessionID returned as unknown
221 if t == typeShortFloat:
222 return struct.unpack('f', desc.data)[0]
223 if t == typeShortInteger:
224 return struct.unpack('h', desc.data)[0]
225 # typeSMFloat identical to typeShortFloat
226 # typeSMInt indetical to typeShortInt
227 # typeStyledText coerced to typeAERecord
228 if t == typeTargetID:
229 return mktargetid(desc.data)
230 # typeTextStyles coerced to typeAERecord
231 # typeTIFF returned as unknown
232 if t == typeTrue:
233 return 1
234 if t == typeType:
235 return mktype(desc.data, formodulename)
236 #
237 # The following are special
238 #
239 if t == 'rang':
240 record = desc.AECoerceDesc('reco')
241 return mkrange(unpack(record, formodulename))
242 if t == 'cmpd':
243 record = desc.AECoerceDesc('reco')
244 return mkcomparison(unpack(record, formodulename))
245 if t == 'logi':
246 record = desc.AECoerceDesc('reco')
247 return mklogical(unpack(record, formodulename))
248 return mkunknown(desc.type, desc.data)
Tim Peters182b5ac2004-07-18 06:16:08 +0000249
Jack Jansend0fc42f2001-08-19 22:05:06 +0000250def coerce(data, egdata):
Jack Jansen0ae32202003-04-09 13:25:43 +0000251 """Coerce a python object to another type using the AE coercers"""
252 pdata = pack(data)
253 pegdata = pack(egdata)
254 pdata = pdata.AECoerceDesc(pegdata.type)
255 return unpack(pdata)
Jack Jansend0fc42f2001-08-19 22:05:06 +0000256
257#
258# Helper routines for unpack
259#
260def mktargetid(data):
Jack Jansen0ae32202003-04-09 13:25:43 +0000261 sessionID = getlong(data[:4])
262 name = mkppcportrec(data[4:4+72])
263 location = mklocationnamerec(data[76:76+36])
264 rcvrName = mkppcportrec(data[112:112+72])
265 return sessionID, name, location, rcvrName
Jack Jansend0fc42f2001-08-19 22:05:06 +0000266
267def mkppcportrec(rec):
Jack Jansen0ae32202003-04-09 13:25:43 +0000268 namescript = getword(rec[:2])
269 name = getpstr(rec[2:2+33])
270 portkind = getword(rec[36:38])
271 if portkind == 1:
272 ctor = rec[38:42]
273 type = rec[42:46]
274 identity = (ctor, type)
275 else:
276 identity = getpstr(rec[38:38+33])
277 return namescript, name, portkind, identity
Jack Jansend0fc42f2001-08-19 22:05:06 +0000278
279def mklocationnamerec(rec):
Jack Jansen0ae32202003-04-09 13:25:43 +0000280 kind = getword(rec[:2])
281 stuff = rec[2:]
282 if kind == 0: stuff = None
283 if kind == 2: stuff = getpstr(stuff)
284 return kind, stuff
Jack Jansend0fc42f2001-08-19 22:05:06 +0000285
286def mkunknown(type, data):
Jack Jansen0ae32202003-04-09 13:25:43 +0000287 return aetypes.Unknown(type, data)
Jack Jansend0fc42f2001-08-19 22:05:06 +0000288
289def getpstr(s):
Jack Jansen0ae32202003-04-09 13:25:43 +0000290 return s[1:1+ord(s[0])]
Jack Jansend0fc42f2001-08-19 22:05:06 +0000291
292def getlong(s):
Jack Jansen0ae32202003-04-09 13:25:43 +0000293 return (ord(s[0])<<24) | (ord(s[1])<<16) | (ord(s[2])<<8) | ord(s[3])
Jack Jansend0fc42f2001-08-19 22:05:06 +0000294
295def getword(s):
Jack Jansen0ae32202003-04-09 13:25:43 +0000296 return (ord(s[0])<<8) | (ord(s[1])<<0)
Jack Jansend0fc42f2001-08-19 22:05:06 +0000297
298def mkkeyword(keyword):
Jack Jansen0ae32202003-04-09 13:25:43 +0000299 return aetypes.Keyword(keyword)
Jack Jansend0fc42f2001-08-19 22:05:06 +0000300
301def mkrange(dict):
Jack Jansen0ae32202003-04-09 13:25:43 +0000302 return aetypes.Range(dict['star'], dict['stop'])
Jack Jansend0fc42f2001-08-19 22:05:06 +0000303
304def mkcomparison(dict):
Jack Jansen0ae32202003-04-09 13:25:43 +0000305 return aetypes.Comparison(dict['obj1'], dict['relo'].enum, dict['obj2'])
Jack Jansend0fc42f2001-08-19 22:05:06 +0000306
307def mklogical(dict):
Jack Jansen0ae32202003-04-09 13:25:43 +0000308 return aetypes.Logical(dict['logc'], dict['term'])
Jack Jansend0fc42f2001-08-19 22:05:06 +0000309
310def mkstyledtext(dict):
Jack Jansen0ae32202003-04-09 13:25:43 +0000311 return aetypes.StyledText(dict['ksty'], dict['ktxt'])
Tim Peters182b5ac2004-07-18 06:16:08 +0000312
Jack Jansend0fc42f2001-08-19 22:05:06 +0000313def mkaetext(dict):
Jack Jansen0ae32202003-04-09 13:25:43 +0000314 return aetypes.AEText(dict[keyAEScriptTag], dict[keyAEStyles], dict[keyAEText])
Tim Peters182b5ac2004-07-18 06:16:08 +0000315
Jack Jansend0fc42f2001-08-19 22:05:06 +0000316def mkinsertionloc(dict):
Jack Jansen0ae32202003-04-09 13:25:43 +0000317 return aetypes.InsertionLoc(dict[keyAEObject], dict[keyAEPosition])
Jack Jansend0fc42f2001-08-19 22:05:06 +0000318
319def mkobject(dict):
Jack Jansen0ae32202003-04-09 13:25:43 +0000320 want = dict['want'].type
321 form = dict['form'].enum
322 seld = dict['seld']
323 fr = dict['from']
324 if form in ('name', 'indx', 'rang', 'test'):
325 if want == 'text': return aetypes.Text(seld, fr)
326 if want == 'cha ': return aetypes.Character(seld, fr)
327 if want == 'cwor': return aetypes.Word(seld, fr)
328 if want == 'clin': return aetypes.Line(seld, fr)
329 if want == 'cpar': return aetypes.Paragraph(seld, fr)
330 if want == 'cwin': return aetypes.Window(seld, fr)
331 if want == 'docu': return aetypes.Document(seld, fr)
332 if want == 'file': return aetypes.File(seld, fr)
333 if want == 'cins': return aetypes.InsertionPoint(seld, fr)
334 if want == 'prop' and form == 'prop' and aetypes.IsType(seld):
335 return aetypes.Property(seld.type, fr)
336 return aetypes.ObjectSpecifier(want, form, seld, fr)
Jack Jansend0fc42f2001-08-19 22:05:06 +0000337
Jack Jansen8b777672002-08-07 14:49:00 +0000338# Note by Jack: I'm not 100% sure of the following code. This was
339# provided by Donovan Preston, but I wonder whether the assignment
340# to __class__ is safe. Moreover, shouldn't there be a better
341# initializer for the classes in the suites?
342def mkobjectfrommodule(dict, modulename):
Jack Jansen0ae32202003-04-09 13:25:43 +0000343 if type(dict['want']) == types.ClassType and issubclass(dict['want'], ObjectSpecifier):
344 # The type has already been converted to Python. Convert back:-(
345 classtype = dict['want']
346 dict['want'] = aetypes.mktype(classtype.want)
347 want = dict['want'].type
348 module = __import__(modulename)
349 codenamemapper = module._classdeclarations
350 classtype = codenamemapper.get(want, None)
351 newobj = mkobject(dict)
352 if classtype:
353 assert issubclass(classtype, ObjectSpecifier)
354 newobj.__class__ = classtype
355 return newobj
Tim Peters182b5ac2004-07-18 06:16:08 +0000356
Jack Jansenfc710262003-03-31 13:32:59 +0000357def mktype(typecode, modulename=None):
Jack Jansen0ae32202003-04-09 13:25:43 +0000358 if modulename:
359 module = __import__(modulename)
360 codenamemapper = module._classdeclarations
361 classtype = codenamemapper.get(typecode, None)
362 if classtype:
363 return classtype
364 return aetypes.mktype(typecode)