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