Fix three PyChecker-detected gotchas.
[python/dscho.git] / Mac / Lib / test / tell.py
blob74e0ca0fb756a0f6577b61c994281f66c6a15770
1 # (Slightly less) primitive operations for sending Apple Events to applications.
2 # This could be the basis of a Script Editor like application.
4 from AE import *
5 from AppleEvents import *
6 import aetools
7 import types
9 class TalkTo:
10 def __init__(self, signature):
11 """Create a communication channel with a particular application.
13 For now, the application must be given by its 4-character signature
14 (because I don't know yet how to do other target types).
15 """
16 if type(signature) != types.StringType or len(signature) != 4:
17 raise TypeError, "signature should be 4-char string"
18 self.target = AECreateDesc(typeApplSignature, signature)
19 self.send_flags = kAEWaitReply
20 self.send_priority = kAENormalPriority
21 self.send_timeout = kAEDefaultTimeout
22 def newevent(self, code, subcode, parameters = {}, attributes = {}):
23 event = AECreateAppleEvent(code, subcode, self.target,
24 kAutoGenerateReturnID, kAnyTransactionID)
25 aetools.packevent(event, parameters, attributes)
26 return event
27 def sendevent(self, event):
28 reply = event.AESend(self.send_flags, self.send_priority,
29 self.send_timeout)
30 parameters, attributes = aetools.unpackevent(reply)
31 return reply, parameters, attributes
33 def send(self, code, subcode, parameters = {}, attributes = {}):
34 return self.sendevent(self.newevent(code, subcode, parameters, attributes))
36 def activate(self):
37 # Send undocumented but easily reverse engineered 'activate' command
38 self.send('misc', 'actv')
41 # This object is equivalent to "selection" in AppleScript
42 # (in the core suite, if that makes a difference):
43 get_selection = aetools.Property('sele', None)
45 # Test program. You can make it do what you want by passing parameters.
46 # The default gets the selection from Quill (Scriptable Text Editor).
48 def test(app = 'quil', suite = 'core', id = 'getd', arg = get_selection):
49 t = TalkTo(app)
50 t.activate()
51 if arg:
52 dict = {'----': arg}
53 else:
54 dict = {}
55 reply, parameters, attributes = t.send(suite, id, dict)
56 print reply, parameters
57 if parameters.has_key('----'): print "returns:", str(parameters['----'])
60 test()
61 # So we can see it:
62 import sys
63 sys.exit(1)