]> git.lyx.org Git - features.git/blob - development/autotests/keytest.py
keytests: Move shortcut handling into own class
[features.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]):\s*(.*)$')
171         self.fileformat = re.compile(r'^((\>\>?)[,\s]\s*)?([^\s]+)\s*$')
172         self.cntrname = None
173         self.cntrfile = None
174
175     def open(self, filename):
176         if not self.cntrfile is None:
177             self.cntrfile.close()
178             self.cntrfile = None
179             self.cntrname = None
180         m = self.fileformat.match(filename)
181         if m:
182             type = m.group(2)
183             filename = m.group(3)
184             if type == '>>':
185                 append = True
186             else:
187                 append = False
188         else:
189             append = False
190         self.cntrname = filename
191         if append:
192             self.cntrfile = open(filename, 'a')
193         else:
194             self.cntrfile = open(filename, 'w')
195
196     def close(self):
197         if not self.cntrfile is None:
198             self.cntrfile.close()
199             self.cntrfile = None
200             self.cntrname = None
201     # make the method below 'private'
202     def __addline(self, pat):
203         self.cntrfile.writelines(pat + "\n")
204
205     def getfname(self):
206         return self.cntrname
207
208     def dispatch(self, c):
209         m = self.control.match(c)
210         if not m:
211             return False
212         command = m.group(1)
213         text = m.group(2)
214         if command == "CO":
215             self.open(text);
216         elif command == "CC":
217             self.close()
218         else:
219             if not self.cntrfile is None:
220                 if command == "CN":
221                     self.__addline("Comment: " + text)
222                 elif command == "CP":
223                     self.__addline("Simple: " + text)
224                 elif command == "Cp":
225                     self.__addline("ErrSimple: " + text)
226                 elif command == "CR":
227                     self.__addline("Regex: " + text)
228                 elif command == "Cr":
229                     self.__addline("ErrRegex: " + text)
230                 else:
231                     die(1,"Error, Unrecognised Command '" + command + "'")
232         return True
233
234
235 def get_proc_pid(proc_name):
236     pid=os.popen("pidof " + proc_name).read().rstrip()
237     return pid
238
239 wlistreg = re.compile(r'^(0x[0-9a-f]{5,9})\s+[^\s]+\s+([0-9]+)\s.*$')
240 def get_proc_win_id(pid, ignoreid):
241     nlist = os.popen("wmctrl -l -p").read()
242     wlist = nlist.split("\n")
243     for item in wlist:
244         m = wlistreg.match(item)
245         if m:
246             win_id = m.group(1)
247             win_pid = m.group(2)
248             if win_pid == pid:
249                 if win_id != ignoreid:
250                     return win_id
251     return None
252
253 def lyx_exists():
254     if lyx_pid is None:
255         return False
256     fname = '/proc/' + lyx_pid + '/status'
257     return os.path.exists(fname)
258
259
260 # Interruptible os.system()
261 def intr_system(cmd, ignore_err = False):
262     print("Executing " + cmd)
263     # Assure the output of cmd does not overhaul
264     sys.stdout.flush()
265     ret = os.system(cmd)
266     if os.WIFSIGNALED(ret):
267         raise KeyboardInterrupt
268     if ret != 0 and not ignore_err:
269         raise BaseException("command failed:" + cmd)
270     return ret
271
272 statreg = re.compile(r'^State:.*\(([a-z]+)\)')
273
274 resstatus = []
275 def printresstatus():
276     for line in resstatus:
277         line = line.rstrip()
278         print("    " + line.rstrip())
279     print('End of /proc-lines')
280
281 def lyx_status_retry(pid):
282     resstatus = []
283     if pid is None:
284         print('Pid is None')
285         return "dead"
286     fname = '/proc/' + pid + '/status'
287     status = "dead"
288     try:
289         f = open(fname)
290         found = False
291         for line in f:
292             resstatus.extend([line])
293             m = statreg.match(line)
294             if m:
295                 status = m.group(1)
296                 found = True
297         f.close()
298         if not found:
299             return "retry"
300         return status
301     except IOError as e:
302         print("I/O error({0}): {1}".format(e.errno, e.strerror))
303         return "dead"
304     except:
305         print("Unexpected error:", sys.exc_info()[0])
306         return "dead"
307     print('This should not happen')
308     return status
309
310 def lyx_status(pid):
311     count = 0
312     while 1:
313         status = lyx_status_retry(pid)
314         if status != "retry":
315             break
316         if count == 0:
317             print('Retrying check for status')
318         count += 1
319         time.sleep(0.01)
320     if count > 1:
321         print('Retried to read status ' + str(count) + ' times')
322     #print('lys_status() returning ' + status)
323     return status
324
325 # Return true if LyX (identified via lyx_pid) is sleeping
326 def lyx_sleeping(LYX_PID):
327     return lyx_status(LYX_PID) == "sleeping"
328
329 # Return true if LyX (identified via lyx_pid) is zombie
330 def lyx_zombie(LYX_PID):
331     return lyx_status(LYX_PID) == "zombie"
332
333 def lyx_dead(LYX_PID):
334     status = lyx_status(LYX_PID)
335     return (status == "dead") or (status == "zombie")
336
337 def wait_until_lyx_sleeping(LYX_PID):
338     before_secs = time.time()
339     while True:
340         status = lyx_status(LYX_PID)
341         if status == "sleeping":
342             return True
343         if (status == "dead") or (status == "zombie"):
344             printresstatus()
345             if dead_expected:
346                 print('Lyx died while waiting for status == sleeping')
347                 return False
348             else:
349                 die(1,"Lyx is dead, exiting")
350         if time.time() - before_secs > 180:
351             # Do profiling, but sysprof has no command line interface?
352             # intr_system("killall -KILL lyx")
353             printresstatus()
354             die(1,"Killing due to freeze (KILL_FREEZE)")
355         time.sleep(0.02)
356     # Should be never reached
357     print('Wait for sleeping ends unexpectedly')
358     return False
359
360 def sendKeystringLocal(keystr, LYX_PID):
361     is_sleeping = wait_until_lyx_sleeping(LYX_PID)
362     if not is_sleeping:
363         print("Not sending \"" + keystr + "\"")
364         return
365     if not screenshot_out is None:
366         print('Making Screenshot: ' + screenshot_out + ' OF ' + infilename)
367         time.sleep(0.2)
368         intr_system('import -window root '+screenshot_out+str(x.count)+".png")
369         time.sleep(0.1)
370     actual_delay = key_delay
371     if actual_delay == '':
372         actual_delay = def_delay
373     xvpar = [xvkbd_exe]
374     if qt_frontend == 'QT5':
375         xvpar.extend(["-jump-pointer", "-no-back-pointer"])
376     else:
377         xvpar.extend(["-xsendevent"])
378     if lyx_other_window_name is None:
379         xvpar.extend(["-window", lyx_window_name])
380     else:
381         xvpar.extend(["-window", lyx_other_window_name])
382     xvpar.extend(["-delay", actual_delay, "-text", keystr])
383     print("Sending \"" + keystr + "\"")
384     subprocess.call(xvpar, stdout = FNULL, stderr = FNULL)
385     sys.stdout.flush()
386
387 Axreg = re.compile(r'^(.*)\\Ax([^\\]*)(.*)$')
388 returnreg = re.compile(r'(\\\[[A-Z][a-z0-9]+\])(.*)$')
389
390 # recursive wrapper around sendKeystringLocal()
391 # handling \Ax-entries
392 def sendKeystringAx(line, LYX_PID):
393     global key_delay
394     saved_delay = key_delay
395     m = Axreg.match(line)
396     if m:
397         prefix = m.group(1)
398         content = m.group(2)
399         rest = m.group(3);
400         if prefix != "":
401             # since (.*) is greedy, check prefix for '\Ax' again
402             sendKeystringAx(prefix, LYX_PID)
403         sendKeystringLocal('\Ax', LYX_PID)
404         time.sleep(0.1)
405         m2 = returnreg.match(rest)
406         if m2:
407             line = m2.group(2)
408             ctrlk = m2.group(1)
409             key_delay = "1"
410             sendKeystringLocal(content + ctrlk, LYX_PID)
411             key_delay = saved_delay
412             time.sleep(controlkey_delay)
413             if line != "":
414                 sendKeystringLocal(line, LYX_PID)
415         else:
416             if content != "":
417                 sendKeystringLocal(content, LYX_PID)
418             if rest != "":
419                 sendKeystringLocal(rest, LYX_PID)
420     else:
421         if line != "":
422             sendKeystringLocal(line, LYX_PID)
423
424 specialkeyreg = re.compile(r'(.+)(\\[AC]([a-zA-Z]|\\\[[A-Z][a-z0-9]+\]).*)$')
425 # Split line at start of each meta or controll char
426
427 def sendKeystringAC(line, LYX_PID):
428     m = specialkeyreg.match(line)
429     if m:
430         first = m.group(1)
431         second = m.group(2)
432         sendKeystringAC(first, LYX_PID)
433         sendKeystringAC(second, LYX_PID)
434     else:
435         sendKeystringAx(line, LYX_PID)
436
437 controlkeyreg = re.compile(r'^(.*\\\[[A-Z][a-z0-9]+\])(.*\\\[[A-Z][a-z0-9]+\])(.*)$')
438 # Make sure, only one of \[Return], \[Tab], \[Down], \[Home] etc are in one sent line
439 # e.g. split the input line on each keysym
440 def sendKeystringRT(line, LYX_PID):
441     m = controlkeyreg.match(line)
442     if m:
443         first = m.group(1)
444         second = m.group(2)
445         third = m.group(3)
446         sendKeystringRT(first, LYX_PID)
447         time.sleep(controlkey_delay)
448         sendKeystringRT(second, LYX_PID)
449         time.sleep(controlkey_delay)
450         if third != "":
451             sendKeystringRT(third, LYX_PID)
452     else:
453         sendKeystringAC(line, LYX_PID)
454
455 def system_retry(num_retry, cmd):
456     i = 0
457     rtn = intr_system(cmd, True)
458     while ( ( i < num_retry ) and ( rtn != 0) ):
459         i = i + 1
460         rtn = intr_system(cmd, True)
461         time.sleep(1)
462     if ( rtn != 0 ):
463         print("Command Failed: "+cmd)
464         die(1," EXITING!")
465
466 def RaiseWindow():
467     #intr_system("echo x-session-manager PID: $X_PID.")
468     #intr_system("echo x-session-manager open files: `lsof -p $X_PID | grep ICE-unix | wc -l`")
469     ####intr_system("wmctrl -l | ( grep '"+lyx_window_name+"' || ( killall lyx ; sleep 1 ; killall -9 lyx ))")
470     print("lyx_window_name = " + lyx_window_name + "\n")
471     intr_system("wmctrl -R '"+lyx_window_name+"' ;sleep 0.1")
472     system_retry(30, "wmctrl -i -a '"+lyx_window_name+"'")
473
474 class Shortcuts:
475
476     def __init__(self):
477         self.shortcut_entry = re.compile(r'^\s*"([^"]+)"\s*\"([^"]+)\"')
478         self.bindings = {}
479         self.bind = re.compile(r'^\s*\\bind\s+"([^"]+)"')
480         if lyx_userdir_ver is None:
481             self.dir = lyx_userdir
482         else:
483             self.dir = lyx_userdir_ver
484
485     def __UseShortcut(self, c):
486         m = self.shortcut_entry.match(c)
487         if m:
488             sh = m.group(1)
489             fkt = m.group(2)
490             self.bindings[sh] = fkt
491         else:
492             die(1, "cad shortcut spec(" + c + ")")
493
494     def __PrepareShortcuts(self):
495         if not self.dir is None:
496             tmp = tempfile.NamedTemporaryFile(suffix='.bind', delete=False)
497             try:
498                 old = open(self.dir + '/bind/user.bind', 'r')
499             except IOError as e:
500                 old = None
501             if not old is None:
502                 lines = old.read().split("\n")
503                 old.close()
504                 bindfound = False
505                 for line in lines:
506                     m = self.bind.match(line)
507                     if m:
508                         bindfound = True
509                         val = m.group(1)
510                         if val in self.bindings:
511                             if self.bindings[val] != "":
512                                 tmp.write("\\bind \"" + val + "\" \"" + self.bindings[val] + "\"\n")
513                                 self.bindings[val] = ""
514                         else:
515                             tmp.write(line + '\n')
516                     elif not bindfound:
517                         tmp.write(line + '\n')
518             else:
519                 tmp.writelines(
520                     '## This file is used for keytests only\n\n' +
521                     'Format 4\n\n'
522                 )
523             for val in self.bindings:
524                 if not self.bindings[val] is None:
525                     if  self.bindings[val] != "":
526                         tmp.write("\\bind \"" + val + "\" \"" + self.bindings[val] + "\"\n")
527                         self.bindings[val] = ""
528             tmp.close()
529             shutil.move(tmp.name, self.dir + '/bind/user.bind')
530         else:
531             print("User dir not specified")
532
533     def dispatch(self, c):
534         if c[0:12] == 'UseShortcut ':
535             self.__UseShortcut(c[12:])
536         elif c == 'PrepareShortcuts':
537             print('Preparing usefull sortcuts for tests')
538             self.__PrepareShortcuts()
539         else:
540             return False
541         return True
542
543 lyx_pid = os.environ.get('LYX_PID')
544 print('lyx_pid: ' + str(lyx_pid) + '\n')
545 infilename = os.environ.get('KEYTEST_INFILE')
546 outfilename = os.environ.get('KEYTEST_OUTFILE')
547 max_drop = os.environ.get('MAX_DROP')
548 lyx_window_name = os.environ.get('LYX_WINDOW_NAME')
549 lyx_other_window_name = None
550 screenshot_out = os.environ.get('SCREENSHOT_OUT')
551 lyx_userdir = os.environ.get('LYX_USERDIR')
552 lyx_userdir_ver = os.environ.get('LYX_USERDIR_23x')
553
554 max_loops = os.environ.get('MAX_LOOPS')
555 if max_loops is None:
556     max_loops = 3
557
558 extra_path = os.environ.get('EXTRA_PATH')
559 if not extra_path is None:
560   os.environ['PATH'] = extra_path + os.pathsep + os.environ['PATH']
561   print("Added " + extra_path + " to path")
562   print(os.environ['PATH'])
563
564 PACKAGE = os.environ.get('PACKAGE')
565 if not PACKAGE is None:
566   print("PACKAGE = " + PACKAGE + "\n")
567
568 PO_BUILD_DIR = os.environ.get('PO_BUILD_DIR')
569 if not PO_BUILD_DIR is None:
570   print("PO_BUILD_DIR = " + PO_BUILD_DIR + "\n")
571
572 lyx = os.environ.get('LYX')
573 if lyx is None:
574     lyx = "lyx"
575
576 lyx_exe = os.environ.get('LYX_EXE')
577 if lyx_exe is None:
578     lyx_exe = lyx
579
580 xvkbd_exe = os.environ.get('XVKBD_EXE')
581 if xvkbd_exe is None:
582     xvkbd_exe = "xvkbd"
583
584 qt_frontend = os.environ.get('QT_FRONTEND')
585 if qt_frontend is None:
586     qt_frontend = 'QT4'
587 if qt_frontend == 'QT5':
588     controlkey_delay = 0.01
589 else:
590     controlkey_delay = 0.4
591
592 locale_dir = os.environ.get('LOCALE_DIR')
593 if locale_dir is None:
594     locale_dir = '.'
595
596 def_delay = os.environ.get('XVKBD_DELAY')
597 if def_delay is None:
598     if qt_frontend == 'QT5':
599         def_delay = '1'
600     else:
601         def_delay = '1'
602
603 file_new_command = os.environ.get('FILE_NEW_COMMAND')
604 if file_new_command is None:
605     file_new_command = "\Afn"
606
607 ResetCommand = os.environ.get('RESET_COMMAND')
608 if ResetCommand is None:
609     ResetCommand = "\[Escape]\[Escape]\[Escape]\[Escape]" + file_new_command
610     #ResetCommand="\[Escape]\[Escape]\[Escape]\[Escape]\Cw\Cw\Cw\Cw\Cw\Afn"
611
612 if lyx_window_name is None:
613     lyx_window_name = 'LyX'
614
615 print('outfilename: ' + outfilename + '\n')
616 print('max_drop: ' + max_drop + '\n')
617
618 if infilename is None:
619     print('infilename is None\n')
620     x = CommandSource()
621     print('Using x=CommandSource\n')
622 else:
623     print('infilename: ' + infilename + '\n')
624     probability_we_drop_a_command = random.uniform(0, float(max_drop))
625     print('probability_we_drop_a_command: ')
626     print('%s' % probability_we_drop_a_command)
627     print('\n')
628     x = CommandSourceFromFile(infilename, probability_we_drop_a_command)
629     print('Using x=CommandSourceFromFile\n')
630
631 outfile = open(outfilename, 'w')
632
633 if not lyx_pid is None:
634     RaiseWindow()
635     # Next command is language dependent
636     #sendKeystringRT("\Afn", lyx_pid)
637
638 write_commands = True
639 failed = False
640 lineempty = re.compile(r'^\s*$')
641 marked = ControlFile()
642 shortcuts = Shortcuts()
643 while not failed:
644     #intr_system('echo -n LOADAVG:; cat /proc/loadavg')
645     c = x.getCommand()
646     if c is None:
647         break
648
649     # Do not strip trailing spaces, only check for 'empty' lines
650     if lineempty.match(c):
651         continue
652     outfile.writelines(c + '\n')
653     outfile.flush()
654     if marked.dispatch(c):
655         continue
656     elif shortcuts.dispatch(c):
657         continue
658     if c[0] == '#':
659         print("Ignoring comment line: " + c)
660     elif c[0:9] == 'TestBegin':
661         print("\n")
662         lyx_pid=get_proc_pid(lyx)
663         if lyx_pid != "":
664             print("Found running instance(s) of LyX: " + lyx_pid + ": killing them all\n")
665             intr_system("killall " + lyx, True)
666             time.sleep(0.5)
667             intr_system("killall -KILL " + lyx, True)
668             time.sleep(0.2)
669         print("Starting LyX . . .")
670         if lyx_userdir is None:
671             intr_system(lyx_exe + c[9:] + "&")
672         else:
673             intr_system(lyx_exe + " -userdir " + lyx_userdir + " " + c[9:] + "&")
674         count = 10
675         old_lyx_pid = "-7"
676         old_lyx_window_name = None
677         print("Waiting for LyX to show up . . .")
678         while count > 0:
679             lyx_pid=get_proc_pid(lyx)
680             if lyx_pid != old_lyx_pid:
681                 print('lyx_pid=' + lyx_pid)
682                 old_lyx_pid = lyx_pid
683             if lyx_pid != "":
684                 lyx_window_name=get_proc_win_id(lyx_pid, "")
685                 if not lyx_window_name is None:
686                     if old_lyx_window_name != lyx_window_name:
687                         print('lyx_win=' + lyx_window_name, '\n')
688                         old_lyx_window_name = lyx_window_name
689                     break
690             else:
691                 count = count - 1
692             time.sleep(0.5)
693         if count <= 0:
694             print('Timeout: could not start ' + lyx_exe, '\n')
695             sys.stdout.flush()
696             failed = True
697         else:
698             print('lyx_pid: ' + lyx_pid)
699             print('lyx_win: ' + lyx_window_name)
700             dead_expected = False
701             sendKeystringLocal("\C\[Home]", lyx_pid)
702             time.sleep(controlkey_delay)
703     elif c[0:5] == 'Sleep':
704         print("Sleeping for " + c[6:] + " seconds")
705         time.sleep(float(c[6:]))
706     elif c[0:4] == 'Exec':
707         cmd = c[5:].rstrip()
708         intr_system(cmd)
709     elif c == 'Loop':
710         outfile.close()
711         outfile = open(outfilename + '+', 'w')
712         print('Now Looping')
713     elif c == 'RaiseLyx':
714         print('Raising Lyx')
715         RaiseWindow()
716     elif c[0:4] == 'KK: ':
717         if lyx_exists():
718             sendKeystringRT(c[4:], lyx_pid)
719         else:
720             ##intr_system('killall lyx; sleep 2 ; killall -9 lyx')
721             if lyx_pid is None:
722               die(1, 'No path /proc/xxxx/status, exiting')
723             else:
724               die(1, 'No path /proc/' + lyx_pid + '/status, exiting')
725     elif c[0:4] == 'KD: ':
726         key_delay = c[4:].rstrip('\n')
727         print('Setting DELAY to ' + key_delay)
728     elif c == 'Loop':
729         RaiseWindow()
730         sendKeystringRT(ResetCommand, lyx_pid)
731     elif c[0:6] == 'Assert':
732         cmd = c[7:].rstrip()
733         result = intr_system(cmd, True)
734         failed = failed or (result != 0)
735         print("result=" + str(result) + ", failed=" + str(failed))
736     elif c[0:15] == 'TestEndWithKill':
737         marked.close()
738         cmd = c[16:].rstrip()
739         if lyx_dead(lyx_pid):
740             print("LyX instance not found because of crash or assert !\n")
741             failed = True
742         else:
743             print("    ------------    Forcing kill of lyx instance: " + str(lyx_pid) + "    ------------")
744             # This line below is there only to allow lyx to update its log-file
745             sendKeystringLocal("\[Escape]", lyx_pid)
746             dead_expected = True
747             while not lyx_dead(lyx_pid):
748                 intr_system("kill -9 " + str(lyx_pid), True);
749                 time.sleep(0.5)
750             if cmd != "":
751                 print("Executing " + cmd)
752                 result = intr_system(cmd, True)
753                 failed = failed or (result != 0)
754                 print("result=" + str(result) + ", failed=" + str(failed))
755             else:
756                 print("failed=" + str(failed))
757     elif c[0:7] == 'TestEnd':
758          #lyx_other_window_name = None
759         if lyx_dead(lyx_pid):
760             print("LyX instance not found because of crash or assert !\n")
761             marked.close()
762             failed = True
763         else:
764             print("    ------------    Forcing quit of lyx instance: " + str(lyx_pid) + "    ------------")
765             # \[Escape]+ should work as RESET focus to main window
766             sendKeystringAx("\[Escape]\[Escape]\[Escape]\[Escape]", lyx_pid)
767             time.sleep(controlkey_delay)
768             # now we should be outside any dialog
769             # and so the function lyx-quit should work
770             sendKeystringLocal("\Cq", lyx_pid)
771             marked.dispatch('CP: action=lyx-quit')
772             marked.close()
773             time.sleep(0.5)
774             dead_expected = True
775             is_sleeping = wait_until_lyx_sleeping(lyx_pid)
776             if is_sleeping:
777                 print('wait_until_lyx_sleeping() indicated "sleeping"')
778                 # For a short time lyx-status is 'sleeping', even if it is nearly dead.
779                 # Without the wait below, the \[Tab]-char is sent to nirvana
780                 # causing a 'beep'
781                 time.sleep(0.5)
782                 # probably waiting for Save/Discard/Abort, we select 'Discard'
783                 sendKeystringRT("\[Tab]\[Return]", lyx_pid)
784                 lcount = 0
785             else:
786                 lcount = 1
787             while not lyx_dead(lyx_pid):
788                 lcount = lcount + 1
789                 if lcount > 20:
790                     print("LyX still up, killing process and waiting for it to die...\n")
791                     intr_system("kill -9 " + str(lyx_pid), True);
792                 time.sleep(0.5)
793         cmd = c[8:].rstrip()
794         if cmd != "":
795             print("Executing " + cmd)
796             result = intr_system(cmd, True)
797             failed = failed or (result != 0)
798             print("result=" + str(result) + ", failed=" + str(failed))
799         else:
800             print("failed=" + str(failed))
801     elif c[0:4] == 'Lang':
802         lang = c[5:].rstrip()
803         print("Setting LANG=" + lang)
804         os.environ['LANG'] = lang
805         os.environ['LC_ALL'] = lang
806 # If it doesn't exist, create a link <locale_dir>/<country-code>/LC_MESSAGES/lyx<version-suffix>.mo
807 # pointing to the corresponding .gmo file. Needed to let lyx find the right translation files.
808 # See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg165613.html
809         idx = lang.rfind(".")
810         if idx != -1:
811             ccode = lang[0:idx]
812         else:
813             ccode = lang
814
815         print("Setting LANGUAGE=" + ccode)
816         os.environ['LANGUAGE'] = ccode
817
818         idx = lang.find("_")
819         if idx != -1:
820             short_code = lang[0:idx]
821         else:
822             short_code = ccode
823         lyx_dir = os.popen("dirname \"" + lyx_exe + "\"").read().rstrip()
824         if PACKAGE is None:
825           # on cmake-build there is no Makefile in this directory
826           # so PACKAGE has to be provided
827           if os.path.exists(lyx_dir + "/Makefile"):
828             print("Executing: grep 'PACKAGE =' " + lyx_dir + "/Makefile | sed -e 's/PACKAGE = \(.*\)/\\1/'")
829             lyx_name = os.popen("grep 'PACKAGE =' " + lyx_dir + "/Makefile | sed -e 's/PACKAGE = \(.*\)/\\1/'").read().rstrip()
830           else:
831             print('Could not determine PACKAGE name needed for translations\n')
832             failed = True
833         else:
834           lyx_name = PACKAGE
835         intr_system("mkdir -p " + locale_dir + "/" + ccode + "/LC_MESSAGES")
836         intr_system("rm -f " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
837         if PO_BUILD_DIR is None:
838             if lyx_dir[0:3] == "../":
839                 rel_dir = "../../" + lyx_dir
840             else:
841                 rel_dir = lyx_dir
842             intr_system("ln -s " + rel_dir + "/../po/" + short_code + ".gmo " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
843         else:
844             intr_system("ln -s " + PO_BUILD_DIR + "/" + short_code + ".gmo " + locale_dir + "/" + ccode + "/LC_MESSAGES/" + lyx_name + ".mo")
845     else:
846         print("Unrecognised Command '" + c + "'\n")
847         failed = True
848
849 print("Test case terminated: ", end = '')
850 if failed:
851     die(1,"FAIL")
852 else:
853     die(0, "Ok")