Jack Jansen | bb65377 | 1996-03-18 14:21:15 +0000 | [diff] [blame] | 1 | # (Slightly less) primitive operations for sending Apple Events to applications. |
| 2 | # This could be the basis of a Script Editor like application. |
| 3 | |
Jack Jansen | 5a6fdcd | 2001-08-25 12:15:04 +0000 | [diff] [blame] | 4 | from Carbon.AE import * |
| 5 | from Carbon.AppleEvents import * |
Jack Jansen | bb65377 | 1996-03-18 14:21:15 +0000 | [diff] [blame] | 6 | import aetools |
| 7 | import types |
| 8 | |
| 9 | class TalkTo: |
| 10 | def __init__(self, signature): |
| 11 | """Create a communication channel with a particular application. |
| 12 | |
| 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 |
| 32 | |
| 33 | def send(self, code, subcode, parameters = {}, attributes = {}): |
| 34 | return self.sendevent(self.newevent(code, subcode, parameters, attributes)) |
| 35 | |
| 36 | def activate(self): |
| 37 | # Send undocumented but easily reverse engineered 'activate' command |
| 38 | self.send('misc', 'actv') |
| 39 | |
| 40 | |
| 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) |
| 44 | |
| 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). |
| 47 | |
| 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['----']) |
| 58 | |
| 59 | |
| 60 | test() |
| 61 | # So we can see it: |
| 62 | import sys |
| 63 | sys.exit(1) |