]> git.lyx.org Git - lyx.git/blob - development/keystest/keytest.py
Next patch for keystest from John McCabe-Dansted.
[lyx.git] / development / keystest / keytest.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # This script generates hundreds of random keypresses per second,
4 #  and sends them to the lyx window
5 # It requires xvkbd and wmctrl
6 # It generates a log of the KEYCODES it sends as development/keystest/out/KEYCODES
7
8 import random
9 import os
10 import re
11 import sys
12 import time
13 #from subprocess import call
14 import subprocess
15
16 print 'Beginning keytest.py'
17
18 DELAY = '59'
19
20 class CommandSource:
21
22     def __init__(self):
23         keycode = [
24             "\[Left]",
25             '\[Right]',
26             '\[Down]',
27             '\[Up]',
28             '\[BackSpace]',
29             '\[Delete]',
30             '\[Escape]',
31             ]
32         keycode[:0] = keycode
33         keycode[:0] = keycode
34
35         keycode[:0] = ['\\']
36
37         for k in range(97, 123):
38             keycode[:0] = chr(k)
39
40         for k in range(97, 123):
41             keycode[:0] = ["\A" + chr(k)]
42
43         for k in range(97, 123):
44             keycode[:0] = ["\A" + chr(k)]
45
46         for k in range(97, 123):
47             keycode[:0] = ["\C" + chr(k)]
48
49         self.keycode = keycode
50         self.count = 0
51         self.count_max = 1999
52
53     def getCommand(self):
54         self.count = self.count + 1
55         if self.count % 200 == 0:
56             return 'RaiseLyx'
57         elif self.count > self.count_max:
58             os._exit(0)
59         else:
60             keystr = ''
61             for k in range(1, 2):
62                 keystr = keystr + self.keycode[random.randint(1,
63                         len(self.keycode)) - 1]
64             return 'KK: ' + keystr
65
66
67 class CommandSourceFromFile(CommandSource):
68
69     def __init__(self, filename, p):
70
71         self.infile = open(filename, 'r')
72         self.lines = self.infile.readlines()
73         self.infile.close()
74         linesbak = self.lines
75         self.p = p
76         print p, self.p, 'self.p'
77         self.i = 0
78         self.count = 0
79         self.loops = 0
80
81         # Now we start randomly dropping lines, which we hope are redundant
82         # p is the probability that any given line will be removed
83
84         if p > 0.001:
85             if random.uniform(0, 1) < 0.5:
86                 print 'randomdrop_independant\n'
87                 self.randomdrop_independant()
88             else:
89                 print 'randomdrop_slice\n'
90                 self.randomdrop_slice()
91         if screenshot_out is None:
92             count_atleast = 100
93         else:
94             count_atleast = 1
95         self.max_count = max(len(self.lines) + 20, count_atleast)
96         if len(self.lines) < 1:
97             self.lines = linesbak
98
99     def randomdrop_independant(self):
100         p = self.p
101
102         # The next couple of lines are to ensure that at least one line is dropped
103
104         drop = random.randint(0, len(self.lines) - 1)
105         del self.lines[drop]
106         p = p - 1 / len(self.lines)
107         origlines = self.lines
108         self.lines = []
109         for l in origlines:
110             if random.uniform(0, 1) < self.p:
111                 print 'Randomly dropping line ' + l + '\n'
112             else:
113                 self.lines.append(l)
114         print 'LINES\n'
115         print self.lines
116         sys.stdout.flush()
117
118     def randomdrop_slice(self):
119         lines = self.lines
120         if random.uniform(0, 1) < 0.4:
121             lines.append(lines[0])
122             del lines[0]
123         num_lines = len(lines)
124         max_drop = max(5, num_lines / 5)
125         num_drop = random.randint(1, 5)
126         drop_mid = random.randint(0, num_lines)
127         drop_start = max(drop_mid - num_drop / 2, 0)
128         drop_end = min(drop_start + num_drop, num_lines)
129         print drop_start, drop_mid, drop_end
130         print lines
131         del lines[drop_start:drop_end]
132         print lines
133         self.lines = lines
134
135     def getCommand(self):
136         if self.count >= self.max_count:
137             os._exit(0)
138         if self.i >= len(self.lines):
139             self.loops = self.loops + 1
140             self.i = 0
141             return 'Loop'
142         line = self.lines[self.i]
143         self.count = self.count + 1
144         self.i = self.i + 1
145         print 'Line read: <<' + line + '>>\n'
146         return line.rstrip('\n').rstrip()
147
148
149 def lyx_sleeping():
150     fname = '/proc/' + lyx_pid + '/status'
151     if not os.path.exists(fname):
152         return False
153     f = open(fname, 'r')
154     lines = f.readlines()
155     sleeping = lines[1].find('(sleeping)') > 0
156
157     # print 'LYX_STATE', lines[1] , 'SLEEPING=', sleeping
158
159     return sleeping
160
161
162 def sendKeystring(keystr, LYX_PID):
163
164     # print "sending keystring "+keystr+"\n"
165
166     if not re.match(".*\w.*", keystr):
167         print 'print .' + keystr + '.\n'
168         keystr = 'a'
169     before_secs = time.time()
170     while not lyx_sleeping():
171         time.sleep(0.02)
172         print '.',
173         if time.time() - before_secs > 180:
174             print 'Killing due to freeze (KILL_FREEZE)'
175
176             # Do profiling, but sysprof has no command line interface?
177             # os.system("killall -KILL lyx")
178
179             os._exit(1)
180     if not screenshot_out is None:
181         while not lyx_sleeping():
182             time.sleep(0.02)
183             print '.',
184         print 'Making Screenshot: ' + screenshot_out
185         time.sleep(0.2)
186         os.system('import -window root '+screenshot_out+str(x.count)+".png")
187         time.sleep(0.1)
188     sys.stdout.flush()
189     subprocess.call(["xvkbd", "-xsendevent", "-delay", DELAY, "-text", keystr])
190
191 def RaiseWindow():
192     os.system("echo x-session-manager PID: $X_PID.")
193     os.system("echo x-session-manager open files: `lsof -p $X_PID | grep ICE-unix | wc -l`")
194     os.system("wmctrl -l | ( grep '"+lyx_window_name+"' || ( killall lyx ; sleep 1 ; killall -9 lyx ))")
195     os.system("wmctrl -R '"+lyx_window_name+"' ;sleep 0.1")
196
197
198 lyx_pid = os.environ.get('LYX_PID')
199 print 'lyx_pid: ' + lyx_pid + '\n'
200 infilename = os.environ.get('KEYTEST_INFILE')
201 outfilename = os.environ.get('KEYTEST_OUTFILE')
202 max_drop = os.environ.get('MAX_DROP')
203 lyx_window_name = os.environ.get('LYX_WINDOW_NAME')
204 screenshot_out = os.environ.get('SCREENSHOT_OUT')
205
206 file_new_command = os.environ.get('FILE_NEW_COMMAND')
207 if file_new_command is None:
208     file_new_command = "\Afn"
209
210 ResetCommand = os.environ.get('RESET_COMMAND')
211 if ResetCommand is None:
212     ResetCommand = "\[Escape]\[Escape]\[Escape]\[Escape]" + file_new_command
213     #ResetCommand="\[Escape]\[Escape]\[Escape]\[Escape]\Cw\Cw\Cw\Cw\Cw\Afn"
214
215 if lyx_window_name is None:
216     lyx_window_name = 'LyX'
217
218 print 'outfilename: ' + outfilename + '\n'
219 print 'max_drop: ' + max_drop + '\n'
220
221 if infilename is None:
222     print 'infilename is None\n'
223     x = CommandSource()
224     print 'Using x=CommandSource\n'
225 else:
226     print 'infilename: ' + infilename + '\n'
227     probability_we_drop_a_command = random.uniform(0, float(max_drop))
228     print 'probability_we_drop_a_command: '
229     print '%s' % probability_we_drop_a_command
230     print '\n'
231     x = CommandSourceFromFile(infilename, probability_we_drop_a_command)
232     print 'Using x=CommandSourceFromFile\n'
233
234 outfile = open(outfilename, 'w')
235
236 RaiseWindow()
237 sendKeystring("\Afn", lyx_pid)
238 write_commands = True
239
240 while True:
241     os.system('echo -n LOADAVG:; cat /proc/loadavg')
242     c = x.getCommand()
243     if c == 'Loop':
244         outfile.close()
245         outfile = open(outfilename + '+', 'w')
246         print 'Now Looping'
247     outfile.writelines(c + '\n')
248     outfile.flush()
249     if c == 'RaiseLyx':
250         print 'Raising Lyx'
251         RaiseWindow()
252     elif c[0:4] == 'KK: ':
253         if os.path.exists('/proc/' + lyx_pid + '/status'):
254             sendKeystring(c[4:], lyx_pid)
255         else:
256             os.system('killall lyx; sleep 2 ; killall -9 lyx')
257             print 'No path /proc/' + lyx_pid + '/status, exiting'
258             os._exit(1)
259     elif c[0:4] == 'KD: ':
260         DELAY = c[4:].rstrip('\n')
261         print 'Setting DELAY to ' + DELAY + '.'
262     elif c == 'Loop':
263         RaiseWindow()
264         sendKeystring(ResetCommand, lyx_pid)
265     else:
266         print "Unrecognised Command '" + c + "'\n"