blob: 792cb728fa69df257eb8496d9220f21211e0d7ee [file] [log] [blame]
Guido van Rossum31559231995-02-05 16:59:27 +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
Jack Jansen40775ba1995-07-17 11:42:23 +000018Some 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
Guido van Rossum31559231995-02-05 16:59:27 +000021"""
22
23
Guido van Rossum31559231995-02-05 16:59:27 +000024from types import *
Guido van Rossum17448e21995-01-30 11:53:55 +000025import AE
Jack Jansen40775ba1995-07-17 11:42:23 +000026import AppleEvents
Guido van Rossum17448e21995-01-30 11:53:55 +000027import MacOS
Jack Jansen20989e81998-01-16 14:40:10 +000028import sys
Guido van Rossum17448e21995-01-30 11:53:55 +000029
Jack Jansen40775ba1995-07-17 11:42:23 +000030from aetypes import *
31from aepack import pack, unpack, coerce, AEDescType
Guido van Rossum31559231995-02-05 16:59:27 +000032
Jack Jansenc46f56e1996-09-20 15:28:28 +000033Error = 'aetools.Error'
34
Guido van Rossum31559231995-02-05 16:59:27 +000035# Special code to unpack an AppleEvent (which is *not* a disguised record!)
Jack Jansen40775ba1995-07-17 11:42:23 +000036# Note by Jack: No??!? If I read the docs correctly it *is*....
Guido van Rossum31559231995-02-05 16:59:27 +000037
Guido van Rossum17448e21995-01-30 11:53:55 +000038aekeywords = [
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 = {}
Jack Jansen90c3c161999-01-22 13:23:12 +000061 try:
62 dirobj = ae.AEGetParamDesc('----', '****')
63 except AE.Error:
64 pass
65 else:
66 parameters['----'] = unpack(dirobj)
67 del dirobj
Guido van Rossum17448e21995-01-30 11:53:55 +000068 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:
Jack Jansen20989e81998-01-16 14:40:10 +000077 if msg[0] != -1701 and msg[0] != -1704:
Guido van Rossum17448e21995-01-30 11:53:55 +000078 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
Jack Jansen40775ba1995-07-17 11:42:23 +000089#
90# Support routine for automatically generated Suite interfaces
Jack Jansen84264771995-10-03 14:35:58 +000091# These routines are also useable for the reverse function.
Jack Jansen40775ba1995-07-17 11:42:23 +000092#
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):
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']
Jack Jansen756a69f1997-08-08 15:00:03 +0000118 err_a1 = errn
Jack Jansen40775ba1995-07-17 11:42:23 +0000119 if arguments.has_key('errs'):
Jack Jansen756a69f1997-08-08 15:00:03 +0000120 err_a2 = arguments['errs']
121 else:
122 err_a2 = MacOS.GetErrorString(errn)
Jack Jansen40775ba1995-07-17 11:42:23 +0000123 if arguments.has_key('erob'):
Jack Jansen756a69f1997-08-08 15:00:03 +0000124 err_a3 = arguments['erob']
125 else:
126 err_a3 = None
127
128 return (err_a1, err_a2, err_a3)
Guido van Rossum31559231995-02-05 16:59:27 +0000129
Jack Jansen40775ba1995-07-17 11:42:23 +0000130class TalkTo:
131 """An AE connection to an application"""
132
Jack Jansen20989e81998-01-16 14:40:10 +0000133 def __init__(self, signature, start=0, timeout=0):
Jack Jansen40775ba1995-07-17 11:42:23 +0000134 """Create a communication channel with a particular application.
135
136 Addressing the application is done by specifying either a
137 4-byte signature, an AEDesc or an object that will __aepack__
138 to an AEDesc.
139 """
Jack Jansenc46f56e1996-09-20 15:28:28 +0000140 self.target_signature = None
Jack Jansen40775ba1995-07-17 11:42:23 +0000141 if type(signature) == AEDescType:
142 self.target = signature
143 elif type(signature) == InstanceType and hasattr(signature, '__aepack__'):
144 self.target = signature.__aepack__()
Jack Jansen7874b5d1995-07-29 15:31:10 +0000145 elif type(signature) == StringType and len(signature) == 4:
Jack Jansen40775ba1995-07-17 11:42:23 +0000146 self.target = AE.AECreateDesc(AppleEvents.typeApplSignature, signature)
Jack Jansenc46f56e1996-09-20 15:28:28 +0000147 self.target_signature = signature
Jack Jansen40775ba1995-07-17 11:42:23 +0000148 else:
149 raise TypeError, "signature should be 4-char string or AEDesc"
150 self.send_flags = AppleEvents.kAEWaitReply
151 self.send_priority = AppleEvents.kAENormalPriority
Jack Jansen20989e81998-01-16 14:40:10 +0000152 if timeout:
153 self.send_timeout = timeout
154 else:
155 self.send_timeout = AppleEvents.kAEDefaultTimeout
Jack Jansenc46f56e1996-09-20 15:28:28 +0000156 if start:
157 self.start()
158
159 def start(self):
160 """Start the application, if it is not running yet"""
Jack Jansen20989e81998-01-16 14:40:10 +0000161 _launch(self.target_signature)
Jack Jansenc46f56e1996-09-20 15:28:28 +0000162
Jack Jansen40775ba1995-07-17 11:42:23 +0000163 def newevent(self, code, subcode, parameters = {}, attributes = {}):
164 """Create a complete structure for an apple event"""
165
166 event = AE.AECreateAppleEvent(code, subcode, self.target,
167 AppleEvents.kAutoGenerateReturnID, AppleEvents.kAnyTransactionID)
168 packevent(event, parameters, attributes)
169 return event
170
171 def sendevent(self, event):
172 """Send a pre-created appleevent, await the reply and unpack it"""
173
174 reply = event.AESend(self.send_flags, self.send_priority,
175 self.send_timeout)
176 parameters, attributes = unpackevent(reply)
177 return reply, parameters, attributes
178
179 def send(self, code, subcode, parameters = {}, attributes = {}):
180 """Send an appleevent given code/subcode/pars/attrs and unpack the reply"""
181 return self.sendevent(self.newevent(code, subcode, parameters, attributes))
182
Jack Jansen7e156a71996-01-29 15:45:09 +0000183 #
184 # The following events are somehow "standard" and don't seem to appear in any
185 # suite...
186 #
Jack Jansen40775ba1995-07-17 11:42:23 +0000187 def activate(self):
188 """Send 'activate' command"""
189 self.send('misc', 'actv')
Jack Jansen7e156a71996-01-29 15:45:09 +0000190
Jack Jansen756a69f1997-08-08 15:00:03 +0000191 def _get(self, _object, as=None, _attributes={}):
192 """_get: get data from an object
Jack Jansen7e156a71996-01-29 15:45:09 +0000193 Required argument: the object
194 Keyword argument _attributes: AppleEvent attribute dictionary
195 Returns: the data
196 """
197 _code = 'core'
198 _subcode = 'getd'
199
200 _arguments = {'----':_object}
Jack Jansen756a69f1997-08-08 15:00:03 +0000201 if as:
202 _arguments['rtyp'] = mktype(as)
Jack Jansen7e156a71996-01-29 15:45:09 +0000203
204 _reply, _arguments, _attributes = self.send(_code, _subcode,
205 _arguments, _attributes)
206 if _arguments.has_key('errn'):
Jack Jansenc46f56e1996-09-20 15:28:28 +0000207 raise Error, decodeerror(_arguments)
Jack Jansen7e156a71996-01-29 15:45:09 +0000208
209 if _arguments.has_key('----'):
210 return _arguments['----']
Jack Jansen20989e81998-01-16 14:40:10 +0000211
212# Tiny Finder class, for local use only
213
214class _miniFinder(TalkTo):
215 def open(self, _object, _attributes={}, **_arguments):
216 """open: Open the specified object(s)
217 Required argument: list of objects to open
218 Keyword argument _attributes: AppleEvent attribute dictionary
219 """
220 _code = 'aevt'
221 _subcode = 'odoc'
222
223 if _arguments: raise TypeError, 'No optional args expected'
224 _arguments['----'] = _object
225
226
227 _reply, _arguments, _attributes = self.send(_code, _subcode,
228 _arguments, _attributes)
229 if _arguments.has_key('errn'):
Jack Jansena0fcd251999-01-21 13:34:26 +0000230 raise Error, decodeerror(_arguments)
Jack Jansen20989e81998-01-16 14:40:10 +0000231 # XXXX Optionally decode result
232 if _arguments.has_key('----'):
233 return _arguments['----']
234#pass
Jack Jansen40775ba1995-07-17 11:42:23 +0000235
Jack Jansen20989e81998-01-16 14:40:10 +0000236_finder = _miniFinder('MACS')
237
238def _launch(appfile):
239 """Open a file thru the finder. Specify file by name or fsspec"""
240 _finder.open(_application_file(('ID ', appfile)))
241
242
243class _application_file(ComponentItem):
244 """application file - An application's file on disk"""
245 want = 'appf'
246
247_application_file._propdict = {
248}
249_application_file._elemdict = {
250}
Jack Jansen40775ba1995-07-17 11:42:23 +0000251
Guido van Rossum31559231995-02-05 16:59:27 +0000252# Test program
Jack Jansen40775ba1995-07-17 11:42:23 +0000253# XXXX Should test more, really...
Guido van Rossum31559231995-02-05 16:59:27 +0000254
Guido van Rossum17448e21995-01-30 11:53:55 +0000255def test():
Jack Jansen20989e81998-01-16 14:40:10 +0000256 target = AE.AECreateDesc('sign', 'quil')
Guido van Rossum17448e21995-01-30 11:53:55 +0000257 ae = AE.AECreateAppleEvent('aevt', 'oapp', target, -1, 0)
258 print unpackevent(ae)
Guido van Rossum31559231995-02-05 16:59:27 +0000259 raw_input(":")
260 ae = AE.AECreateAppleEvent('core', 'getd', target, -1, 0)
261 obj = Character(2, Word(1, Document(1)))
262 print obj
263 print repr(obj)
264 packevent(ae, {'----': obj})
265 params, attrs = unpackevent(ae)
266 print params['----']
267 raw_input(":")
Guido van Rossum17448e21995-01-30 11:53:55 +0000268
269if __name__ == '__main__':
270 test()
Jack Jansen20989e81998-01-16 14:40:10 +0000271 sys.exit(1)