summaryrefslogtreecommitdiffstats
path: root/Mac/Contrib/AECaptureParser/AECaptureParser.py
blob: 25a0237a3d115fd69813a6c4c6bcef0ec3f930b0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
'''
AECaptureParser makes a brave attempt to convert the text output
of the very handy Lasso Capture AE control panel
into close-enough executable python code.

In a roundabout way AECaptureParser offers the way to write lines of AppleScript
and convert them to python code. Once Pythonised, the code can be made prettier,
and it can run without Capture or Script Editor being open.

You need Lasso Capture AE from Blueworld:
ftp://ftp.blueworld.com/Lasso251/LassoCaptureAE.hqx

Lasso Capture AE prints structured ascii representations in a small window.
As these transcripts can be very complex, cut and paste to AECaptureParser, it parses and writes
python code that will, when executed, cause the same events to happen.
It's been tested with some household variety events, I'm sure there will be tons that
don't work.

All objects are converted to standard aetypes.ObjectSpecifier instances.

How to use:
	1. Start the Capture window
	2. Cause the desired appleevent to happen
		- by writing a line of applescript in Script Editor and running it (!)
		- by recording some action in Script Editor and running it
	3. Find the events in Capture:
		- make sure you get the appropriate events, cull if necessary
		- sometimes Capture barfs, just quit and start Capture again, run events again
		- AECaptureParser can process multiple events - it will just make more code.
	4. Copy and paste in this script and execute
	5. It will print python code that, when executed recreates the events.

Example:
	For instance the following line of AppleScript in Script Editor
			tell application "Finder"
				return application processes
			end tell
	will result in the following transcript:
			[event: target="Finder", class=core, id=getd]
			'----':obj {form:indx, want:type(pcap), seld:abso(«616C6C20»), from:'null'()}
			[/event]
	Feed a string with this (and perhaps more) events to AECaptureParser
	
Some mysteries:
	* 	what is '&subj' - it is sent in an activate event:	&subj:'null'()
		The activate event works when this is left out. A possibility?
	*	needs to deal with embedded aliasses


'''
__version__ = '0.002'
__author__ = 'evb'


import string 

opentag = '{'
closetag = '}'



import aetools
import aetypes

class eventtalker(aetools.TalkTo):
	pass

def processes():
	'''Helper function to get the list of current processes and their creators
	This code was mostly written by AECaptureParser! It ain't pretty, but that's not python's fault!'''
	talker = eventtalker('MACS')
	_arguments = {}
	_attributes = {}
	p = []
	names = []
	creators = []
	results = []
	# first get the list of process names
	_arguments['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('pcap'),
			form="indx", seld=aetypes.Unknown('abso', "all "), fr=None)
	_reply, _arguments, _attributes = talker.send('core', 'getd', _arguments, _attributes)
	if _arguments.has_key('errn'):
		raise aetools.Error, aetools.decodeerror(_arguments)
	if _arguments.has_key('----'):
		p = _arguments['----']
	for proc in p:
		names.append(proc.seld)
	# then get the list of process creators
	_arguments = {}
	_attributes = {}
	AEobject_00 = aetypes.ObjectSpecifier(want=aetypes.Type('pcap'), form="indx", seld=aetypes.Unknown('abso', "all "), fr=None)
	AEobject_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('fcrt'), fr=AEobject_00)
	_arguments['----'] = AEobject_01
	_reply, _arguments, _attributes = talker.send('core', 'getd', _arguments, _attributes)
	if _arguments.has_key('errn'):
		raise aetools.Error, aetools.decodeerror(_arguments)
	if _arguments.has_key('----'):
		p = _arguments['----']
	for proc in p:
		creators.append(proc.type)
	# then put the lists together
	for i in range(len(names)):
		results.append((names[i], creators[i]))
	return results

		
class AECaptureParser:
	'''convert a captured appleevent-description into executable python code'''
	def __init__(self, aetext):
		self.aetext = aetext
		self.events = []
		self.arguments = {}
		self.objectindex = 0
		self.varindex = 0
		self.currentevent =  {'variables':{}, 'arguments':{}, 'objects':{}}
		self.parse()
	
	def parse(self):
		self.lines = string.split(self.aetext, '\n')
		for l in self.lines:
			if l[:7] == '[event:':
				self.eventheader(l)
			elif l[:7] == '[/event':
				if len(self.currentevent)<>0:
					self.events.append(self.currentevent)
					self.currentevent = {'variables':{}, 'arguments':{}, 'objects':{}}
					self.objectindex = 0
			else:
				self.line(l)
	
	def line(self, value):
		'''interpret literals, variables, lists etc.'''
		# stuff in [  ], l ists
		varstart = string.find(value, '[')
		varstop = string.find(value, ']')
		if varstart <> -1 and varstop <> -1 and varstop>varstart:
			variable = value[varstart:varstop+1]
			name = 'aevar_'+string.zfill(self.varindex, 2)
			self.currentevent['variables'][name] = variable
			value = value[:varstart]+name+value[varstop+1:]
			self.varindex = self.varindex + 1
		# stuff in «  »
		# these are 'ordinal' descriptors of 4 letter codes, so translate
		varstart = string.find(value, '«')
		varstop = string.find(value, '»')
		if varstart <> -1 and varstop <> -1 and varstop>varstart:
			variable = value[varstart+1:varstop]
			t = ''
			for i in range(0, len(variable), 2):
				c = eval('0x'+variable[i : i+2])
				t = t + chr(c)
			
			name = 'aevar_'+string.zfill(self.varindex, 2)
			self.currentevent['variables'][name] = '"' + t + '"'
			value = value[:varstart]+name+value[varstop+1:]
			self.varindex = self.varindex + 1
		pos = string.find(value, ':')
		if pos==-1:return
		ok = 1
		while ok <> None:
			value, ok = self.parseobject(value)
		self.currentevent['arguments'].update(self.splitparts(value, ':'))
		
		# remove the &subj argument?
		if self.currentevent['arguments'].has_key('&subj'):
			del self.currentevent['arguments']['&subj']
			
		# check for arguments len(a) < 4, and pad with spaces
		for k in self.currentevent['arguments'].keys():
			if len(k)<4:
				newk = k + (4-len(k))*' '
				self.currentevent['arguments'][newk] = self.currentevent['arguments'][k]
				del self.currentevent['arguments'][k]

	def parseobject(self, obj):
		a, b = self.findtag(obj)
		stuff = None
		if a<>None and b<>None:
			stuff = obj[a:b]
			name = 'AEobject_'+string.zfill(self.objectindex, 2)
			self.currentevent['objects'][name] = self.splitparts(stuff, ':')
			obj = obj[:a-5] + name + obj[b+1:]
			self.objectindex = self.objectindex +1
		return obj, stuff
		
	def nextopen(self, pos, text):
		return string.find(text, opentag, pos)
		
	def nextclosed(self, pos, text):
		return string.find(text, closetag, pos)
	
	def nexttag(self, pos, text):
		start = self.nextopen(pos, text)
		stop = self.nextclosed(pos, text)
		if start == -1:
			if stop == -1:
				return -1, -1
			return 0, stop
		if start < stop and start<>-1:
			return 1, start
		else:
			return 0, stop
					
	def findtag(self, text):
		p = -1
		last = None,None
		while 1:
			kind, p = self.nexttag(p+1, text)
			if last[0]==1 and kind==0:
				return last[1]+len(opentag), p
			if (kind, p) == (-1, -1):
				break
			last=kind, p
		return None, None
	
	def splitparts(self, txt, splitter):
		res = {}
		parts = string.split(txt, ', ')
		for p in parts:
			pos = string.find(p, splitter)
			key = string.strip(p[:pos])
			value = string.strip(p[pos+1:])
			res[key] = self.map(value)
		return res
		
	def eventheader(self, hdr):
		self.currentevent['event'] = self.splitparts(hdr[7:-1], '=')
	
	def printobject(self, d):
		'''print one object as python code'''
		t = []
		obj = {}
		obj.update(d)
		t.append("aetypes.ObjectSpecifier(")
		if obj.has_key('want'):
			t.append('want=' + self.map(obj['want']))
			del obj['want']
			t.append(', ')
		if obj.has_key('form'):
			t.append('form=' + addquotes(self.map(obj['form'])))
			del obj['form']
			t.append(', ')
		if obj.has_key('seld'):
			t.append('seld=' + self.map(obj['seld']))
			del obj['seld']
			t.append(', ')
		if obj.has_key('from'):
			t.append('fr=' + self.map(obj['from']))
			del obj['from']
		if len(obj.keys()) > 0:
			print '# ', `obj`			
		t.append(")")
		return string.join(t, '')
	
	def map(self, t):
		'''map some Capture syntax to python
		matchstring : [(old, new), ... ]
		'''
		m = {
				'type(': [('type(', "aetypes.Type('"), (')', "')")],
				"'null'()": [("'null'()", "None")],
				'abso(': [('abso(', "aetypes.Unknown('abso', ")],
				'³':	[('³', '"')],
				'²':	[('²', '"')],
				'[':	[('[', '('), (', ', ',')],
				']':	[(']', ')')],
				'«':	[('«', "«")],
				'»':	[('»', "»")],
				
			}
		for k in m.keys():
			if string.find(t, k) <> -1:
				for old, new in m[k]:
					p = string.split(t, old)
					t = string.join(p, new)
		return t
		
	def printevent(self, i):
		'''print the entire captured sequence as python'''
		evt = self.events[i]
		code = []
		code.append('\n# start event ' + `i` + ', talking to ' + evt['event']['target'])
		# get the signature for the target application
		code.append('talker = eventtalker("'+self.gettarget(evt['event']['target'])+'")')
		code.append("_arguments = {}")
		code.append("_attributes = {}")
		# write the variables
		for key, value in evt['variables'].items():
			value = evt['variables'][key]
			code.append(key + ' = ' + value)
		# write the object in the right order
		objkeys = evt['objects'].keys()
		objkeys.sort()
		for key in objkeys:
			value = evt['objects'][key]
			code.append(key + ' = ' + self.printobject(value))
		# then write the arguments
		for key, value in evt['arguments'].items():
			code.append("_arguments[" + addquotes(key) + "] = " + value )
		code.append('_reply, _arguments, _attributes = talker.send("'+
				evt['event']['class']+'", "'+evt['event']['id']+'", _arguments, _attributes)')
		code.append("if _arguments.has_key('errn'):")
		code.append('\traise aetools.Error, aetools.decodeerror(_arguments)')	
		code.append("if _arguments.has_key('----'):")
		code.append("\tprint _arguments['----']")
		code.append('# end event ' + `i`)
		return string.join(code, '\n')
	
	def gettarget(self, target):
		'''get the signature for the target application'''
		target = target[1:-1]
		if target == 'Finder':
			return "MACS"
		apps = processes()
		for name, creator in apps:
			if name == target:
				return creator
		return '****'
			
	def makecode(self):
		code = []
		code.append("\n\n")
		code.append("# code generated by AECaptureParser v " + __version__)
		code.append("# imports, definitions for all events")
		code.append("import aetools")
		code.append("import aetypes")
		code.append("class eventtalker(aetools.TalkTo):")
		code.append("\tpass")
		code.append("# the events")
		# print the events
		for i in range(len(self.events)):
			code.append(self.printevent(i))
		code.append("# end code")
		return string.join(code, '\n')

def addquotes(txt):
	quotes = ['"', "'"]
	if not txt[0] in quotes and not txt[-1] in quotes:
		return '"'+txt+'"'
	return txt 
	
	




# ------------------------------------------
#	the factory
# ------------------------------------------

# for instance, this event was captured from the Script Editor asking the Finder for a list of active processes.

eventreceptacle = """

[event: target="Finder", class=core, id=setd]
'----':obj {form:prop, want:type(prop), seld:type(posn), from:obj {form:name, want:type(cfol), seld:³MoPar:Data:DevDev:Python:Python 1.5.2c1:Extensions², from:'null'()}}, data:[100, 10]
[/event]

"""

aet = AECaptureParser(eventreceptacle)
print aet.makecode()