forked from erkyrath/plotex
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregtest.py
More file actions
1451 lines (1330 loc) · 52.6 KB
/
Copy pathregtest.py
File metadata and controls
1451 lines (1330 loc) · 52.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# RegTest: a really simple IF regression tester.
# Version 1.13
# Andrew Plotkin <erkyrath@eblong.com>
# This script is in the public domain.
#
# For a full description, see <http://eblong.com/zarf/plotex/regtest.html>
#
# (This software is not connected to PlotEx; I'm just distributing them
# from the same folder.)
# We use the print() function for Python 2/3 compatibility
from __future__ import print_function
# We use the Py2 unichr() function. In Py3 there is no such function,
# but we define a back-polyfill. (I'm lazy.)
try:
unichr(32)
except NameError:
unichr = chr
# In Py2, we'll need a bit of extra decoding.
py2_readline = False
try:
unicode
py2_readline = True
except:
pass
import sys
import os
import optparse
import select
import time
import fnmatch
import subprocess
import re
import types
gamefile = None
terppath = None
terpargs = []
terpformat = 'cheap' # 'cheap', 'rem', 'remsingle'
precommands = []
checkclasses = []
testmap = {}
testls = []
totalerrors = 0
popt = optparse.OptionParser()
popt.add_option('-g', '--game',
action='store', dest='gamefile',
help='game to test')
popt.add_option('-i', '--interpreter', '--terp',
action='store', dest='terppath',
help='interpreter to execute')
popt.add_option('-l', '--list',
action='store_true', dest='listonly',
help='list all tests (or all matching tests)')
popt.add_option('-p', '--pre', '--precommand',
action='append', dest='precommands',
help='extra command to execute before (each) test')
popt.add_option('-c', '--cc', '--checkclass',
action='append', dest='checkfiles', metavar='FILE',
help='module containing custom Check classes')
popt.add_option('-f', '--format',
action='store', dest='terpformat',
help='the interpreter format: cheap, rem, remsingle')
popt.add_option('-r', '--rem',
action='store_true', dest='remformat',
help='equivalent to --format rem')
popt.add_option('-E', '--env',
action='append', dest='env',
help='environment variables to set before running interpreter')
popt.add_option('-t', '--timeout',
dest='timeout_secs', type=float, default=1.0,
help='timeout interval (default: 1.0 sec)')
popt.add_option('--vital',
action='count', dest='vital', default=0,
help='abort a test on the first error (or the whole run, if repeated)')
popt.add_option('-v', '--verbose',
action='count', dest='verbose', default=0,
help='display the transcripts as they run')
(opts, args) = popt.parse_args()
if (not args):
print('usage: regtest.py TESTFILE [ TESTPATS... ]')
sys.exit(1)
class RegTest:
"""RegTest represents one test in the test file. (That is, a block
beginning with a single asterisk.)
A test is one session of the game, from the beginning. (Not necessarily
to the end.) After every game command, tests can be run.
"""
def __init__(self, name, testfile):
self.name = name
self.testfile = testfile
self.gamefile = None # use global gamefile
self.terp = None # global terppath, terpargs
self.precmd = None
self.cmds = []
def __repr__(self):
return '<RegTest %s>' % (self.name,)
def addcmd(self, cmd):
self.cmds.append(cmd)
class Command:
"""Command is one cycle of a RegTest -- a game input, followed by
tests to run on the game's output.
"""
glk_key_names = {
'left':0xfffffffe, 'right':0xfffffffd, 'up':0xfffffffc,
'down':0xfffffffb, 'return':0xfffffffa, 'delete':0xfffffff9,
'escape':0xfffffff8, 'tab':0xfffffff7, 'pageup':0xfffffff6,
'pagedown':0xfffffff5, 'home':0xfffffff4, 'end':0xfffffff3,
'func1':0xffffffef, 'func2':0xffffffee, 'func3':0xffffffed,
'func4':0xffffffec, 'func5':0xffffffeb, 'func6':0xffffffea,
'func7':0xffffffe9, 'func8':0xffffffe8, 'func9':0xffffffe7,
'func10':0xffffffe6, 'func11':0xffffffe5, 'func12':0xffffffe4,
}
def __init__(self, cmd, type=None):
if type is None:
# Peel off the "{...}" prefix, if found.
match = re.match('{([a-z_:]*)}', cmd)
if not match:
type = 'line'
cmd = cmd.strip()
else:
type = match.group(1)
cmd = cmd[match.end() : ].strip()
self.type = type
if self.type == 'line':
self.cmd = cmd
elif self.type == 'char':
self.cmd = None
if len(cmd) == 0:
self.cmd = '\n'
elif len(cmd) == 1:
self.cmd = cmd
elif cmd.lower() in Command.glk_key_names:
self.cmd = cmd.lower()
elif cmd.lower() == 'space':
self.cmd = ' '
elif cmd.lower().startswith('0x'):
self.cmd = unichr(int(cmd[2:], 16))
else:
try:
self.cmd = unichr(int(cmd))
except:
pass
if self.cmd is None:
raise Exception('Unable to interpret char "%s"' % (cmd,))
elif self.type == 'timer':
self.cmd = None
elif self.type == 'hyperlink':
try:
cmd = int(cmd)
except:
pass
self.cmd = cmd
elif self.type == 'mouse':
try:
ls = cmd.split()
self.x = int(ls[0])
self.y = int(ls[1])
self.cmd = (self.x, self.y,)
except:
raise Exception('Mouse event must provide numeric x and y')
elif self.type == 'refresh':
self.cmd = None
elif self.type == 'arrange':
self.cmd = None
self.width = None
self.height = None
try:
ls = cmd.split()
self.width = int(ls[0])
self.height = int(ls[1])
except:
pass
elif self.type in ['include', 'include:silent']:
self.silent = self.type.endswith(':silent')
self.type = 'include'
self.cmd = cmd
elif self.type == 'fileref_prompt':
self.cmd = cmd
elif self.type == 'debug':
self.cmd = cmd
else:
raise Exception('Unknown command type: %s' % (type,))
self.checks = []
def __repr__(self):
return '<Command "%s">' % (self.cmd,)
def addcheck(self, ln, linenum):
args = { 'linenum':linenum }
# First peel off "!" and "{...}" prefixes
while True:
match = re.match('!|{[a-z]*}', ln)
if not match:
break
ln = ln[match.end() : ].strip()
val = match.group()
if val == '!' or val == '{invert}':
args['inverse'] = True
elif val == '{status}':
args['instatus'] = True
elif val == '{graphic}' or val == '{graphics}':
args['ingraphics'] = True
elif val == '{vital}':
args['vital'] = True
else:
raise Exception('Unknown test modifier: %s' % (val,))
# Then the test itself, which may have many formats. We try
# each of the classes in the checkclasses array until one
# returns a Check.
for cla in checkclasses:
check = cla.buildcheck(ln, args)
if check is not None:
self.checks.append(check)
break
else:
raise Exception('Unrecognized test: %s' % (ln,))
class Check:
"""Represents a single test (applied to the output of a game command).
This can be applied to the story, status, or graphics window. (The
model is simplistic and assumes there is exactly one story window
and at most one of the other two kinds.)
An "inverse" test has reversed sense.
A "vital" test will end the test run on failure.
This is a virtual base class. Subclasses should customize the subeval()
method to examine a list of lines, and return None (on success) or a
string (explaining the failure).
"""
inrawdata = False
inverse = False
instatus = False
ingraphics = False
showverbose = False
@classmethod
def buildcheck(cla, ln, args):
raise Exception('No buildcheck method defined for class: %s' % (cla.__name__,))
def __init__(self, ln, **args):
self.linenum = args.get('linenum', None)
self.inverse = args.get('inverse', False)
self.instatus = args.get('instatus', False)
self.ingraphics = args.get('ingraphics', False)
self.showverbose = opts.verbose
self.vital = args.get('vital', False) or opts.vital
self.ln = ln
def __repr__(self):
val = self.ln
if len(val) > 32 and not self.showverbose:
val = val[:32] + '...'
lnumflag = '' if self.linenum is None else ':%d' % (self.linenum,)
invflag = '!' if self.inverse else ''
if self.instatus:
invflag += '{status}'
if self.ingraphics:
invflag += '{graphics}'
detail = self.reprdetail()
return '<%s%s %s%s"%s">' % (self.__class__.__name__, lnumflag, detail, invflag, val,)
def reprdetail(self):
return ''
def eval(self, state):
if not self.inrawdata:
if self.instatus:
lines = state.statuswin
elif self.ingraphics:
lines = state.graphicswin
else:
lines = state.storywin
else:
if self.instatus:
lines = state.statuswindat
elif self.ingraphics:
lines = state.graphicswindat
else:
lines = state.storywindat
res = self.subeval(lines)
if (not self.inverse):
return res
else:
if res:
return
return 'inverse test should fail'
def subeval(self, lines):
return 'not implemented'
class RegExpCheck(Check):
"""A Check which looks for a regular expression match in the output.
"""
@classmethod
def buildcheck(cla, ln, args):
# Matches check lines starting with a slash
if (ln.startswith('/')):
return RegExpCheck(ln[1:].strip(), **args)
def subeval(self, lines):
for ln in lines:
if re.search(self.ln, ln):
return
return 'not found'
class LiteralCheck(Check):
"""A Check which looks for a literal string match in the output.
"""
@classmethod
def buildcheck(cla, ln, args):
# Always matches
return LiteralCheck(ln, **args)
def subeval(self, lines):
for ln in lines:
if self.ln in ln:
return
return 'not found'
class LiteralCountCheck(Check):
"""A Check which looks for a literal string match in the output,
which must occur at least N times.
"""
@classmethod
def buildcheck(cla, ln, args):
match = re.match('{count=([0-9]+)}', ln)
if match:
ln = ln[ match.end() : ].strip()
res = LiteralCountCheck(ln, **args)
res.count = int(match.group(1))
return res
def reprdetail(self):
return '{count=%d} ' % (self.count,)
def subeval(self, lines):
counter = 0
for ln in lines:
start = 0
while True:
pos = ln.find(self.ln, start)
if pos < 0:
break
counter += 1
start = pos+1
if counter >= self.count:
return
if counter == 0:
return 'not found'
else:
return 'only found %d times' % (counter,)
class HyperlinkSpanCheck(Check):
inrawdata = True
@classmethod
def buildcheck(cla, ln, args):
match = re.match('{hyperlink=([0-9]+)}', ln)
if match:
ln = ln[ match.end() : ].strip()
res = HyperlinkSpanCheck(ln, **args)
res.linkvalue = int(match.group(1))
return res
def reprdetail(self):
return '{hyperlink=%d} ' % (self.linkvalue,)
def subeval(self, lines):
for para in lines:
for line in para:
for span in line:
linkval = span.get('hyperlink')
text = span.get('text', '')
if linkval == self.linkvalue and self.ln in text:
return
return 'not found'
class JSONSpanCheck(Check):
inrawdata = True
@classmethod
def buildcheck(cla, ln, args):
import ast
match = re.match('{json (.*)}$', ln)
if match:
res = JSONSpanCheck(ln, **args)
opts = match.group(1)
ls = []
while True:
opts = opts.lstrip()
if not opts:
break
match = re.match('([a-z]+)\\s*:\\s*', opts)
if not match:
raise Exception('{json} argument not recognized: %s' % opts)
key = match.group(1)
opts = opts[ match.end() : ]
if opts.startswith('"'):
match = re.match('"([^"])*"', opts)
if not match:
raise Exception('{json} string has bad format: %s' % opts)
val = ast.literal_eval(opts[ : match.end() ])
opts = opts[ match.end() : ]
elif opts.startswith("'"):
match = re.match("'([^'])*'", opts)
if not match:
raise Exception('{json} string has bad format: %s' % opts)
val = ast.literal_eval(opts[ : match.end() ])
opts = opts[ match.end() : ]
else:
match = re.match('-?[0-9.]+', opts)
if match:
val = ast.literal_eval(opts[ : match.end() ])
opts = opts[ match.end() : ]
else:
match = re.match('[a-zA-Z0-9_]+', opts)
if match:
val0 = opts[ : match.end() ]
if val0 == 'true':
val = True
elif val0 == 'false':
val = False
elif val0 == 'null':
val = None
else:
val = ast.literal_eval(val0)
opts = opts[ match.end() : ]
else:
raise Exception('{json} literal has bad format: %s' % opts)
ls.append( (key, val) )
res.pairs = ls
return res
def subeval(self, lines):
for para in lines:
for line in para:
for span in line:
got = True
for (key, val) in self.pairs:
if (key in span and span[key] == val):
continue
got = False
break
if got:
return
return 'not found'
class ImageSpanCheck(Check):
inrawdata = True
@classmethod
def buildcheck(cla, ln, args):
match = re.match('{image=([0-9]+)([^}]*)}', ln)
if match:
ln = ln[ match.end() : ].strip()
res = ImageSpanCheck(ln, **args)
res.imagevalue = int(match.group(1))
res.widthvalue = None
res.heightvalue = None
res.widthratiovalue = None
res.aspectwidthvalue = None
res.aspectheightvalue = None
res.winmaxwidthvalue = None
res.alignmentvalue = None
res.xvalue = None
res.yvalue = None
opts = match.group(2)
if opts:
for val in opts.split(' '):
if not val:
continue
match = re.match('([a-z]+)=([a-z0-9.]+)', val)
if not match:
raise Exception('{image} argument not recognized: %s' % val)
key = match.group(1)
val = match.group(2)
if key == 'width':
res.widthvalue = int(val)
elif key == 'height':
res.heightvalue = int(val)
elif key == 'widthratio':
res.widthratiovalue = float(val)
elif key == 'aspectwidth':
res.aspectwidthvalue = float(val)
elif key == 'aspectheight':
res.aspectheightvalue = float(val)
elif key == 'winmaxwidth':
if val == 'null':
res.winmaxwidthvalue = 'null'
else:
res.winmaxwidthvalue = float(val)
elif key == 'alignment':
res.alignmentvalue = val
elif key == 'x':
res.xvalue = int(val)
elif key == 'y':
res.yvalue = int(val)
else:
raise Exception('{image} argument not recognized: %s' % key)
return res
def reprdetail(self):
pairs = [
('image', self.imagevalue),
('width', self.widthvalue),
('height', self.heightvalue),
('widthratio', self.widthratiovalue),
('aspectwidth', self.aspectwidthvalue),
('aspectheight', self.aspectheightvalue),
('winmaxwidth', self.winmaxwidthvalue),
('x', self.xvalue),
('y', self.yvalue),
]
strls = [ ('%s=%s' % (key, val,)) for (key, val) in pairs if val is not None ]
return '{%s} ' % (' '.join(strls),)
def subeval(self, lines):
for para in lines:
for line in para:
for span in line:
if span.get('special') == 'image' and span.get('image') == self.imagevalue:
if self.widthvalue is not None and span.get('width') != self.widthvalue:
continue
if self.heightvalue is not None and span.get('height') != self.heightvalue:
continue
if self.widthratiovalue is not None and span.get('widthratio') != self.widthratiovalue:
continue
if self.aspectwidthvalue is not None and span.get('aspectwidth') != self.aspectwidthvalue:
continue
if self.aspectheightvalue is not None and span.get('aspectheight') != self.aspectheightvalue:
continue
if self.winmaxwidthvalue is not None:
val = self.winmaxwidthvalue
if val == 'null':
val = None
if span.get('winmaxwidth') != val:
continue
if self.alignmentvalue is not None and span.get('alignment') != self.alignmentvalue:
continue
if self.xvalue is not None and span.get('x') != self.xvalue:
continue
if self.yvalue is not None and span.get('y') != self.yvalue:
continue
return
return 'not found'
class GameState:
"""The GameState class wraps the connection to the interpreter subprocess
(the pipe in and out streams). It's responsible for sending commands
to the interpreter, and receiving the game output back.
(The RemGlkSingle subclass doesn't maintain a running pipe-in and
pipe-out, so those arguments are not passed in. Instead, we pass a
set of interpreter arguments.)
Currently this class is set up to manage exactly one each of story,
status, and graphics windows. (A missing window is treated as blank.)
This is not very general -- we should understand the notion of multiple
windows -- but it's adequate for now.
This is a virtual base class. Subclasses should customize the
initialize, perform_input, and accept_output methods.
"""
def __init__(self, infile, outfile, args=None):
self.infile = infile
self.outfile = outfile
self.terpargs = args
# Lists of strings
self.statuswin = []
self.graphicswin = []
self.storywin = []
# Lists of line data lists
self.statuswindat = []
self.graphicswindat = []
self.storywindat = []
# Gotta keep track of where each status window begins in the
# (vertically) agglomerated statuswin[] array
self.statuslinestarts = {}
def initialize(self):
pass
def perform_input(self, cmd):
raise Exception('perform_input not implemented')
def accept_output(self, silenced=False):
raise Exception('accept_output not implemented')
class GameStateCheap(GameState):
"""Wrapper for a simple stdin/stdout (dumb terminal) interpreter.
This class never fills in the status window -- that's always blank.
It can only handle line input (not character input).
"""
def perform_input(self, cmd):
if cmd.type != 'line':
raise Exception('Cheap mode only supports line input')
self.infile.write((cmd.cmd+'\n').encode())
self.infile.flush()
def accept_output(self, silenced=False):
self.storywin = []
output = bytearray()
timeout_time = time.time() + opts.timeout_secs
while (select.select([self.outfile],[],[],opts.timeout_secs)[0] != []):
ch = self.outfile.read(1)
if ch == b'':
break
output += ch
if (output[-2:] == b'\n>'):
break
if time.time() >= timeout_time:
raise Exception('Timed out awaiting output')
dat = output.decode('utf-8')
res = dat.split('\n')
if opts.verbose and not silenced:
for ln in res:
if (ln == '>'):
continue
print(ln)
self.storywin = res
class GameStateRemGlk(GameState):
"""Wrapper for a RemGlk-based interpreter. This can in theory handle
any I/O supported by Glk. But the current implementation is limited
to line and char input, and no more than one graphics window.
Multiple story (buffer) windows are accepted, but their output for
a given turn is agglomerated. The same goes for multiple status (grid)
windows.
"""
@staticmethod
def assert_json(dat):
# Given a block of text, complain if it starts with lines that
# don't look like JSON. Raises an exception contining the offending
# lines.
# Note that this doesn't check whether the text *is* JSON. (We
# might get a partial JSON output.) We just want to make sure that
# it starts with an open-brace.
dat = dat.lstrip()
badlines = []
while dat and not dat.startswith('{'):
ln, _, dat = dat.partition('\n')
badlines.append(ln.rstrip())
dat = dat.lstrip()
if badlines:
raise NotJSONException(*badlines)
@staticmethod
def extract_text(line):
# Extract the text from a line object, ignoring styles.
con = line.get('content')
if not con:
return ''
dat = []
i = 0
while i < len(con):
val = con[i]
i += 1
if type(val) is dict:
dat.append(val.get('text', ''))
else:
dat.append(con[i])
i += 1
return ''.join(dat)
@staticmethod
def extract_raw(line):
# Extract the content array from a line object.
con = line.get('content')
if not con:
return []
return con
@staticmethod
def create_metrics(width=None, height=None):
if not width:
width = 800
if not height:
height = 480
res = {
'width':width, 'height':height,
'gridcharwidth':10, 'gridcharheight':12,
'buffercharwidth':10, 'buffercharheight':12,
}
return res
def initialize(self):
import json
update = { 'type':'init', 'gen':0,
'metrics': GameStateRemGlk.create_metrics(),
'support': [ 'timer', 'hyperlinks', 'graphics', 'graphicswin', 'graphicsext' ],
}
cmd = json.dumps(update)
self.infile.write((cmd+'\n').encode())
self.infile.flush()
self.generation = 0
self.windows = {}
# This doesn't track multiple-window input the way it should,
# nor distinguish hyperlink input state across multiple windows.
self.lineinputwin = None
self.charinputwin = None
self.specialinput = None
self.hyperlinkinputwin = None
self.mouseinputwin = None
def perform_input(self, cmd):
import json
update = self.construct_remglk_input(cmd)
cmd = json.dumps(update)
self.infile.write((cmd+'\n').encode())
self.infile.flush()
def accept_output(self, silenced=False):
import json
output = bytearray()
update = None
timeout_time = time.time() + opts.timeout_secs
# Read until a complete JSON object comes through the pipe (or
# we time out).
# We sneakily rely on the fact that RemGlk always uses dicts
# as the JSON object, so it always ends with "}".
while (select.select([self.outfile],[],[],opts.timeout_secs)[0] != []):
ch = self.outfile.read(1)
if ch == b'':
# End of stream. Hopefully we have a valid object.
dat = output.decode('utf-8')
self.assert_json(dat)
update = json.loads(dat)
break
output += ch
if (output[-1] == ord('}')):
# Test and see if we have a complete valid object.
# (It might be partial, in which case we'll try again later.)
dat = output.decode('utf-8')
self.assert_json(dat)
try:
update = json.loads(dat)
break
except:
pass
if time.time() >= timeout_time:
raise Exception('Timed out awaiting output')
self.parse_remglk_update(update, silenced=silenced)
def construct_remglk_input(self, cmd):
if cmd.type == 'line':
if not self.lineinputwin:
raise Exception('Game is not expecting line input')
update = { 'type':'line', 'gen':self.generation,
'window':self.lineinputwin, 'value':cmd.cmd
}
elif cmd.type == 'char':
if not self.charinputwin:
raise Exception('Game is not expecting char input')
val = cmd.cmd
if val == '\n':
val = 'return'
# We should handle arrow keys, too
update = { 'type':'char', 'gen':self.generation,
'window':self.charinputwin, 'value':val
}
elif cmd.type == 'hyperlink':
if not self.hyperlinkinputwin:
raise Exception('Game is not expecting hyperlink input')
update = { 'type':'hyperlink', 'gen':self.generation,
'window':self.hyperlinkinputwin, 'value':cmd.cmd
}
elif cmd.type == 'mouse':
if not self.mouseinputwin:
raise Exception('Game is not expecting mouse input')
update = { 'type':'mouse', 'gen':self.generation,
'window':self.mouseinputwin, 'x':cmd.x, 'y':cmd.y
}
elif cmd.type == 'timer':
update = { 'type':'timer', 'gen':self.generation }
elif cmd.type == 'arrange':
update = { 'type':'arrange', 'gen':self.generation,
'metrics': GameStateRemGlk.create_metrics(cmd.width, cmd.height)
}
elif cmd.type == 'refresh':
update = { 'type':'refresh', 'gen':0 }
elif cmd.type == 'fileref_prompt':
if self.specialinput != 'fileref_prompt':
raise Exception('Game is not expecting a fileref_prompt')
update = { 'type':'specialresponse', 'gen':self.generation,
'response':'fileref_prompt', 'value':cmd.cmd
}
elif cmd.type == 'debug':
update = { 'type':'debuginput', 'gen':self.generation,
'value':cmd.cmd
}
else:
raise Exception('Rem mode does not recognize command type: %s' % (cmd.type))
if opts.verbose >= 2:
ObjPrint.pprint(update)
print()
return update
def parse_remglk_update(self, update, silenced=False):
# Parse the update object. This is complicated. For the format,
# see http://eblong.com/zarf/glk/glkote/docs.html
if opts.verbose >= 2:
ObjPrint.pprint(update)
print()
self.generation = update.get('gen')
windows = update.get('windows')
if windows is not None:
self.windows = {}
for win in windows:
id = win.get('id')
self.windows[id] = win
grids = [ win for win in self.windows.values() if win.get('type') == 'grid' ]
totalheight = 0
# This doesn't work if just one status window resizes.
# We should be keeping track of them separately and merging
# the lists on every update.
self.statuslinestarts.clear()
for win in grids:
self.statuslinestarts[win.get('id')] = totalheight
totalheight += win.get('gridheight', 0)
if totalheight < len(self.statuswin):
self.statuswin = self.statuswin[0:totalheight]
self.statuswindat = self.statuswindat[0:totalheight]
while totalheight > len(self.statuswin):
self.statuswin.append('')
self.statuswindat.append([])
contents = update.get('content')
if contents is not None:
for content in contents:
id = content.get('id')
win = self.windows.get(id)
if not win:
raise Exception('No such window')
if win.get('type') == 'buffer':
self.storywin = []
self.storywindat = []
text = content.get('text')
if text:
for line in text:
dat = self.extract_text(line)
if opts.verbose == 1 and not silenced:
if (dat != '>'):
print(dat)
if line.get('append') and len(self.storywin):
self.storywin[-1] += dat
else:
self.storywin.append(dat)
dat = self.extract_raw(line)
if line.get('append') and len(self.storywindat):
self.storywindat[-1].append(dat)
else:
self.storywindat.append([dat])
elif win.get('type') == 'grid':
lines = content.get('lines')
for line in lines:
linenum = self.statuslinestarts[id] + line.get('line')
dat = self.extract_text(line)
if linenum >= 0 and linenum < len(self.statuswin):
self.statuswin[linenum] = dat
dat = self.extract_raw(line)
if linenum >= 0 and linenum < len(self.statuswindat):
self.statuswindat[linenum].append(dat)
elif win.get('type') == 'graphics':
self.graphicswin = []
self.graphicswindat = []
draw = content.get('draw')
if draw:
self.graphicswindat.append([draw])
inputs = update.get('input')
specialinputs = update.get('specialinput')
if specialinputs is not None:
self.specialinput = specialinputs.get('type')
self.lineinputwin = None
self.charinputwin = None
self.hyperlinkinputwin = None
self.mouseinputwin = None
elif inputs is not None:
self.specialinput = None
self.lineinputwin = None
self.charinputwin = None
self.hyperlinkinputwin = None
self.mouseinputwin = None
for input in inputs:
if input.get('type') == 'line':
if self.lineinputwin:
raise Exception('Multiple windows accepting line input')
self.lineinputwin = input.get('id')
if input.get('type') == 'char':
if self.charinputwin:
raise Exception('Multiple windows accepting char input')
self.charinputwin = input.get('id')
if input.get('hyperlink'):
self.hyperlinkinputwin = input.get('id')
if input.get('mouse'):
self.mouseinputwin = input.get('id')
class GameStateRemGlkSingle(GameStateRemGlk):
"""Wrapper for a RemGlk-based interpreter in single-turn mode. That is,
rather than keeping an interpreter open in the background, we launch
it once for each input. RemGlk will autosave each turn and autorestore
for the next turn.
This has the same limitations as GameStateRemGlk.
"""
def initialize(self):
import json
update = { 'type':'init', 'gen':0,
'metrics': GameStateRemGlk.create_metrics(),
'support': [ 'timer', 'hyperlinks', 'graphics', 'graphicswin', 'graphicsext' ],
}
cmd = json.dumps(update)
proc = subprocess.Popen(
self.terpargs + [ '-singleturn', '--autosave' ],
env=terpenv,
bufsize=0,
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
(outdat, errdat) = proc.communicate((cmd+'\n').encode(), timeout=opts.timeout_secs)
self.pendingupdate = outdat.decode()
self.generation = 0
self.windows = {}
# This doesn't track multiple-window input the way it should,
# nor distinguish hyperlink input state across multiple windows.
self.lineinputwin = None
self.charinputwin = None
self.specialinput = None
self.hyperlinkinputwin = None
self.mouseinputwin = None
def perform_input(self, cmd):
import json
update = self.construct_remglk_input(cmd)
cmd = json.dumps(update)
proc = subprocess.Popen(
self.terpargs + [ '-singleturn', '-autometrics', '--autosave', '--autorestore' ],
env=terpenv,
bufsize=0,
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
(outdat, errdat) = proc.communicate((cmd+'\n').encode(), timeout=opts.timeout_secs)
self.pendingupdate = outdat.decode()
def accept_output(self, silenced=False):
import json
dat = self.pendingupdate
self.assert_json(dat)
update = json.loads(dat)
self.pendingupdate = None
self.parse_remglk_update(update, silenced=silenced)
class ObjPrint:
NoneType = type(None)
try:
UnicodeType = unicode
except:
UnicodeType = str
@staticmethod
def pprint(obj):
printer = ObjPrint()
printer.printval(obj, depth=0)
print(''.join(printer.arr))
def __init__(self):
self.arr = []
@staticmethod
def valislong(val):
typ = type(val)
if typ is ObjPrint.NoneType:
return False
elif typ is bool or typ is int or typ is float:
return False
elif typ is str or typ is ObjPrint.UnicodeType:
return (len(val) > 16)
elif typ is list or typ is dict:
return (len(val) > 0)
else:
return True
def printval(self, val, depth=0):
typ = type(val)