]> git.lyx.org Git - lyx.git/blob - development/keystest/keytest.py
New keytest version 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             if self.loops > 3:
141                 os._exit(0)
142             self.i = 0
143             return 'Loop'
144         line = self.lines[self.i]
145         self.count = self.count + 1
146         self.i = self.i + 1
147         print 'Line read: <<' + line + '>>\n'
148         return line.rstrip('\n').rstrip()
149
150
151 def lyx_sleeping():
152     fname = '/proc/' + lyx_pid + '/status'
153     if not os.path.exists(fname):
154         return False
155     f = open(fname, 'r')
156     lines = f.readlines()
157     sleeping = lines[1].find('(sleeping)') > 0
158
159     # print 'LYX_STATE', lines[1] , 'SLEEPING=', sleeping
160
161     return sleeping
162
163
164 def sendKeystring(keystr, LYX_PID):
165
166     # print "sending keystring "+keystr+"\n"
167
168     if not re.match(".*\w.*", keystr):
169         print 'print .' + keystr + '.\n'
170         keystr = 'a'
171     before_secs = time.time()
172     while not lyx_sleeping():
173         time.sleep(0.02)
174         print '.',
175         if time.time() - before_secs > 180:
176             print 'Killing due to freeze (KILL_FREEZE)'
177
178             # Do profiling, but sysprof has no command line interface?
179             # os.system("killall -KILL lyx")
180
181             os._exit(1)
182     if not screenshot_out is None:
183         while not lyx_sleeping():
184             time.sleep(0.02)
185             print '.',
186         print 'Making Screenshot: ' + screenshot_out + ' OF ' + infilename
187         time.sleep(0.2)
188         os.system('import -window root '+screenshot_out+str(x.count)+".png")
189         time.sleep(0.1)
190     sys.stdout.flush()
191     subprocess.call(["xvkbd", "-xsendevent", "-delay", DELAY, "-text", keystr])
192
193 def system_retry(num_retry, cmd):
194     i = 0
195     rtn = os.system(cmd)
196     while ( ( i < num_retry ) and ( rtn != 0) ):
197         i = i + 1
198         rtn=os.system(cmd)
199         time.sleep(1)
200     if ( rtn != 0 ):
201         print "Command Failed: "+cmd
202         print " EXITING!\n"
203         os._exit(1)
204
205 def RaiseWindow():
206     os.system("echo x-session-manager PID: $X_PID.")
207     os.system("echo x-session-manager open files: `lsof -p $X_PID | grep ICE-unix | wc -l`")
208     ####os.system("wmctrl -l | ( grep '"+lyx_window_name+"' || ( killall lyx ; sleep 1 ; killall -9 lyx ))")
209     #os.system("wmctrl -R '"+lyx_window_name+"' ;sleep 0.1")
210     system_retry(30, "wmctrl -R '"+lyx_window_name+"'")
211
212
213 lyx_pid = os.environ.get('LYX_PID')
214 print 'lyx_pid: ' + lyx_pid + '\n'
215 infilename = os.environ.get('KEYTEST_INFILE')
216 outfilename = os.environ.get('KEYTEST_OUTFILE')
217 max_drop = os.environ.get('MAX_DROP')
218 lyx_window_name = os.environ.get('LYX_WINDOW_NAME')
219 screenshot_out = os.environ.get('SCREENSHOT_OUT')
220
221 file_new_command = os.environ.get('FILE_NEW_COMMAND')
222 if file_new_command is None:
223     file_new_command = "\Afn"
224
225 ResetCommand = os.environ.get('RESET_COMMAND')
226 if ResetCommand is None:
227     ResetCommand = "\[Escape]\[Escape]\[Escape]\[Escape]" + file_new_command
228     #ResetCommand="\[Escape]\[Escape]\[Escape]\[Escape]\Cw\Cw\Cw\Cw\Cw\Afn"
229
230 if lyx_window_name is None:
231     lyx_window_name = 'LyX'
232
233 print 'outfilename: ' + outfilename + '\n'
234 print 'max_drop: ' + max_drop + '\n'
235
236 if infilename is None:
237     print 'infilename is None\n'
238     x = CommandSource()
239     print 'Using x=CommandSource\n'
240 else:
241     print 'infilename: ' + infilename + '\n'
242     probability_we_drop_a_command = random.uniform(0, float(max_drop))
243     print 'probability_we_drop_a_command: '
244     print '%s' % probability_we_drop_a_command
245     print '\n'
246     x = CommandSourceFromFile(infilename, probability_we_drop_a_command)
247     print 'Using x=CommandSourceFromFile\n'
248
249 outfile = open(outfilename, 'w')
250
251 RaiseWindow()
252 sendKeystring("\Afn", lyx_pid)
253 write_commands = True
254
255 while True:
256     os.system('echo -n LOADAVG:; cat /proc/loadavg')
257     c = x.getCommand()
258     if c == 'Loop':
259         outfile.close()
260         outfile = open(outfilename + '+', 'w')
261         print 'Now Looping'
262     outfile.writelines(c + '\n')
263     outfile.flush()
264     if c == 'RaiseLyx':
265         print 'Raising Lyx'
266         RaiseWindow()
267     elif c[0:4] == 'KK: ':
268         if os.path.exists('/proc/' + lyx_pid + '/status'):
269             sendKeystring(c[4:], lyx_pid)
270         else:
271             ##os.system('killall lyx; sleep 2 ; killall -9 lyx')
272             print 'No path /proc/' + lyx_pid + '/status, exiting'
273             os._exit(1)
274     elif c[0:4] == 'KD: ':
275         DELAY = c[4:].rstrip('\n')
276         print 'Setting DELAY to ' + DELAY + '.'
277     elif c == 'Loop':
278         RaiseWindow()
279         sendKeystring(ResetCommand, lyx_pid)
280     else:
281         print "Unrecognised Command '" + c + "'\n"