]> git.lyx.org Git - lyx.git/blob - development/autotests/keytest.py
Amend 2b24c03e: Do not override (Back)Tab in Adv F&R when it is useful
[lyx.git] / development / autotests / 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 # Adapted by Tommaso Cucinotta from the original MonKey Test by
9 # John McCabe-Dansted.
10
11 from __future__ import print_function
12 import random
13 import os
14 import re
15 import sys
16 import time
17 import tempfile
18 import shutil
19
20 #from subprocess import call
21 import subprocess
22
23 print('Beginning keytest.py')
24
25 FNULL = open('/dev/null', 'w')
26
27 key_delay = ''
28
29 # Ignore status == "dead" if this is set. Used at the last commands after "\Cq"
30 dead_expected = False
31
32 def die(excode, text):
33     if text != "":
34         print(text)
35     sys.stdout.flush()
36     os._exit(excode)
37
38 class CommandSource:
39
40     def __init__(self):
41         keycode = [
42             "\[Left]",
43             '\[Right]',
44             '\[Down]',
45             '\[Up]',
46             '\[BackSpace]',
47             '\[Delete]',
48             '\[Escape]',
49             ]
50         keycode[:0] = keycode
51         keycode[:0] = keycode
52
53         keycode[:0] = ['\\']
54
55         for k in range(97, 123):
56             keycode[:0] = chr(k)
57
58         for k in range(97, 123):
59             keycode[:0] = ["\A" + chr(k)]
60
61         for k in range(97, 123):
62             keycode[:0] = ["\A" + chr(k)]
63
64         for k in range(97, 123):
65             keycode[:0] = ["\C" + chr(k)]
66
67         self.keycode = keycode
68         self.count = 0
69         self.count_max = 1999
70
71     def getCommand(self):
72         self.count = self.count + 1
73         if self.count % 200 == 0:
74             return 'RaiseLyx'
75         elif self.count > self.count_max:
76             die(0, "")
77         else:
78             keystr = ''
79             for k in range(1, 2):
80                 keystr = keystr + self.keycode[random.randint(1,
81                         len(self.keycode)) - 1]
82             return 'KK: ' + keystr
83
84
85 class CommandSourceFromFile(CommandSource):
86
87     def __init__(self, filename, p):
88
89         self.infile = open(filename, 'r')
90         self.lines = self.infile.readlines()
91         self.infile.close()
92         linesbak = self.lines
93         self.p = p
94         print(p, self.p, 'self.p')
95         self.i = 0
96         self.count = 0
97         self.loops = 0
98
99         # Now we start randomly dropping lines, which we hope are redundant
100         # p is the probability that any given line will be removed
101
102         if p > 0.001:
103             if random.uniform(0, 1) < 0.5:
104                 print('randomdrop_independant\n')
105                 self.randomdrop_independant()
106             else:
107                 print('randomdrop_slice\n')
108                 self.randomdrop_slice()
109         if screenshot_out is None:
110             count_atleast = 100
111         else:
112             count_atleast = 1
113         self.max_count = max(len(self.lines) + 20, count_atleast)
114         if len(self.lines) < 1:
115             self.lines = linesbak
116
117     def randomdrop_independant(self):
118         p = self.p
119
120         # The next couple of lines are to ensure that at least one line is dropped
121
122         drop = random.randint(0, len(self.lines) - 1)
123         del self.lines[drop]
124         #p = p - 1 / len(self.lines)
125         origlines = self.lines
126         self.lines = []
127         for l in origlines:
128             if random.uniform(0, 1) < self.p:
129                 print('Randomly dropping line ' + l + '\n')
130             else:
131                 self.lines.append(l)
132         print('LINES\n')
133         print(self.lines)
134         sys.stdout.flush()
135
136     def randomdrop_slice(self):
137         lines = self.lines
138         if random.uniform(0, 1) < 0.4:
139             lines.append(lines[0])
140             del lines[0]
141         num_lines = len(lines)
142         max_drop = max(5, num_lines / 5)
143         num_drop = random.randint(1, 5)
144         drop_mid = random.randint(0, num_lines)
145         drop_start = max(drop_mid - num_drop / 2, 0)
146         drop_end = min(drop_start + num_drop, num_lines)
147         print(drop_start, drop_mid, drop_end)
148         print(lines)
149         del lines[drop_start:drop_end]
150         print(lines)
151         self.lines = lines
152
153     def getCommand(self):
154         if self.count >= self.max_count:
155             die(0, "")
156         if self.i >= len(self.lines):
157             self.loops = self.loops + 1
158             if self.loops >= int(max_loops):
159                 return None
160             self.i = 0
161             return 'Loop'
162         line = self.lines[self.i].rstrip('\n')
163         self.count = self.count + 1
164         self.i = self.i + 1
165         return line
166
167 class ControlFile:
168
169     def __init__(self):
170         self.control = re.compile(r'^(C[ONPpRrC])([A-Za-z0-9]*):\s*(.*)$')
171         self.fileformat = re.compile(r'^((\>\>?)[,\s]\s*)?([^\s]+)\s*$')
172         self.cntrfile = dict()
173         # Map keytest marker to pattern-file-marker for searchPatterns.pl
174         self.convertSearchMark = { 'CN': 'Comment: ',
175                                    'CP': 'Simple: ', 'Cp': 'ErrSimple: ',
176                                    'CR': 'Regex: ',  'Cr': 'ErrRegex: '}
177
178     def __open(self, handle, filename):
179         if handle in self.cntrfile:
180             self.cntrfile[handle].close()
181             del self.cntrfile[handle]
182         m = self.fileformat.match(filename)
183         if m:
184             type = m.group(2)
185             filename = m.group(3)
186             if type == '>>':
187                 append = True
188             else:
189                 append = False
190         else:
191             append = False
192         if append:
193             self.cntrfile[handle] = open(filename, 'a')
194         else:
195             self.cntrfile[handle] = open(filename, 'w')
196
197     def closeall(self):
198         handles = self.cntrfile.keys()
199         for handle in handles:
200             self.__close(handle)
201
202     def __close(self, handle):
203         if handle in self.cntrfile:
204             name = self.cntrfile[handle].name
205             self.cntrfile[handle].close()
206             del self.cntrfile[handle]
207             print("Closed ctrl " + handle + " (" + name + ")")
208
209     # make the method below 'private'
210     def __addline(self, handle, pat):
211         self.cntrfile[handle].writelines(pat + "\n")
212
213     def dispatch(self, c):
214         m = self.control.match(c)
215         if not m:
216             return False
217         command = m.group(1)
218         handle = m.group(2)
219         if handle is None:
220             handle = ""
221         text = m.group(3)
222         if command == "CO":
223             self.__open(handle, text);
224         elif command == "CC":
225             self.__close(handle)
226         else:
227             if handle in self.cntrfile:
228                 if command in self.convertSearchMark:
229                     self.__addline(handle, self.convertSearchMark[command] + text)
230                 else:
231                     die(1,"Error, Unrecognised Command '" + command + "'")
232             elif handle != "":
233                 die(1, "Ctrl-file " + handle + " not in use")
234         return True
235
236
237 def get_proc_pid(proc_name):
238     pid=os.popen("pidof " + proc_name).read().rstrip()
239     return pid
240
241 wlistreg = re.compile(r'^(0x[0-9a-f]{5,9})\s+[^\s]+\s+([0-9]+)\s.*$')
242 def get_proc_win_id(pid, ignoreid):
243     nlist = os.popen("wmctrl -l -p").read()
244     wlist = nlist.split("\n")
245     for item in wlist:
246         m = wlistreg.match(item)
247         if m:
248             win_id = m.group(1)
249             win_pid = m.group(2)
250             if win_pid == pid:
251                 if win_id != ignoreid:
252                     return win_id
253     return None
254
255 def lyx_exists():
256     if lyx_pid is None:
257         return False
258     fname = '/proc/' + lyx_pid + '/status'
259     return os.path.exists(fname)
260
261
262 # Interruptible os.system()
263 def intr_system(cmd, ignore_err = False):
264     print("Executing " + cmd)
265     # Assure the output of cmd does not overhaul
266     sys.stdout.flush()
267     ret = os.system(cmd)
268     if os.WIFSIGNALED(ret):
269         raise KeyboardInterrupt
270     if ret != 0 and not ignore_err:
271         raise BaseException("command failed:" + cmd)
272     return ret
273
274 statreg = re.compile(r'^State:.*\(([a-z]+)\)')
275
276 resstatus = []
277 def printresstatus():
278     for line in resstatus:
279         line = line.rstrip()
280         print("    " + line.rstrip())
281     print('End of /proc-lines')
282
283 def lyx_status_retry(pid):
284     resstatus = []
285     if pid is None:
286         print('Pid is None')
287         return "dead"
288     fname = '/proc/' + pid + '/status'
289     status = "dead"
290     try:
291         f = open(fname)
292         found = False
293         for line in f:
294             resstatus.extend([line])
295             m = statreg.match(line)
296             if m:
297                 status = m.group(1)
298                 found = True
299         f.close()
300         if not found:
301             return "retry"
302         return status
303     except IOError as e:
304         print("I/O error({0}): {1}".format(e.errno, e.strerror))
305         return "dead"
306     except:
307         print("Unexpected error:", sys.exc_info()[0])
308         return "dead"
309     print('This should not happen')
310     return status
311
312 def lyx_status(pid):
313     count = 0
314     while 1:
315         status = lyx_status_retry(pid)
316         if status != "retry":
317             break
318         if count == 0:
319             print('Retrying check for status')
320         count += 1
321         time.sleep(0.01)
322     if count > 1:
323         print('Retried to read status ' + str(count) + ' times')
324     #print('lys_status() returning ' + status)
325     return status
326
327 # Return true if LyX (identified via lyx_pid) is sleeping
328 def lyx_sleeping(LYX_PID):
329     return lyx_status(LYX_PID) == "sleeping"
330
331 # Return true if LyX (identified via lyx_pid) is zombie
332 def lyx_zombie(LYX_PID):
333     return lyx_status(LYX_PID) == "zombie"
334
335 def lyx_dead(LYX_PID):
336     status = lyx_status(LYX_PID)
337     return (status == "dead") or (status == "zombie")
338
339 def wait_until_lyx_sleeping(LYX_PID):
340     before_secs = time.time()
341     while True:
342         status = lyx_status(LYX_PID)
343         if status == "sleeping":
344             return True
345         if (status == "dead") or (status == "zombie"):
346             printresstatus()
347             if dead_expected:
348                 print('Lyx died while waiting for status == sleeping')
349                 return False
350             else:
351                 die(1,"Lyx is dead, exiting")
352         if time.time() - before_secs > 180:
353             # Do profiling, but sysprof has no command line interface?
354             # intr_system("killall -KILL lyx")
355             printresstatus()
356             die(1,"Killing due to freeze (KILL_FREEZE)")
357         time.sleep(0.02)
358     # Should be never reached
359     print('Wait for sleeping ends unexpectedly')
360     return False
361
362 def sendKeystringLocal(keystr, LYX_PID):
363     is_sleeping = wait_until_lyx_sleeping(LYX_PID)
364     if not is_sleeping:
365         print("Not sending \"" + keystr + "\"")
366         return
367     if not screenshot_out is None:
368         print('Making Screenshot: ' + screenshot_out + ' OF ' + infilename)
369         time.sleep(0.2)
370         intr_system('import -window root '+screenshot_out+str(x.count)+".png")
371         time.sleep(0.1)
372     actual_delay = key_delay
373     if actual_delay == '':
374         actual_delay = def_delay
375     xvpar = [xvkbd_exe]
376     if qt_frontend == 'QT5':
377         xvpar.extend(["-jump-pointer", "-no-back-pointer"])
378     else:
379         xvpar.extend(["-xsendevent"])
380     if lyx_other_window_name is None:
381         xvpar.extend(["-window", lyx_window_name])
382     else:
383         xvpar.extend(["-window", lyx_other_window_name])
384     xvpar.extend(["-delay", actual_delay, "-text", keystr])
385     print("Sending \"" + keystr + "\"")
386     subprocess.call(xvpar, stdout = FNULL, stderr = FNULL)
387     sys.stdout.flush()
388
389 def extractmultiple(line, regex):
390     #print("extractmultiple " + line)
391     res = ["", ""]
392     m = regex.match(line)
393     if m:
394         chr = m.group(1)
395         if m.group(2) == "":
396             res[0] = chr
397             res[1] = ""
398         else:
399             norm = extractmultiple(m.group(2), regex)
400             res[0] = chr + norm[0]
401             res[1] = norm[1]
402     else:
403         res[0] = ""
404         res[1] = line
405     return res
406
407 normal_re = re.compile(r'^([^\\]|\\\\)(.*)$')
408 def extractnormal(line):
409     # collect non-special chars from start of line
410     return extractmultiple(line, normal_re)
411
412 modifier_re = re.compile(r'^(\\[CAS])(.+)$')
413 def extractmodifiers(line):
414     # collect modifiers like '\\A' at start of line
415     return extractmultiple(line, modifier_re)
416
417 special_re = re.compile(r'^(\\\[[A-Z][a-z0-9]+\])(.*)$')
418 def extractsingle(line):
419     # check for single key following a modifier
420     # either ascii like 'a'
421     # or special like '\[Return]'
422     res = [False, "", ""]
423     m = normal_re.match(line)
424     if m:
425         res[0] = False
426         res[1] = m.group(1)
427         res[2] = m.group(2)
428     else:
429         m = special_re.match(line)
430         if m:
431             res[0] = True
432             res[1] = m.group(1)
433             res[2] = m.group(2)
434         else:
435             die(1, "Undecodable key for line \'" + line + "\"")
436     return res
437
438 def sendKeystring(line, LYX_PID):
439     if line == "":
440         return
441     normalchars = extractnormal(line)
442     line = normalchars[1]
443     if normalchars[0] != "":
444         sendKeystringLocal(normalchars[0], LYX_PID)
445     if line == "":
446         return
447     modchars = extractmodifiers(line)
448     line = modchars[1]
449     if line == "":
450         die(1, "Missing modified key")
451     modifiedchar = extractsingle(line)
452     line = modifiedchar[2]
453     special = modchars[0] != "" or modifiedchar[0]
454     sendKeystringLocal(modchars[0] + modifiedchar[1], LYX_PID)
455     if special:
456         # give the os time to update the status info (in /proc)
457         time.sleep(controlkey_delay)
458     sendKeystring(line, LYX_PID)
459
460 def system_retry(num_retry, cmd):
461     i = 0
462     rtn = intr_system(cmd, True)
463     while ( ( i < num_retry ) and ( rtn != 0) ):
464         i = i + 1
465         rtn = intr_system(cmd, True)
466         time.sleep(1)
467     if ( rtn != 0 ):
468         print("Command Failed: "+cmd)
469         die(1," EXITING!")
470
471 def RaiseWindow():
472     #intr_system("echo x-session-manager PID: $X_PID.")
473     #intr_system("echo x-session-manager open files: `lsof -p $X_PID | grep ICE-unix | wc -l`")
474     ####intr_system("wmctrl -l | ( grep '"+lyx_window_name+"' || ( killall lyx ; sleep 1 ; killall -9 lyx ))")
475     print("lyx_window_name = " + lyx_window_name + "\n")
476     intr_system("wmctrl -R '"+lyx_window_name+"' ;sleep 0.1")
477     system_retry(30, "wmctrl -i -a '"+lyx_window_name+"'")
478
479 class Shortcuts:
480
481     def __init__(self):
482         self.shortcut_entry = re.compile(r'^\s*"([^"]+)"\s*\"([^"]+)\"')
483         self.bindings = {}
484         self.unbindings = {}
485         self.bind = re.compile(r'^\s*\\(un)?bind\s+"([^"]+)"')
486         if lyx_userdir_ver is None:
487             self.dir = lyx_userdir
488         else:
489             self.dir = lyx_userdir_ver
490
491     def __UseShortcut(self, c):
492         m = self.shortcut_entry.match(c)
493         if m:
494             sh = m.group(1)
495             fkt = m.group(2)
496             self.bindings[sh] = fkt
497         else:
498             die(1, "cad shortcut spec(" + c + ")")
499
500     def __UnuseShortcut(self, c):
501         m = self.shortcut_entry.match(c)
502         if m:
503             sh = m.group(1)
504             fkt = m.group(2)
505             self.unbindings[sh] = fkt
506         else:
507             die(1, "cad shortcut spec(" + c + ")")
508
509     def __PrepareShortcuts(self):
510         if not self.dir is None:
511             tmp = tempfile.NamedTemporaryFile(suffix='.bind', delete=False)
512             try:
513                 old = open(self.dir + '/bind/user.bind', 'r')
514             except IOError as e:
515                 old = None
516             if not old is None:
517                 lines = old.read().split("\n")
518                 old.close()
519                 bindfound = False
520                 for line in lines:
521                     m = self.bind.match(line)
522                     if m:
523                         bindfound = True
524                         val = m.group(2)
525                         if val in self.bindings:
526                             if self.bindings[val] != "":
527                                 tmp.write("\\bind \"" + val + "\" \"" + self.bindings[val] + "\"\n")
528                                 self.bindings[val] = ""
529                         elif val in self.unbindings:
530                             if self.unbindings[val] != "":
531                                 tmp.write("\\unbind \"" + val + "\" \"" + self.unbindings[val] + "\"\n")
532                                 self.unbindings[val] = ""
533                         else:
534                             tmp.write(line + '\n')
535                     elif not bindfound:
536                         tmp.write(line + '\n')
537             else:
538                 tmp.writelines(
539                     '## This file is used for keytests only\n\n' +
540                     'Format 4\n\n'
541                 )
542             for val in self.bindings:
543                 if not self.bindings[val] is None:
544                     if self.bindings[val] != "":
545                         tmp.write("\\bind \"" + val + "\" \"" + self.bindings[val] + "\"\n")
546                         self.bindings[val] = ""
547             for val in self.unbindings:
548                 if not self.unbindings[val] is None:
549                     if self.unbindings[val] != "":
550                         tmp.write("\\unbind \"" + val + "\" \"" + self.unbindings[val] + "\"\n")
551                         self.unbindings[val] = ""
552             tmp.close()
553             shutil.move(tmp.name, self.dir + '/bind/user.bind')
554         else:
555             print("User dir not specified")
556
557     def dispatch(self, c):
558         if c[0:12] == 'UseShortcut ':
559             self.__UseShortcut(c[12:])
560         elif c[0:14] == 'UnuseShortcut ':
561             self.__UnuseShortcut(c[14:])
562         elif c == 'PrepareShortcuts':
563             print('Preparing usefull sortcuts for tests')
564             self.__PrepareShortcuts()
565         else:
566             return False
567         return True
568
569 lyx_pid = os.environ.get('LYX_PID')
570 print('lyx_pid: ' + str(lyx_pid) + '\n')
571 infilename = os.environ.get('KEYTEST_INFILE')
572 outfilename = os.environ.get('KEYTEST_OUTFILE')
573 max_drop = os.environ.get('MAX_DROP')
574 lyx_window_name = os.environ.get('LYX_WINDOW_NAME')
575 lyx_other_window_name = None
576 screenshot_out = os.environ.get('SCREENSHOT_OUT')
577 lyx_userdir = os.environ.get('LYX_USERDIR')
578 lyx_userdir_ver = os.environ.get('LYX_USERDIR_24x')
579 if lyx_userdir is None:
580     lyx_userdir = lyx_userdir_ver
581
582 max_loops = os.environ.get('MAX_LOOPS')
583 if max_loops is None:
584     max_loops = 3
585
586 extra_path = os.environ.get('EXTRA_PATH')
587 if not extra_path is None:
588   os.environ['PATH'] = extra_path + os.pathsep + os.environ['PATH']
589   print("Added " + extra_path + " to path")
590   print(os.environ['PATH'])
591
592 PACKAGE = os.environ.get('PACKAGE')
593 if not PACKAGE is None:
594   print("PACKAGE = " + PACKAGE + "\n")
595
596 PO_BUILD_DIR = os.environ.get('PO_BUILD_DIR')
597 if not PO_BUILD_DIR is None:
598   print("PO_BUILD_DIR = " + PO_BUILD_DIR + "\n")
599
600 lyx = os.environ.get('LYX')
601 if lyx is None:
602     lyx = "lyx"
603
604 lyx_exe = os.environ.get('LYX_EXE')
605 if lyx_exe is None:
606     lyx_exe = lyx
607
608 xvkbd_exe = os.environ.get('XVKBD_EXE')
609 if xvkbd_exe is None:
610     xvkbd_exe = "xvkbd"
611
612 qt_frontend = os.environ.get('QT_FRONTEND')
613 if qt_frontend is None:
614     qt_frontend = 'QT4'
615 if qt_frontend == 'QT5':
616     # Some tests sometimes failed with value 0.01 on Qt5.8
617     controlkey_delay = 0.4
618 else:
619     controlkey_delay = 0.4
620
621 locale_dir = os.environ.get('LOCALE_DIR')
622 if locale_dir is None:
623     locale_dir = '.'
624
625 def_delay = os.environ.get('XVKBD_DELAY')
626 if def_delay is None:
627     if qt_frontend == 'QT5':
628         def_delay = '1'
629     else:
630         def_delay = '1'
631
632 file_new_command = os.environ.get('FILE_NEW_COMMAND')
633 if file_new_command is None:
634     file_new_command = "\Afn"
635
636 ResetCommand = os.environ.get('RESET_COMMAND')
637 if ResetCommand is None:
638     ResetCommand = "\[Escape]\[Escape]\[Escape]\[Escape]" + file_new_command
639     #ResetCommand="\[Escape]\[Escape]\[Escape]\[Escape]\Cw\Cw\Cw\Cw\Cw\Afn"
640
641 if lyx_window_name is None:
642     lyx_window_name = 'LyX'
643
644 print('outfilename: ' + outfilename + '\n')
645 print('max_drop: ' + max_drop + '\n')
646
647 if infilename is None:
648     print('infilename is None\n')
649     x = CommandSource()
650     print('Using x=CommandSource\n')
651 else:
652     print('infilename: ' + infilename + '\n')
653     probability_we_drop_a_command = random.uniform(0, float(max_drop))
654     print('probability_we_drop_a_command: ')
655     print('%s' % probability_we_drop_a_command)
656     print('\n')
657     x = CommandSourceFromFile(infilename, probability_we_drop_a_command)
658     print('Using x=CommandSourceFromFile\n')
659
660 outfile = open(outfilename, 'w')
661
662 if not lyx_pid is None:
663     RaiseWindow()
664     # Next command is language dependent
665     #sendKeystring("\Afn", lyx_pid)
666
667 write_commands = True
668 failed = False
669 lineempty = re.compile(r'^\s*$')
670 marked = ControlFile()
671 shortcuts = Shortcuts()
672 while not failed:
673     #intr_system('echo -n LOADAVG:; cat /proc/loadavg')
674     c = x.getCommand()
675     if c is None:
676         break
677
678     # Do not strip trailing spaces, only check for 'empty' lines
679     if lineempty.match(c):
680         continue
681     outfile.writelines(c + '\n')
682     outfile.flush()
683     if marked.dispatch(c):
684         continue
685     elif shortcuts.dispatch(c):
686         continue
687     if c[0] == '#':
688         print("Ignoring comment line: " + c)
689     elif c[0:9] == 'TestBegin':
690         print("\n")
691         lyx_pid=get_proc_pid(lyx)
692         if lyx_pid != "":
693             print("Found running instance(s) of LyX: " + lyx_pid + ": killing them all\n")
694             intr_system("killall " + lyx, True)
695             time.sleep(0.5)
696             intr_system("killall -KILL " + lyx, True)
697             time.sleep(0.2)
698         print("Starting LyX . . .")
699         if lyx_userdir is None:
700             intr_system(lyx_exe + c[9:] + "&")
701         else:
702             intr_system(lyx_exe + " -userdir " + lyx_userdir + " " + c[9:] + "&")
703         count = 10
704         old_lyx_pid = "-7"
705         old_lyx_window_name = None
706         print("Waiting for LyX to show up . . .")
707         while count > 0:
708             lyx_pid=get_proc_pid(lyx)
709             if lyx_pid != old_lyx_pid:
710                 print('lyx_pid=' + lyx_pid)
711                 old_lyx_pid = lyx_pid
712             if lyx_pid != "":
713                 lyx_window_name=get_proc_win_id(lyx_pid, "")
714                 if not lyx_window_name is None:
715                     if old_lyx_window_name != lyx_window_name:
716                         print('lyx_win=' + lyx_window_name, '\n')
717                         old_lyx_window_name = lyx_window_name
718                     break
719             else:
720                 count = count - 1
721             time.sleep(0.5)
722         if count <= 0:
723             print('Timeout: could not start ' + lyx_exe, '\n')
724             sys.stdout.flush()
725             failed = True
726         else:
727             print('lyx_pid: ' + lyx_pid)
728             print('lyx_win: ' + lyx_window_name)
729             dead_expected = False
730             sendKeystring("\C\[Home]", lyx_pid)
731     elif c[0:5] == 'Sleep':
732         print("Sleeping for " + c[6:] + " seconds")
733         time.sleep(float(c[6:]))
734     elif c[0:4] == 'Exec':
735         cmd = c[5:].rstrip()
736         intr_system(cmd)
737     elif c == 'Loop':
738         outfile.close()
739         outfile = open(outfilename + '+', 'w')
740         print('Now Looping')
741     elif c == 'RaiseLyx':
742         print('Raising Lyx')
743         RaiseWindow()
744     elif c[0:4] == 'KK: ':
745         if lyx_exists():
746             sendKeystring(c[4:], lyx_pid)
747         else:
748             ##intr_system('killall lyx; sleep 2 ; killall -9 lyx')
749             if lyx_pid is None:
750               die(1, 'No path /proc/xxxx/status, exiting')
751             else:
752               die(1, 'No path /proc/' + lyx_pid + '/status, exiting')
753     elif c[0:4] == 'KD: ':
754         key_delay = c[4:].rstrip('\n')
755         print('Setting DELAY to ' + key_delay)
756     elif c == 'Loop':
757         RaiseWindow()
758         sendKeystring(ResetCommand, lyx_pid)
759     elif c[0:6] == 'Assert':
760         cmd = c[7:].rstrip()
761         result = intr_system(cmd, True)
762         failed = failed or (result != 0)
763         print("result=" + str(result) + ", failed=" + str(failed))
764     elif c[0:15] == 'TestEndWithKill':
765         marked.closeall()
766         cmd = c[16:].rstrip()
767         if lyx_dead(lyx_pid):
768             print("LyX instance not found because of crash or assert !\n")
769             failed = True
770         else:
771             print("    ------------    Forcing kill of lyx instance: " + str(lyx_pid) + "    ------------")
772             # This line below is there only to allow lyx to update its log-file
773             sendKeystring("\[Escape]", lyx_pid)
774             dead_expected = True
775             while not lyx_dead(lyx_pid):
776                 intr_system("kill -9 " + str(lyx_pid), True);
777                 time.sleep(0.5)
778             if cmd != "":
779                 print("Executing " + cmd)
780                 result = intr_system(cmd, True)
781                 failed = failed or (result != 0)
782                 print("result=" + str(result) + ", failed=" + str(failed))
783             else:
784                 print("failed=" + str(failed))
785     elif c[0:7] == 'TestEnd':
786          #lyx_other_window_name = None
787         if lyx_dead(lyx_pid):
788             print("LyX instance not found because of crash or assert !\n")
789             marked.closeall()
790             failed = True
791         else:
792             print("    ------------    Forcing quit of lyx instance: " + str(lyx_pid) + "    ------------")
793             # \[Escape]+ should work as RESET focus to main window
794             sendKeystring("\[Escape]\[Escape]\[Escape]\[Escape]", lyx_pid)
795             # now we should be outside any dialog
796             # and so the function lyx-quit should work
797             sendKeystring("\Cq", lyx_pid)
798             marked.dispatch('CP: action=lyx-quit')
799             marked.dispatch('CC:')
800             time.sleep(0.5)
801             dead_expected = True
802             is_sleeping = wait_until_lyx_sleeping(lyx_pid)
803             if is_sleeping:
804                 print('wait_until_lyx_sleeping() indicated "sleeping"')
805                 # For a short time lyx-status is 'sleeping', even if it is nearly dead.
806                 # Without the wait below, the \[Tab]-char is sent to nirvana
807                 # causing a 'beep'
808                 time.sleep(0.5)
809                 # probably waiting for Save/Discard/Abort, we select 'Discard'
810                 sendKeystring("\[Tab]\[Return]", lyx_pid)
811                 lcount = 0
812             else:
813                 lcount = 1
814             while not lyx_dead(lyx_pid):
815                 lcount = lcount + 1
816                 if lcount > 20:
817                     print("LyX still up, killing process and waiting for it to die...\n")
818                     intr_system("kill -9 " + str(lyx_pid), True);
819                 time.sleep(0.5)
820         cmd = c[8:].rstrip()
821         if cmd != "":
822             print("Executing " + cmd)
823             result = intr_system(cmd, True)
824             failed = failed or (result != 0)
825             print("result=" + str(result) + ", failed=" + str(failed))
826         else:
827             print("failed=" + str(failed))
828     elif c[0:4] == 'Lang':
829         lang = c[5:].rstrip()
830         print("Setting LANG=" + lang)
831         os.environ['LANG'] = lang
832         os.environ['LC_ALL'] = lang
833 # If it doesn't exist, create a link <locale_dir>/<country-code>/LC_MESSAGES/lyx<version-suffix>.mo
834 # pointing to the corresponding .gmo file. Needed to let lyx find the right translation files.
835 # See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg165613.html
836         idx = lang.rfind(".")
837         if idx != -1:
838             ccode = lang[0:idx]
839         else:
840             ccode = lang
841
842         print("Setting LANGUAGE=" + ccode)
843         os.environ['LANGUAGE'] = ccode
844
845         idx = lang.find("_")
846         if idx != -1:
847             short_code = lang[0:idx]
848         else:
849             short_code = ccode
850         lyx_dir = os.popen("dirname \"" + lyx_exe + "\"").read().rstrip()
851         if PACKAGE is None:
852           # on cmake-build there is no Makefile in this directory
853           # so PACKAGE has to be provided
854           if os.path.exists(lyx_dir + "/Makefile"):
855             print("Executing: grep 'PACKAGE =' " + lyx_dir + "/Makefile | sed -e 's/PACKAGE = \(.*\)/\\1/'")
856             lyx_name = os.popen("grep 'PACKAGE =' " + lyx_dir + "/Makefile | sed -e 's/PACKAGE = \(.*\)/\\1/'").read().rstrip()
857           else:
858             print('Could not determine PACKAGE name needed for translations\n')
859             failed = True
860         else:
861             lyx_name = PACKAGE
862         intr_system("mkdir -p " + locale_dir + "/" + ccode + "/LC_MESSAGES")
863         intr_system("rm -f " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
864         if PO_BUILD_DIR is None:
865             if lyx_dir[0:3] == "../":
866                 rel_dir = "../../" + lyx_dir
867             else:
868                 rel_dir = lyx_dir
869             intr_system("ln -s " + rel_dir + "/../po/" + short_code + ".gmo " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
870         else:
871             intr_system("ln -s " + PO_BUILD_DIR + "/" + short_code + ".gmo " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
872     else:
873         print("Unrecognised Command '" + c + "'\n")
874         failed = True
875
876 print("Test case terminated: ", end = '')
877 if failed:
878     die(1,"FAIL")
879 else:
880     die(0, "Ok")