blob: 17a7e7050de2f23de91718a881ad8b7104930bf4 [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
16import string
17import types
18from string import strip
19from types import *
Jack Jansen5a6fdcd2001-08-25 12:15:04 +000020from Carbon import AE
21from Carbon.AppleEvents import *
Jack Jansend0fc42f2001-08-19 22:05:06 +000022import MacOS
Jack Jansen2b88dec2003-01-28 23:53:40 +000023import Carbon.File
Jack Jansend0fc42f2001-08-19 22:05:06 +000024import StringIO
25import aetypes
26from aetypes import mkenum, mktype
Jack Jansen8b777672002-08-07 14:49:00 +000027import os
Jack Jansend0fc42f2001-08-19 22:05:06 +000028
29# These ones seem to be missing from AppleEvents
30# (they're in AERegistry.h)
31
32#typeColorTable = 'clrt'
33#typeDrawingArea = 'cdrw'
34#typePixelMap = 'cpix'
35#typePixelMapMinus = 'tpmm'
36#typeRotation = 'trot'
37#typeTextStyles = 'tsty'
38#typeStyledText = 'STXT'
39#typeAEText = 'tTXT'
40#typeEnumeration = 'enum'
41
42#
43# Some AE types are immedeately coerced into something
44# we like better (and which is equivalent)
45#
46unpacker_coercions = {
47 typeComp : typeFloat,
48 typeColorTable : typeAEList,
49 typeDrawingArea : typeAERecord,
50 typeFixed : typeFloat,
51 typeExtended : typeFloat,
52 typePixelMap : typeAERecord,
53 typeRotation : typeAERecord,
54 typeStyledText : typeAERecord,
55 typeTextStyles : typeAERecord,
56};
57
58#
59# Some python types we need in the packer:
60#
Jack Jansenad5dcaf2002-03-30 23:44:58 +000061AEDescType = AE.AEDescType
Jack Jansen2b88dec2003-01-28 23:53:40 +000062FSSType = Carbon.File.FSSpecType
63FSRefType = Carbon.File.FSRefType
64AliasType = Carbon.File.AliasType
Jack Jansend0fc42f2001-08-19 22:05:06 +000065
Jack Jansen8b777672002-08-07 14:49:00 +000066def packkey(ae, key, value):
67 if hasattr(key, 'which'):
68 keystr = key.which
69 elif hasattr(key, 'want'):
70 keystr = key.want
71 else:
72 keystr = key
73 ae.AEPutParamDesc(keystr, pack(value))
74
Jack Jansend0fc42f2001-08-19 22:05:06 +000075def pack(x, forcetype = None):
76 """Pack a python object into an AE descriptor"""
77
78 if forcetype:
79 if type(x) is StringType:
80 return AE.AECreateDesc(forcetype, x)
81 else:
82 return pack(x).AECoerceDesc(forcetype)
83
84 if x == None:
85 return AE.AECreateDesc('null', '')
86
Jack Jansen2b88dec2003-01-28 23:53:40 +000087 if isinstance(x, AEDescType):
Jack Jansend0fc42f2001-08-19 22:05:06 +000088 return x
Jack Jansen2b88dec2003-01-28 23:53:40 +000089 if isinstance(x, FSSType):
Jack Jansend0fc42f2001-08-19 22:05:06 +000090 return AE.AECreateDesc('fss ', x.data)
Jack Jansenf59c6fa2003-02-12 15:37:26 +000091 if isinstance(x, FSRefType):
92 return AE.AECreateDesc('fsrf', x.data)
Jack Jansen2b88dec2003-01-28 23:53:40 +000093 if isinstance(x, AliasType):
Jack Jansend0fc42f2001-08-19 22:05:06 +000094 return AE.AECreateDesc('alis', x.data)
Jack Jansen2b88dec2003-01-28 23:53:40 +000095 if isinstance(x, IntType):
Jack Jansend0fc42f2001-08-19 22:05:06 +000096 return AE.AECreateDesc('long', struct.pack('l', x))
Jack Jansen2b88dec2003-01-28 23:53:40 +000097 if isinstance(x, FloatType):
Jack Jansend0fc42f2001-08-19 22:05:06 +000098 return AE.AECreateDesc('doub', struct.pack('d', x))
Jack Jansen2b88dec2003-01-28 23:53:40 +000099 if isinstance(x, StringType):
Jack Jansend0fc42f2001-08-19 22:05:06 +0000100 return AE.AECreateDesc('TEXT', x)
Jack Jansen2b88dec2003-01-28 23:53:40 +0000101 if isinstance(x, UnicodeType):
Jack Jansen5bb8f782002-02-05 21:24:47 +0000102 data = t.encode('utf16')
103 if data[:2] == '\xfe\xff':
104 data = data[2:]
105 return AE.AECreateDesc('utxt', data)
Jack Jansen2b88dec2003-01-28 23:53:40 +0000106 if isinstance(x, ListType):
Jack Jansend0fc42f2001-08-19 22:05:06 +0000107 list = AE.AECreateList('', 0)
108 for item in x:
109 list.AEPutDesc(0, pack(item))
110 return list
Jack Jansen2b88dec2003-01-28 23:53:40 +0000111 if isinstance(x, DictionaryType):
Jack Jansend0fc42f2001-08-19 22:05:06 +0000112 record = AE.AECreateList('', 1)
113 for key, value in x.items():
Jack Jansen8b777672002-08-07 14:49:00 +0000114 packkey(record, key, value)
115 #record.AEPutParamDesc(key, pack(value))
Jack Jansend0fc42f2001-08-19 22:05:06 +0000116 return record
Jack Jansen2b88dec2003-01-28 23:53:40 +0000117 if hasattr(x, '__aepack__'):
Jack Jansend0fc42f2001-08-19 22:05:06 +0000118 return x.__aepack__()
Jack Jansen8b777672002-08-07 14:49:00 +0000119 if hasattr(x, 'which'):
120 return AE.AECreateDesc('TEXT', x.which)
121 if hasattr(x, 'want'):
122 return AE.AECreateDesc('TEXT', x.want)
Jack Jansend0fc42f2001-08-19 22:05:06 +0000123 return AE.AECreateDesc('TEXT', repr(x)) # Copout
124
Jack Jansen8b777672002-08-07 14:49:00 +0000125def unpack(desc, formodulename=""):
Jack Jansend0fc42f2001-08-19 22:05:06 +0000126 """Unpack an AE descriptor to a python object"""
127 t = desc.type
128
129 if unpacker_coercions.has_key(t):
130 desc = desc.AECoerceDesc(unpacker_coercions[t])
131 t = desc.type # This is a guess by Jack....
132
133 if t == typeAEList:
134 l = []
135 for i in range(desc.AECountItems()):
136 keyword, item = desc.AEGetNthDesc(i+1, '****')
Jack Jansen8b777672002-08-07 14:49:00 +0000137 l.append(unpack(item, formodulename))
Jack Jansend0fc42f2001-08-19 22:05:06 +0000138 return l
139 if t == typeAERecord:
140 d = {}
141 for i in range(desc.AECountItems()):
142 keyword, item = desc.AEGetNthDesc(i+1, '****')
Jack Jansen8b777672002-08-07 14:49:00 +0000143 d[keyword] = unpack(item, formodulename)
Jack Jansend0fc42f2001-08-19 22:05:06 +0000144 return d
145 if t == typeAEText:
146 record = desc.AECoerceDesc('reco')
Jack Jansen8b777672002-08-07 14:49:00 +0000147 return mkaetext(unpack(record, formodulename))
Jack Jansend0fc42f2001-08-19 22:05:06 +0000148 if t == typeAlias:
Jack Jansen2b88dec2003-01-28 23:53:40 +0000149 return Carbon.File.Alias(rawdata=desc.data)
Jack Jansend0fc42f2001-08-19 22:05:06 +0000150 # typeAppleEvent returned as unknown
151 if t == typeBoolean:
152 return struct.unpack('b', desc.data)[0]
153 if t == typeChar:
154 return desc.data
Jack Jansen5bb8f782002-02-05 21:24:47 +0000155 if t == typeUnicodeText:
156 return unicode(desc.data, 'utf16')
Jack Jansend0fc42f2001-08-19 22:05:06 +0000157 # typeColorTable coerced to typeAEList
158 # typeComp coerced to extended
159 # typeData returned as unknown
160 # typeDrawingArea coerced to typeAERecord
161 if t == typeEnumeration:
162 return mkenum(desc.data)
163 # typeEPS returned as unknown
164 if t == typeFalse:
165 return 0
166 if t == typeFloat:
167 data = desc.data
168 return struct.unpack('d', data)[0]
169 if t == typeFSS:
Jack Jansen2b88dec2003-01-28 23:53:40 +0000170 return Carbon.File.FSSpec(rawdata=desc.data)
Jack Jansenf59c6fa2003-02-12 15:37:26 +0000171 if t == typeFSRef:
172 return Carbon.File.FSRef(rawdata=desc.data)
Jack Jansend0fc42f2001-08-19 22:05:06 +0000173 if t == typeInsertionLoc:
174 record = desc.AECoerceDesc('reco')
Jack Jansen8b777672002-08-07 14:49:00 +0000175 return mkinsertionloc(unpack(record, formodulename))
Jack Jansend0fc42f2001-08-19 22:05:06 +0000176 # typeInteger equal to typeLongInteger
177 if t == typeIntlText:
178 script, language = struct.unpack('hh', desc.data[:4])
179 return aetypes.IntlText(script, language, desc.data[4:])
180 if t == typeIntlWritingCode:
181 script, language = struct.unpack('hh', desc.data)
182 return aetypes.IntlWritingCode(script, language)
183 if t == typeKeyword:
184 return mkkeyword(desc.data)
185 if t == typeLongInteger:
186 return struct.unpack('l', desc.data)[0]
187 if t == typeLongDateTime:
188 a, b = struct.unpack('lL', desc.data)
189 return (long(a) << 32) + b
190 if t == typeNull:
191 return None
192 if t == typeMagnitude:
193 v = struct.unpack('l', desc.data)
194 if v < 0:
195 v = 0x100000000L + v
196 return v
197 if t == typeObjectSpecifier:
198 record = desc.AECoerceDesc('reco')
Jack Jansen8b777672002-08-07 14:49:00 +0000199 # If we have been told the name of the module we are unpacking aedescs for,
200 # we can attempt to create the right type of python object from that module.
201 if formodulename:
202 return mkobjectfrommodule(unpack(record, formodulename), formodulename)
203 return mkobject(unpack(record, formodulename))
Jack Jansend0fc42f2001-08-19 22:05:06 +0000204 # typePict returned as unknown
205 # typePixelMap coerced to typeAERecord
206 # typePixelMapMinus returned as unknown
207 # typeProcessSerialNumber returned as unknown
208 if t == typeQDPoint:
209 v, h = struct.unpack('hh', desc.data)
210 return aetypes.QDPoint(v, h)
211 if t == typeQDRectangle:
212 v0, h0, v1, h1 = struct.unpack('hhhh', desc.data)
213 return aetypes.QDRectangle(v0, h0, v1, h1)
214 if t == typeRGBColor:
215 r, g, b = struct.unpack('hhh', desc.data)
216 return aetypes.RGBColor(r, g, b)
217 # typeRotation coerced to typeAERecord
218 # typeScrapStyles returned as unknown
219 # typeSessionID returned as unknown
220 if t == typeShortFloat:
221 return struct.unpack('f', desc.data)[0]
222 if t == typeShortInteger:
223 return struct.unpack('h', desc.data)[0]
224 # typeSMFloat identical to typeShortFloat
225 # typeSMInt indetical to typeShortInt
226 # typeStyledText coerced to typeAERecord
227 if t == typeTargetID:
228 return mktargetid(desc.data)
229 # typeTextStyles coerced to typeAERecord
230 # typeTIFF returned as unknown
231 if t == typeTrue:
232 return 1
233 if t == typeType:
234 return mktype(desc.data)
235 #
236 # The following are special
237 #
238 if t == 'rang':
239 record = desc.AECoerceDesc('reco')
Jack Jansen8b777672002-08-07 14:49:00 +0000240 return mkrange(unpack(record, formodulename))
Jack Jansend0fc42f2001-08-19 22:05:06 +0000241 if t == 'cmpd':
242 record = desc.AECoerceDesc('reco')
Jack Jansen8b777672002-08-07 14:49:00 +0000243 return mkcomparison(unpack(record, formodulename))
Jack Jansend0fc42f2001-08-19 22:05:06 +0000244 if t == 'logi':
245 record = desc.AECoerceDesc('reco')
Jack Jansen8b777672002-08-07 14:49:00 +0000246 return mklogical(unpack(record, formodulename))
Jack Jansend0fc42f2001-08-19 22:05:06 +0000247 return mkunknown(desc.type, desc.data)
248
249def coerce(data, egdata):
250 """Coerce a python object to another type using the AE coercers"""
251 pdata = pack(data)
252 pegdata = pack(egdata)
253 pdata = pdata.AECoerceDesc(pegdata.type)
254 return unpack(pdata)
255
256#
257# Helper routines for unpack
258#
259def mktargetid(data):
260 sessionID = getlong(data[:4])
261 name = mkppcportrec(data[4:4+72])
262 location = mklocationnamerec(data[76:76+36])
263 rcvrName = mkppcportrec(data[112:112+72])
264 return sessionID, name, location, rcvrName
265
266def mkppcportrec(rec):
267 namescript = getword(rec[:2])
268 name = getpstr(rec[2:2+33])
269 portkind = getword(rec[36:38])
270 if portkind == 1:
271 ctor = rec[38:42]
272 type = rec[42:46]
273 identity = (ctor, type)
274 else:
275 identity = getpstr(rec[38:38+33])
276 return namescript, name, portkind, identity
277
278def mklocationnamerec(rec):
279 kind = getword(rec[:2])
280 stuff = rec[2:]
281 if kind == 0: stuff = None
282 if kind == 2: stuff = getpstr(stuff)
283 return kind, stuff
284
285def mkunknown(type, data):
286 return aetypes.Unknown(type, data)
287
288def getpstr(s):
289 return s[1:1+ord(s[0])]
290
291def getlong(s):
292 return (ord(s[0])<<24) | (ord(s[1])<<16) | (ord(s[2])<<8) | ord(s[3])
293
294def getword(s):
295 return (ord(s[0])<<8) | (ord(s[1])<<0)
296
297def mkkeyword(keyword):
298 return aetypes.Keyword(keyword)
299
300def mkrange(dict):
301 return aetypes.Range(dict['star'], dict['stop'])
302
303def mkcomparison(dict):
304 return aetypes.Comparison(dict['obj1'], dict['relo'].enum, dict['obj2'])
305
306def mklogical(dict):
307 return aetypes.Logical(dict['logc'], dict['term'])
308
309def mkstyledtext(dict):
310 return aetypes.StyledText(dict['ksty'], dict['ktxt'])
311
312def mkaetext(dict):
313 return aetypes.AEText(dict[keyAEScriptTag], dict[keyAEStyles], dict[keyAEText])
314
315def mkinsertionloc(dict):
316 return aetypes.InsertionLoc(dict[keyAEObject], dict[keyAEPosition])
317
318def mkobject(dict):
319 want = dict['want'].type
320 form = dict['form'].enum
321 seld = dict['seld']
322 fr = dict['from']
323 if form in ('name', 'indx', 'rang', 'test'):
324 if want == 'text': return aetypes.Text(seld, fr)
325 if want == 'cha ': return aetypes.Character(seld, fr)
326 if want == 'cwor': return aetypes.Word(seld, fr)
327 if want == 'clin': return aetypes.Line(seld, fr)
328 if want == 'cpar': return aetypes.Paragraph(seld, fr)
329 if want == 'cwin': return aetypes.Window(seld, fr)
330 if want == 'docu': return aetypes.Document(seld, fr)
331 if want == 'file': return aetypes.File(seld, fr)
332 if want == 'cins': return aetypes.InsertionPoint(seld, fr)
333 if want == 'prop' and form == 'prop' and aetypes.IsType(seld):
334 return aetypes.Property(seld.type, fr)
335 return aetypes.ObjectSpecifier(want, form, seld, fr)
336
Jack Jansen8b777672002-08-07 14:49:00 +0000337# Note by Jack: I'm not 100% sure of the following code. This was
338# provided by Donovan Preston, but I wonder whether the assignment
339# to __class__ is safe. Moreover, shouldn't there be a better
340# initializer for the classes in the suites?
341def mkobjectfrommodule(dict, modulename):
342 want = dict['want'].type
343 module = __import__(modulename)
344 codenamemapper = module._classdeclarations
345 classtype = codenamemapper.get(want, None)
346 newobj = mkobject(dict)
347 if classtype:
348 newobj.__class__ = classtype
349 return newobj