blob: f58dd33f4a6d5401cf127ace5eaef2148f716c61 [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
23import macfs
24import StringIO
25import aetypes
26from aetypes import mkenum, mktype
27
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 = {
46 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,
55};
56
57#
58# Some python types we need in the packer:
59#
Jack Jansenad5dcaf2002-03-30 23:44:58 +000060AEDescType = AE.AEDescType
61FSSType = macfs.FSSpecType
62AliasType = macfs.AliasType
Jack Jansend0fc42f2001-08-19 22:05:06 +000063
64def pack(x, forcetype = None):
65 """Pack a python object into an AE descriptor"""
66
67 if forcetype:
68 if type(x) is StringType:
69 return AE.AECreateDesc(forcetype, x)
70 else:
71 return pack(x).AECoerceDesc(forcetype)
72
73 if x == None:
74 return AE.AECreateDesc('null', '')
75
76 t = type(x)
77 if t == AEDescType:
78 return x
79 if t == FSSType:
80 return AE.AECreateDesc('fss ', x.data)
81 if t == AliasType:
82 return AE.AECreateDesc('alis', x.data)
83 if t == IntType:
84 return AE.AECreateDesc('long', struct.pack('l', x))
85 if t == FloatType:
86 return AE.AECreateDesc('doub', struct.pack('d', x))
87 if t == StringType:
88 return AE.AECreateDesc('TEXT', x)
Jack Jansen5bb8f782002-02-05 21:24:47 +000089 if t == UnicodeType:
90 data = t.encode('utf16')
91 if data[:2] == '\xfe\xff':
92 data = data[2:]
93 return AE.AECreateDesc('utxt', data)
Jack Jansend0fc42f2001-08-19 22:05:06 +000094 if t == ListType:
95 list = AE.AECreateList('', 0)
96 for item in x:
97 list.AEPutDesc(0, pack(item))
98 return list
99 if t == DictionaryType:
100 record = AE.AECreateList('', 1)
101 for key, value in x.items():
102 record.AEPutParamDesc(key, pack(value))
103 return record
104 if t == InstanceType and hasattr(x, '__aepack__'):
105 return x.__aepack__()
106 return AE.AECreateDesc('TEXT', repr(x)) # Copout
107
108def unpack(desc):
109 """Unpack an AE descriptor to a python object"""
110 t = desc.type
111
112 if unpacker_coercions.has_key(t):
113 desc = desc.AECoerceDesc(unpacker_coercions[t])
114 t = desc.type # This is a guess by Jack....
115
116 if t == typeAEList:
117 l = []
118 for i in range(desc.AECountItems()):
119 keyword, item = desc.AEGetNthDesc(i+1, '****')
120 l.append(unpack(item))
121 return l
122 if t == typeAERecord:
123 d = {}
124 for i in range(desc.AECountItems()):
125 keyword, item = desc.AEGetNthDesc(i+1, '****')
126 d[keyword] = unpack(item)
127 return d
128 if t == typeAEText:
129 record = desc.AECoerceDesc('reco')
130 return mkaetext(unpack(record))
131 if t == typeAlias:
132 return macfs.RawAlias(desc.data)
133 # typeAppleEvent returned as unknown
134 if t == typeBoolean:
135 return struct.unpack('b', desc.data)[0]
136 if t == typeChar:
137 return desc.data
Jack Jansen5bb8f782002-02-05 21:24:47 +0000138 if t == typeUnicodeText:
139 return unicode(desc.data, 'utf16')
Jack Jansend0fc42f2001-08-19 22:05:06 +0000140 # typeColorTable coerced to typeAEList
141 # typeComp coerced to extended
142 # typeData returned as unknown
143 # typeDrawingArea coerced to typeAERecord
144 if t == typeEnumeration:
145 return mkenum(desc.data)
146 # typeEPS returned as unknown
147 if t == typeFalse:
148 return 0
149 if t == typeFloat:
150 data = desc.data
151 return struct.unpack('d', data)[0]
152 if t == typeFSS:
153 return macfs.RawFSSpec(desc.data)
154 if t == typeInsertionLoc:
155 record = desc.AECoerceDesc('reco')
156 return mkinsertionloc(unpack(record))
157 # typeInteger equal to typeLongInteger
158 if t == typeIntlText:
159 script, language = struct.unpack('hh', desc.data[:4])
160 return aetypes.IntlText(script, language, desc.data[4:])
161 if t == typeIntlWritingCode:
162 script, language = struct.unpack('hh', desc.data)
163 return aetypes.IntlWritingCode(script, language)
164 if t == typeKeyword:
165 return mkkeyword(desc.data)
166 if t == typeLongInteger:
167 return struct.unpack('l', desc.data)[0]
168 if t == typeLongDateTime:
169 a, b = struct.unpack('lL', desc.data)
170 return (long(a) << 32) + b
171 if t == typeNull:
172 return None
173 if t == typeMagnitude:
174 v = struct.unpack('l', desc.data)
175 if v < 0:
176 v = 0x100000000L + v
177 return v
178 if t == typeObjectSpecifier:
179 record = desc.AECoerceDesc('reco')
180 return mkobject(unpack(record))
181 # typePict returned as unknown
182 # typePixelMap coerced to typeAERecord
183 # typePixelMapMinus returned as unknown
184 # typeProcessSerialNumber returned as unknown
185 if t == typeQDPoint:
186 v, h = struct.unpack('hh', desc.data)
187 return aetypes.QDPoint(v, h)
188 if t == typeQDRectangle:
189 v0, h0, v1, h1 = struct.unpack('hhhh', desc.data)
190 return aetypes.QDRectangle(v0, h0, v1, h1)
191 if t == typeRGBColor:
192 r, g, b = struct.unpack('hhh', desc.data)
193 return aetypes.RGBColor(r, g, b)
194 # typeRotation coerced to typeAERecord
195 # typeScrapStyles returned as unknown
196 # typeSessionID returned as unknown
197 if t == typeShortFloat:
198 return struct.unpack('f', desc.data)[0]
199 if t == typeShortInteger:
200 return struct.unpack('h', desc.data)[0]
201 # typeSMFloat identical to typeShortFloat
202 # typeSMInt indetical to typeShortInt
203 # typeStyledText coerced to typeAERecord
204 if t == typeTargetID:
205 return mktargetid(desc.data)
206 # typeTextStyles coerced to typeAERecord
207 # typeTIFF returned as unknown
208 if t == typeTrue:
209 return 1
210 if t == typeType:
211 return mktype(desc.data)
212 #
213 # The following are special
214 #
215 if t == 'rang':
216 record = desc.AECoerceDesc('reco')
217 return mkrange(unpack(record))
218 if t == 'cmpd':
219 record = desc.AECoerceDesc('reco')
220 return mkcomparison(unpack(record))
221 if t == 'logi':
222 record = desc.AECoerceDesc('reco')
223 return mklogical(unpack(record))
224 return mkunknown(desc.type, desc.data)
225
226def coerce(data, egdata):
227 """Coerce a python object to another type using the AE coercers"""
228 pdata = pack(data)
229 pegdata = pack(egdata)
230 pdata = pdata.AECoerceDesc(pegdata.type)
231 return unpack(pdata)
232
233#
234# Helper routines for unpack
235#
236def mktargetid(data):
237 sessionID = getlong(data[:4])
238 name = mkppcportrec(data[4:4+72])
239 location = mklocationnamerec(data[76:76+36])
240 rcvrName = mkppcportrec(data[112:112+72])
241 return sessionID, name, location, rcvrName
242
243def mkppcportrec(rec):
244 namescript = getword(rec[:2])
245 name = getpstr(rec[2:2+33])
246 portkind = getword(rec[36:38])
247 if portkind == 1:
248 ctor = rec[38:42]
249 type = rec[42:46]
250 identity = (ctor, type)
251 else:
252 identity = getpstr(rec[38:38+33])
253 return namescript, name, portkind, identity
254
255def mklocationnamerec(rec):
256 kind = getword(rec[:2])
257 stuff = rec[2:]
258 if kind == 0: stuff = None
259 if kind == 2: stuff = getpstr(stuff)
260 return kind, stuff
261
262def mkunknown(type, data):
263 return aetypes.Unknown(type, data)
264
265def getpstr(s):
266 return s[1:1+ord(s[0])]
267
268def getlong(s):
269 return (ord(s[0])<<24) | (ord(s[1])<<16) | (ord(s[2])<<8) | ord(s[3])
270
271def getword(s):
272 return (ord(s[0])<<8) | (ord(s[1])<<0)
273
274def mkkeyword(keyword):
275 return aetypes.Keyword(keyword)
276
277def mkrange(dict):
278 return aetypes.Range(dict['star'], dict['stop'])
279
280def mkcomparison(dict):
281 return aetypes.Comparison(dict['obj1'], dict['relo'].enum, dict['obj2'])
282
283def mklogical(dict):
284 return aetypes.Logical(dict['logc'], dict['term'])
285
286def mkstyledtext(dict):
287 return aetypes.StyledText(dict['ksty'], dict['ktxt'])
288
289def mkaetext(dict):
290 return aetypes.AEText(dict[keyAEScriptTag], dict[keyAEStyles], dict[keyAEText])
291
292def mkinsertionloc(dict):
293 return aetypes.InsertionLoc(dict[keyAEObject], dict[keyAEPosition])
294
295def mkobject(dict):
296 want = dict['want'].type
297 form = dict['form'].enum
298 seld = dict['seld']
299 fr = dict['from']
300 if form in ('name', 'indx', 'rang', 'test'):
301 if want == 'text': return aetypes.Text(seld, fr)
302 if want == 'cha ': return aetypes.Character(seld, fr)
303 if want == 'cwor': return aetypes.Word(seld, fr)
304 if want == 'clin': return aetypes.Line(seld, fr)
305 if want == 'cpar': return aetypes.Paragraph(seld, fr)
306 if want == 'cwin': return aetypes.Window(seld, fr)
307 if want == 'docu': return aetypes.Document(seld, fr)
308 if want == 'file': return aetypes.File(seld, fr)
309 if want == 'cins': return aetypes.InsertionPoint(seld, fr)
310 if want == 'prop' and form == 'prop' and aetypes.IsType(seld):
311 return aetypes.Property(seld.type, fr)
312 return aetypes.ObjectSpecifier(want, form, seld, fr)
313
314def _test():
315 """Test program. Pack and unpack various things"""
316 objs = [
317 'a string',
318 12,
319 12.0,
320 None,
321 ['a', 'list', 'of', 'strings'],
322 {'key1': 'value1', 'key2':'value2'},
323 macfs.FSSpec(':'),
324 macfs.FSSpec(':').NewAliasMinimal(),
325 aetypes.Enum('enum'),
326 aetypes.Type('type'),
327 aetypes.Keyword('kwrd'),
328 aetypes.Range(1, 10),
329 aetypes.Comparison(1, '< ', 10),
330 aetypes.Logical('not ', 1),
331 # Cannot do StyledText
332 # Cannot do AEText
333 aetypes.IntlText(0, 0, 'international text'),
334 aetypes.IntlWritingCode(0,0),
335 aetypes.QDPoint(50,100),
336 aetypes.QDRectangle(50,100,150,200),
337 aetypes.RGBColor(0x7000, 0x6000, 0x5000),
338 aetypes.Unknown('xxxx', 'unknown type data'),
339 aetypes.Character(1),
340 aetypes.Character(2, aetypes.Line(2)),
341 ]
342 for o in objs:
343 print 'BEFORE', o, `o`
344 packed = pack(o)
345 unpacked = unpack(packed)
346 print 'AFTER ', unpacked, `unpacked`
347 import sys
348 sys.exit(1)
349
350if __name__ == '__main__':
351 _test()
352