blob: 00ec18aadc7a441f3391c1cb12f1cc0100c4c74a [file] [log] [blame]
Jack Jansend0fc42f2001-08-19 22:05:06 +00001"""Tools for use in AppleEvent clients and servers.
2
3pack(x) converts a Python object to an AEDesc object
4unpack(desc) does the reverse
5
6packevent(event, parameters, attributes) sets params and attrs in an AEAppleEvent record
7unpackevent(event) returns the parameters and attributes from an AEAppleEvent record
8
9Plus... Lots of classes and routines that help representing AE objects,
10ranges, conditionals, logicals, etc., so you can write, e.g.:
11
12 x = Character(1, Document("foobar"))
13
14and pack(x) will create an AE object reference equivalent to AppleScript's
15
16 character 1 of document "foobar"
17
18Some of the stuff that appears to be exported from this module comes from other
19files: the pack stuff from aepack, the objects from aetypes.
20
21"""
22
23
24from types import *
Jack Jansen5a6fdcd2001-08-25 12:15:04 +000025from Carbon import AE
26from Carbon import AppleEvents
Jack Jansend0fc42f2001-08-19 22:05:06 +000027import MacOS
28import sys
29
30from aetypes import *
31from aepack import pack, unpack, coerce, AEDescType
32
33Error = 'aetools.Error'
34
35# Special code to unpack an AppleEvent (which is *not* a disguised record!)
36# Note by Jack: No??!? If I read the docs correctly it *is*....
37
38aekeywords = [
39 'tran',
40 'rtid',
41 'evcl',
42 'evid',
43 'addr',
44 'optk',
45 'timo',
46 'inte', # this attribute is read only - will be set in AESend
47 'esrc', # this attribute is read only
48 'miss', # this attribute is read only
49 'from' # new in 1.0.1
50]
51
52def missed(ae):
53 try:
54 desc = ae.AEGetAttributeDesc('miss', 'keyw')
55 except AE.Error, msg:
56 return None
57 return desc.data
58
59def unpackevent(ae):
60 parameters = {}
61 try:
62 dirobj = ae.AEGetParamDesc('----', '****')
63 except AE.Error:
64 pass
65 else:
66 parameters['----'] = unpack(dirobj)
67 del dirobj
68 while 1:
69 key = missed(ae)
70 if not key: break
71 parameters[key] = unpack(ae.AEGetParamDesc(key, '****'))
72 attributes = {}
73 for key in aekeywords:
74 try:
75 desc = ae.AEGetAttributeDesc(key, '****')
76 except (AE.Error, MacOS.Error), msg:
77 if msg[0] != -1701 and msg[0] != -1704:
78 raise sys.exc_type, sys.exc_value
79 continue
80 attributes[key] = unpack(desc)
81 return parameters, attributes
82
83def packevent(ae, parameters = {}, attributes = {}):
84 for key, value in parameters.items():
85 ae.AEPutParamDesc(key, pack(value))
86 for key, value in attributes.items():
87 ae.AEPutAttributeDesc(key, pack(value))
88
89#
90# Support routine for automatically generated Suite interfaces
91# These routines are also useable for the reverse function.
92#
93def keysubst(arguments, keydict):
94 """Replace long name keys by their 4-char counterparts, and check"""
95 ok = keydict.values()
96 for k in arguments.keys():
97 if keydict.has_key(k):
98 v = arguments[k]
99 del arguments[k]
100 arguments[keydict[k]] = v
101 elif k != '----' and k not in ok:
102 raise TypeError, 'Unknown keyword argument: %s'%k
103
104def enumsubst(arguments, key, edict):
105 """Substitute a single enum keyword argument, if it occurs"""
106 if not arguments.has_key(key) or edict is None:
107 return
108 v = arguments[key]
109 ok = edict.values()
110 if edict.has_key(v):
111 arguments[key] = edict[v]
112 elif not v in ok:
113 raise TypeError, 'Unknown enumerator: %s'%v
114
115def decodeerror(arguments):
116 """Create the 'best' argument for a raise MacOS.Error"""
117 errn = arguments['errn']
118 err_a1 = errn
119 if arguments.has_key('errs'):
120 err_a2 = arguments['errs']
121 else:
122 err_a2 = MacOS.GetErrorString(errn)
123 if arguments.has_key('erob'):
124 err_a3 = arguments['erob']
125 else:
126 err_a3 = None
127
128 return (err_a1, err_a2, err_a3)
129
130class TalkTo:
131 """An AE connection to an application"""
132 _signature = None # Can be overridden by subclasses
133
134 def __init__(self, signature=None, start=0, timeout=0):
135 """Create a communication channel with a particular application.
136
137 Addressing the application is done by specifying either a
138 4-byte signature, an AEDesc or an object that will __aepack__
139 to an AEDesc.
140 """
141 self.target_signature = None
142 if signature is None:
143 signature = self._signature
144 if type(signature) == AEDescType:
145 self.target = signature
146 elif type(signature) == InstanceType and hasattr(signature, '__aepack__'):
147 self.target = signature.__aepack__()
148 elif type(signature) == StringType and len(signature) == 4:
149 self.target = AE.AECreateDesc(AppleEvents.typeApplSignature, signature)
150 self.target_signature = signature
151 else:
152 raise TypeError, "signature should be 4-char string or AEDesc"
153 self.send_flags = AppleEvents.kAEWaitReply
154 self.send_priority = AppleEvents.kAENormalPriority
155 if timeout:
156 self.send_timeout = timeout
157 else:
158 self.send_timeout = AppleEvents.kAEDefaultTimeout
159 if start:
160 self.start()
161
162 def start(self):
163 """Start the application, if it is not running yet"""
164 try:
165 self.send('ascr', 'noop')
166 except AE.Error:
167 _launch(self.target_signature)
168
169 def newevent(self, code, subcode, parameters = {}, attributes = {}):
170 """Create a complete structure for an apple event"""
171
172 event = AE.AECreateAppleEvent(code, subcode, self.target,
173 AppleEvents.kAutoGenerateReturnID, AppleEvents.kAnyTransactionID)
174 packevent(event, parameters, attributes)
175 return event
176
177 def sendevent(self, event):
178 """Send a pre-created appleevent, await the reply and unpack it"""
179
180 reply = event.AESend(self.send_flags, self.send_priority,
181 self.send_timeout)
182 parameters, attributes = unpackevent(reply)
183 return reply, parameters, attributes
184
185 def send(self, code, subcode, parameters = {}, attributes = {}):
186 """Send an appleevent given code/subcode/pars/attrs and unpack the reply"""
187 return self.sendevent(self.newevent(code, subcode, parameters, attributes))
188
189 #
190 # The following events are somehow "standard" and don't seem to appear in any
191 # suite...
192 #
193 def activate(self):
194 """Send 'activate' command"""
195 self.send('misc', 'actv')
196
197 def _get(self, _object, as=None, _attributes={}):
198 """_get: get data from an object
199 Required argument: the object
200 Keyword argument _attributes: AppleEvent attribute dictionary
201 Returns: the data
202 """
203 _code = 'core'
204 _subcode = 'getd'
205
206 _arguments = {'----':_object}
207 if as:
208 _arguments['rtyp'] = mktype(as)
209
210 _reply, _arguments, _attributes = self.send(_code, _subcode,
211 _arguments, _attributes)
212 if _arguments.has_key('errn'):
213 raise Error, decodeerror(_arguments)
214
215 if _arguments.has_key('----'):
216 return _arguments['----']
217
218# Tiny Finder class, for local use only
219
220class _miniFinder(TalkTo):
221 def open(self, _object, _attributes={}, **_arguments):
222 """open: Open the specified object(s)
223 Required argument: list of objects to open
224 Keyword argument _attributes: AppleEvent attribute dictionary
225 """
226 _code = 'aevt'
227 _subcode = 'odoc'
228
229 if _arguments: raise TypeError, 'No optional args expected'
230 _arguments['----'] = _object
231
232
233 _reply, _arguments, _attributes = self.send(_code, _subcode,
234 _arguments, _attributes)
235 if _arguments.has_key('errn'):
236 raise Error, decodeerror(_arguments)
237 # XXXX Optionally decode result
238 if _arguments.has_key('----'):
239 return _arguments['----']
240#pass
241
242_finder = _miniFinder('MACS')
243
244def _launch(appfile):
245 """Open a file thru the finder. Specify file by name or fsspec"""
246 _finder.open(_application_file(('ID ', appfile)))
247
248
249class _application_file(ComponentItem):
250 """application file - An application's file on disk"""
251 want = 'appf'
252
253_application_file._propdict = {
254}
255_application_file._elemdict = {
256}
257
258# Test program
259# XXXX Should test more, really...
260
261def test():
262 target = AE.AECreateDesc('sign', 'quil')
263 ae = AE.AECreateAppleEvent('aevt', 'oapp', target, -1, 0)
264 print unpackevent(ae)
265 raw_input(":")
266 ae = AE.AECreateAppleEvent('core', 'getd', target, -1, 0)
267 obj = Character(2, Word(1, Document(1)))
268 print obj
269 print repr(obj)
270 packevent(ae, {'----': obj})
271 params, attrs = unpackevent(ae)
272 print params['----']
273 raw_input(":")
274
275if __name__ == '__main__':
276 test()
277 sys.exit(1)