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