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