/
lineterm.py
executable file
·1905 lines (1687 loc) · 88.1 KB
/
lineterm.py
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
#!/usr/bin/env python
""" Lineterm: Line-oriented pseudo-tty wrapper for GraphTerm
https://github.com/mitotic/graphterm
Derived from the public-domain Ajaxterm code, v0.11 (2008-11-13).
https://github.com/antonylesuisse/qweb
http://antony.lesuisse.org/software/ajaxterm/
The contents of this file remain in the public-domain.
"""
from __future__ import with_statement
import array, cgi, copy, fcntl, glob, logging, mimetypes, optparse, os, pty
import re, signal, select, socket, sys, threading, time, termios, tty, struct, pwd
try:
import ujson as json
except ImportError:
import json
import random
try:
random = random.SystemRandom()
except NotImplementedError:
import random
import base64
import hashlib
import hmac
import Queue
import shlex
import subprocess
import traceback
MAX_SCROLL_LINES = 500
MAX_PAGELET_BYTES = 1000000 # Max size for pagelet buffer
IDLE_TIMEOUT = 300 # Idle timeout in seconds
UPDATE_INTERVAL = 0.05 # Fullscreen update time interval
TERM_TYPE = "xterm" # "screen" may be a better default terminal, but arrow keys do not always work
NO_COPY_ENV = set(["GRAPHTERM_EXPORT", "TERM_PROGRAM","TERM_PROGRAM_VERSION", "TERM_SESSION_ID"])
ALTERNATE_SCREEN_CODES = (47, 1047, 1049) # http://rtfm.etla.org/xterm/ctlseq.html
GRAPHTERM_SCREEN_CODES = (1150, 1155)
FILE_EXTENSIONS = {"css": "css", "htm": "html", "html": "html", "js": "javascript", "py": "python",
"xml": "xml"}
FILE_COMMANDS = set(["cd", "cp", "mv", "rm", "gcp", "gimages", "gls", "gopen", "gvi"])
REMOTE_FILE_COMMANDS = set(["gbrowse", "gcp"])
COMMAND_DELIMITERS = "<>;"
# Scroll lines array components
JINDEX = 0
JOFFSET = 1
JDIR = 2
JMARKUP = 3
JLINE = 4
Log_ignored = False
MAX_LOG_CHARS = 8
BINDIR = "bin"
File_dir = os.path.dirname(__file__)
Exec_path = os.path.join(File_dir, BINDIR)
Gls_path = os.path.join(Exec_path, "gls")
Exec_errmsg = False
ENCODING = "utf-8" # "utf-8" or "ascii"
# Bash PROMPT CMD variable (and export version)
BASH_PROMPT_CMD = 'export PS1=$GRAPHTERM_PROMPT; echo -n "\033[?%s;${GRAPHTERM_COOKIE}h$PWD\033[?%s;l"'
EXPT_PROMPT_CMD = 'export PS1=$GRAPHTERM_PROMPT; echo -n `printf \"\\033\"`\"[?%s;${GRAPHTERM_COOKIE}h$PWD\"`printf \"\\033\"`\"[?%s;l\"'
STYLE4 = 4
UNI24 = 24
UNIMASK = 0xffffff
ASCIIMASK = 0x7f
def make_lterm_cookie():
return "%016d" % random.randrange(10**15, 10**16)
# Meta info indices
JCURDIR = 0
JCONTINUATION = 1
def create_array(fill_value, count):
"""Return array of 32-bit values"""
return array.array('L', [fill_value]*count)
def dump(data, trim=False, encoded=False):
"""Return unicode string from array of long data, trimming NULs, and encoded to str, if need be"""
if ENCODING == "ascii":
ucodes = [(x & ASCIIMASK) for x in data]
else:
ucodes = [(x & UNIMASK) for x in data]
# Replace non-NUL, non-newline control character by space
ucodes = [(32 if (x < 32 and x and x != 10) else x) for x in ucodes]
return uclean( u"".join(map(unichr, ucodes)), trim=trim, encoded=encoded)
def uclean(ustr, trim=False, encoded=False):
"""Return cleaned up unicode string, trimmed and encoded to str, if need be"""
if trim:
# Trim trailing NULs
ustr = ustr.rstrip(u"\x00")
# Replace NULs with spaces and DELs with "?"
ustr = ustr.replace(u"\x00", u" ").replace(u"\x7f", u"?")
return ustr.encode(ENCODING, "replace") if encoded else ustr
def prompt_offset(line, prompt, meta=None):
"""Return offset at end of prompt (not including trailing space), or zero"""
offset = 0
if (meta and not meta[JCONTINUATION]) or (prompt and prompt[0] and line.startswith(prompt[0])):
end_offset = line.find(prompt[2])
if end_offset >= 0:
offset = end_offset + len(prompt[2])
return offset
def command_output(command_args, **kwargs):
""" Executes a command and returns the string tuple (stdout, stderr)
keyword argument timeout can be specified to time out command (defaults to 15 sec)
"""
timeout = kwargs.pop("timeout", 15)
def command_output_aux():
try:
proc = subprocess.Popen(command_args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
return proc.communicate()
except Exception, excp:
return "", str(excp)
if not timeout:
return command_output_aux()
exec_queue = Queue.Queue()
def execute_in_thread():
exec_queue.put(command_output_aux())
thrd = threading.Thread(target=execute_in_thread)
thrd.start()
try:
return exec_queue.get(block=True, timeout=timeout)
except Queue.Empty:
return "", "Timed out after %s seconds" % timeout
def is_executable(filepath):
return os.path.isfile(filepath) and os.access(filepath, os.X_OK)
def which(filepath, add_path=[]):
filedir, filename = os.path.split(filepath)
if filedir:
if is_executable(filepath):
return filepath
else:
for path in os.environ["PATH"].split(os.pathsep) + add_path:
whichpath = os.path.join(path, filepath)
if is_executable(whichpath):
return whichpath
return None
def getcwd(pid):
"""Return working directory of running process"""
if sys.platform.startswith("linux"):
command_args = ["pwdx", str(pid)]
else:
command_args = ["lsof", "-a", "-p", str(pid), "-d", "cwd", "-Fn"]
std_out, std_err = command_output(command_args, timeout=1)
if std_err:
logging.warning("getcwd: ERROR %s", std_err)
return ""
try:
if sys.platform.startswith("linux"):
return std_out.split()[1]
else:
return std_out.split("\n")[1][1:]
except Exception, excp:
logging.warning("getcwd: ERROR %s", excp)
return ""
def parse_headers(text):
"""Parse gterm output and return (headers, content)"""
headers = {"content_type": "text/html", "x_gterm_response": "",
"x_gterm_parameters": {}}
content = text
if text.startswith("<"):
# Raw HTML
return (headers, content)
# "MIME headers"
head_str, sep, tail_str = text.partition("\r\n\r\n")
if not sep:
head_str, sep, tail_str = text.partition("\n\n")
if not sep:
head_str, sep, tail_str = text.partition("\r\r")
if sep:
if head_str.startswith("{"):
# JSON headers
try:
headers = json.loads(head_str)
content = tail_str
except Exception, excp:
content = str(excp)
headers["json_error"] = "JSON parse error"
headers["content_type"] = "text/plain"
else:
# Parse mime headers: "-" -> "_" (TO DO)
pass
if "x_gterm_response" not in headers:
headers["x_gterm_response"] = ""
if "x_gterm_parameters" not in headers:
headers["x_gterm_parameters"] = {}
return (headers, content)
def shplit(line, delimiters=COMMAND_DELIMITERS, final_delim="&", index=None):
"""Split shell command line, returning all components as a list, including separators
"""
if not line:
return []
comps = shlex.split(line)
indices = []
buf = line
offset = 0
for comp in comps:
ncomp = len(buf) - len(buf.lstrip())
if ncomp:
indices.append(offset+ncomp)
offset += ncomp
buf = buf[ncomp:]
ncomp = len(comp)
while True:
try:
temcomp = shlex.split(buf[:ncomp])[0]
except Exception:
temcomp = None
if temcomp == comp:
break
ncomp += 1
if ncomp > len(buf):
raise Exception("shplit ERROR ('%s','%s')" % (comp, buf))
comp = buf[:ncomp]
buf = buf[ncomp:]
if delimiters:
tembuf = comp.replace(" ", ".").replace(delimiters[0], " ")
indices += shplit(tembuf, delimiters=delimiters[1:], index=offset)
else:
indices.append(offset+ncomp)
offset += ncomp
if buf:
indices.append(offset+len(buf))
if index is None:
jprev = 0
retval = []
for j in indices:
retval.append(line[jprev:j])
jprev = j
if final_delim and retval and retval[-1].endswith(final_delim) and retval[-1] != final_delim:
retval[-1] = retval[-1][:-len(final_delim)]
retval.append(final_delim)
return retval
else:
return [j+index for j in indices]
FILE_URI_PREFIX = "file://"
FILE_PREFIX = "/file/"
JSERVER = 0
JHOST = 1
JFILENAME = 2
JFILEPATH = 3
JQUERY = 4
HEX_DIGITS = 16
def create_file_uri(url_comps):
return FILE_URI_PREFIX + url_comps[JHOST] + url_comps[JFILEPATH] + url_comps[JQUERY]
def split_file_url(url, check_host_secret=None):
"""Return [protocol://server[:port], hostname, filename, fullpath, query] for file://host/path
or http://server:port/file/host/path, or /file/host/path URLs.
If not file URL, returns []
If check_host_secret is specified, and file hmac matches, then hostname is set to the null string.
"""
if not url:
return []
server_port = ""
if url.startswith(FILE_URI_PREFIX):
host_path = url[len(FILE_URI_PREFIX):]
elif url.startswith(FILE_PREFIX):
host_path = url[len(FILE_PREFIX):]
else:
if url.startswith("http://"):
protocol = "http"
elif url.startswith("https://"):
protocol = "https"
else:
return []
j = url.find("/", len(protocol)+3)
if j < 0:
return []
server_port = url[:j]
url_path = url[j:]
if not url_path.startswith(FILE_PREFIX):
return []
host_path = url_path[len(FILE_PREFIX):]
j = host_path.find("?")
if j >= 0:
query = host_path[j:]
host_path = host_path[:j]
else:
query = ""
comps = host_path.split("/")
hostname = comps[0]
filepath = "/"+"/".join(comps[1:])
filename = comps[-1]
if check_host_secret:
filehmac = "?hmac="+hmac.new(str(check_host_secret), filepath, digestmod=hashlib.sha256).hexdigest()[:HEX_DIGITS]
if query.lower() == filehmac.lower():
hostname = ""
return [server_port, hostname, filename, filepath, query]
def relative_file_url(file_url, cwd):
url_comps = split_file_url(file_url)
if not url_comps:
return file_url
filepath = url_comps[JFILEPATH]
if filepath == cwd:
return "."
else:
relpath = os.path.relpath(filepath, cwd)
if relpath.startswith("../../../"):
# Too many .. would be confusing
return filepath
else:
return relpath
def prompt_markup(text, entry_index, current_dir):
return '<span class="gterm-cmd-prompt gterm-link" id="prompt%s" data-gtermdir="%s">%s</span>' % (entry_index, current_dir, cgi.escape(text))
def plain_markup(text, command=False):
cmd_class = " gterm-command" if command else ""
return '<span class="gterm-cmd-text gterm-link%s">%s</span>' % (cmd_class, cgi.escape(text),)
def path_markup(text, current_dir, command=False):
cmd_class = " gterm-command" if command else ""
fullpath = os.path.normpath(os.path.join(current_dir, text))
return '<a class="gterm-cmd-path gterm-link%s" href="file://%s" data-gtermmime="x-graphterm/%s" data-gtermcmd="%s">%s</a>' % (cmd_class, fullpath, "path", "xpaste", cgi.escape(text))
def command_markup(entry_index, current_dir, pre_offset, offset, line):
marked_up = prompt_markup(line[pre_offset:offset], entry_index, current_dir)
try:
comps = shplit(line[offset:])
except Exception:
return marked_up + line[offset:]
while comps and not comps[0].strip():
marked_up += comps.pop(0)
if not comps:
return marked_up
cmd = comps.pop(0)
if current_dir and (cmd.startswith("./") or cmd.startswith("../")):
marked_up += path_markup(cmd, current_dir, command=True)
else:
marked_up += plain_markup(cmd, command=True)
file_command = cmd in FILE_COMMANDS
for comp in comps:
if not comp.strip():
# Space
marked_up += comp
elif comp[0] in COMMAND_DELIMITERS:
marked_up += plain_markup(comp)
if comp[0] == ";":
file_command = False
elif file_command and current_dir and comp[0] != "-":
marked_up += path_markup(comp, current_dir)
else:
marked_up += plain_markup(comp)
return marked_up
class ScreenBuf(object):
def __init__(self, prompt, fg_color=0, bg_color=7):
self.prompt = prompt
self.pre_offset = len(prompt[0]) if prompt else 0
self.width = None
self.height = None
self.cursorx = None
self.cursory = None
self.main_screen = None
self.alt_screen = None
self.entry_index = 0
self.current_scroll_count = 0
self.clear_buf()
self.cleared_current_dir = None
self.cleared_last = False
self.fg_color = fg_color
self.bg_color = bg_color
self.default_style = (bg_color << STYLE4) | fg_color
self.inverse_style = (fg_color << STYLE4) | bg_color
self.bold_style = 0x08
self.default_nul = self.default_style << UNI24
def clear_buf(self):
self.last_scroll_count = self.current_scroll_count
self.scroll_lines = []
self.full_update = True
def clear_last_entry(self, last_entry_index=None):
if not self.scroll_lines or self.entry_index <= 0:
return
n = len(self.scroll_lines)-1
entry_index, offset, dir, markup, line = self.scroll_lines[n]
if self.entry_index != entry_index:
return
if last_entry_index and last_entry_index != entry_index:
return
self.entry_index -= 1
while n > 0 and self.scroll_lines[n-1][JINDEX] == entry_index:
n -= 1
self.current_scroll_count -= len(self.scroll_lines) - n
self.cleared_last = True
if self.cleared_current_dir is None:
self.cleared_current_dir = self.scroll_lines[n][JDIR]
self.scroll_lines[n:] = []
if self.last_scroll_count > self.current_scroll_count:
self.last_scroll_count = self.current_scroll_count
def scroll_buf_up(self, line, meta, offset=0):
current_dir = ""
current_markup = None
if offset:
# Prompt line (i.e., command line)
self.entry_index += 1
current_dir = meta[JCURDIR] if meta else ""
current_markup = command_markup(self.entry_index, current_dir, self.pre_offset, offset, line)
if not self.cleared_last:
self.cleared_current_dir = None
self.cleared_last = False
self.current_scroll_count += 1
self.scroll_lines.append([self.entry_index, offset, current_dir, current_markup, line])
if len(self.scroll_lines) > MAX_SCROLL_LINES:
entry_index, offset, dir, markup, line = self.scroll_lines.pop(0)
while self.scroll_lines and self.scroll_lines[0][JINDEX] == entry_index:
self.scroll_lines.pop(0)
def update(self, active_rows, width, height, cursorx, cursory, main_screen,
alt_screen=None, prompt=[], reconnecting=False):
""" Returns full_update, update_rows, update_scroll
"""
full_update = self.full_update or reconnecting
if not reconnecting and (width != self.width or height != self.height):
self.width = width
self.height = height
full_update = True
if (alt_screen and not self.alt_screen) or (not alt_screen and self.alt_screen):
full_update = True
if alt_screen:
screen = alt_screen
old_screen = self.alt_screen
row_count = height
else:
screen = main_screen
old_screen = self.main_screen
row_count = active_rows
cursor_moved = (cursorx != self.cursorx or cursory != self.cursory)
update_rows = []
for j in range(row_count):
new_row = screen.data[width*j:width*(j+1)]
if full_update or old_screen is None:
row_update = True
else:
row_update = (new_row != old_screen.data[width*j:width*(j+1)])
if row_update or (cursor_moved and (cursory == j or self.cursory == j)):
offset = prompt_offset(dump(new_row), prompt, screen.meta[j])
update_rows.append([j, offset, "", None, self.dumprichtext(new_row, trim=True)])
if reconnecting:
update_scroll = self.scroll_lines[:]
elif self.last_scroll_count < self.current_scroll_count:
update_scroll = self.scroll_lines[self.last_scroll_count-self.current_scroll_count:]
else:
update_scroll = []
if not reconnecting:
self.last_scroll_count = self.current_scroll_count
self.full_update = False
self.cursorx = cursorx
self.cursory = cursory
self.main_screen = main_screen.make_copy() if main_screen else None
self.alt_screen = alt_screen.make_copy() if alt_screen else None
return full_update, update_rows, update_scroll
def dumprichtext(self, data, trim=False):
"""Returns [(style_list, utf8str), ...] for line data"""
if all((x >> UNI24) == self.default_style for x in data):
# All default style (optimize)
return [([], dump(data, trim=trim, encoded=True))]
span_list = []
style_list = []
span_style, span_bg, span_fg = self.default_style, -1, -1
span = u""
for scode in data:
char_style = scode >> UNI24
ucode = scode & ASCIIMASK if ENCODING == "ascii" else scode & UNIMASK
if ucode < 32 and ucode and ucode != 10:
# Replace non-NUL, non-newline control character by space
ucode = 32
if span_style != char_style:
if span:
span_list.append( (style_list, uclean(span, encoded=True)) )
span = u""
span_style = char_style
style_list = []
if span_style & self.bold_style:
style_list.append("bold")
if (span_style & 0x77) == self.inverse_style:
style_list.append("inverse")
span += unichr(ucode)
cspan = uclean(span, trim=trim, encoded=True)
if cspan:
span_list.append( (style_list, cspan) )
return span_list
def __repr__(self):
if not self.main_screen:
return ""
d = dump(self.main_screen.data, trim=True)
r = ""
for i in range(self.height):
r += "|%s|\n"%d[self.width*i:self.width*(i+1)]
return r
class Screen(object):
def __init__(self, width, height, data=None, meta=None):
self.width = width
self.height = height
self.data = data or create_array(0, width*height)
self.meta = [None] * height
def make_copy(self):
return Screen(self.width, self.height, data=copy.copy(self.data), meta=copy.copy(self.meta))
class Terminal(object):
def __init__(self, term_name, fd, pid, screen_callback, height=25, width=80, cookie=0,
shared_secret="", host="", prompt=[], logfile=""):
self.term_name = term_name
self.fd = fd
self.pid = pid
self.screen_callback = screen_callback
self.width = width
self.height = height
self.cookie = cookie
self.shared_secret = shared_secret
self.host = host
self.prompt = prompt
self.logfile = logfile
self.screen_buf = ScreenBuf(prompt)
self.init()
self.reset()
self.output_time = time.time()
self.buf = ""
self.alt_mode = False
self.screen = self.main_screen
self.trim_first_prompt = bool(prompt)
self.logchars = 0
def init(self):
self.esc_seq={
"\x00": None,
"\x05": self.esc_da,
"\x07": None,
"\x08": self.esc_0x08,
"\x09": self.esc_0x09,
"\x0a": self.esc_0x0a,
"\x0b": self.esc_0x0a,
"\x0c": self.esc_0x0a,
"\x0d": self.esc_0x0d,
"\x0e": None,
"\x0f": None,
"\x1b#8": None,
"\x1b=": None,
"\x1b>": None,
"\x1b(0": None,
"\x1b(A": None,
"\x1b(B": None,
"\x1b[c": self.esc_da,
"\x1b[0c": self.esc_da,
"\x1b[>c": self.esc_sda,
"\x1b[>0c": self.esc_sda,
"\x1b[5n": self.esc_sr,
"\x1b[6n": self.esc_cpr,
"\x1b[x": self.esc_tpr,
"\x1b]R": None,
"\x1b7": self.esc_save,
"\x1b8": self.esc_restore,
"\x1bD": self.esc_ind,
"\x1bE": self.esc_nel,
"\x1bH": None,
"\x1bM": self.esc_ri,
"\x1bN": None,
"\x1bO": None,
"\x1bZ": self.esc_da,
"\x1ba": None,
"\x1bc": self.reset,
"\x1bn": None,
"\x1bo": None,
}
for k,v in self.esc_seq.items():
if v==None:
self.esc_seq[k] = self.esc_ignore
# regex
d={
r'\[\??([0-9;]*)([@ABCDEFGHJKLMPXacdefghlmnqrstu`])' : self.csi_dispatch,
r'\]([^\x07]+)\x07' : self.esc_ignore,
}
self.esc_re=[]
for k,v in d.items():
self.esc_re.append((re.compile('\x1b'+k), v))
# define csi sequences
self.csi_seq={
'@': (self.csi_at,[1]),
'`': (self.csi_G,[1]),
'J': (self.csi_J,[0]),
'K': (self.csi_K,[0]),
}
for i in [i[4] for i in dir(self) if i.startswith('csi_') and len(i)==5]:
if not self.csi_seq.has_key(i):
self.csi_seq[i] = (getattr(self,'csi_'+i),[1])
def reset(self, s=""):
self.update_time = 0
self.needs_updating = True
self.main_screen = Screen(self.width, self.height)
self.alt_screen = Screen(self.width, self.height)
self.scroll_top = 0
self.scroll_bot = self.height-1
self.cursor_x_bak = self.cursor_x = 0
self.cursor_y_bak = self.cursor_y = 0
self.cursor_eol = 0
self.current_nul = self.screen_buf.default_nul
self.echobuf = ""
self.echobuf_count = 0
self.outbuf = ""
self.last_html = ""
self.active_rows = 0
self.current_meta = None
self.gterm_code = None
self.gterm_buf = None
self.gterm_buf_size = 0
self.gterm_entry_index = None
self.gterm_validated = False
self.gterm_output_buf = []
def resize(self, height, width):
reset_flag = (self.width != width or self.height != height)
if reset_flag:
self.scroll_screen()
min_width = min(self.width, width)
saved_line = None
if self.active_rows:
# Check first active line for prompt
line = dump(self.main_screen.data[:min_width])
if prompt_offset(line, self.prompt, self.main_screen.meta[0]):
saved_line = [len(line.rstrip(u'\x00')), self.main_screen.meta[0], self.main_screen.data[:min_width]]
self.width = width
self.height = height
self.reset()
if saved_line:
# Restore saved line
self.active_rows = 1
self.cursor_x = saved_line[0]
self.main_screen.meta[0] = saved_line[1]
self.main_screen.data[:min_width] = saved_line[2]
self.screen = self.alt_screen if self.alt_mode else self.main_screen
self.needs_updating = True
def clear(self):
self.screen_buf.clear_buf()
self.needs_updating = True
def reconnect(self, response_id=""):
self.update_callback(response_id=response_id)
self.graphterm_output(response_id=response_id, from_buffer=True)
def clear_last_entry(self, last_entry_index=None):
self.screen_buf.clear_last_entry(last_entry_index=last_entry_index)
def scroll_screen(self, scroll_rows=None):
if scroll_rows == None:
scroll_rows = 0
for j in range(self.active_rows-1,-1,-1):
line = dump(self.main_screen.data[self.width*j:self.width*(j+1)])
if prompt_offset(line, self.prompt, self.main_screen.meta[j]):
# Move rows before last prompt to buffer
scroll_rows = j
break
if not scroll_rows:
return
# Move scrolled active rows to buffer
cursor_y = 0
while cursor_y < scroll_rows:
row = self.main_screen.data[self.width*cursor_y:self.width*cursor_y+self.width]
meta = self.main_screen.meta[cursor_y]
offset = prompt_offset(dump(row), self.prompt, meta)
if meta:
# Concatenate rows for multiline command
while cursor_y < scroll_rows-1 and self.main_screen.meta[cursor_y+1] and self.main_screen.meta[cursor_y+1][JCONTINUATION]:
cursor_y += 1
row += self.main_screen.data[self.width*cursor_y:self.width*cursor_y+self.width]
self.screen_buf.scroll_buf_up(dump(row, trim=True, encoded=True), meta, offset=offset)
cursor_y += 1
# Scroll and zero rest of screen
if scroll_rows < self.active_rows:
self.poke(0, 0, self.peek(scroll_rows, 0, self.active_rows-1, self.width))
self.active_rows = self.active_rows - scroll_rows
if self.active_rows:
self.screen.meta[0:self.active_rows] = self.screen.meta[scroll_rows:scroll_rows+self.active_rows]
self.zero_lines(self.active_rows, self.height-1)
self.cursor_y = max(0, self.cursor_y - scroll_rows)
if not self.active_rows:
self.cursor_x = 0
self.cursor_eol = 0
def update(self):
self.update_time = time.time()
self.needs_updating = False
if not self.alt_mode:
self.scroll_screen()
self.update_callback()
def update_callback(self, response_id=""):
alt_screen = self.alt_screen if self.alt_mode else None
full_update, update_rows, update_scroll = self.screen_buf.update(self.active_rows, self.width, self.height,
self.cursor_x, self.cursor_y,
self.main_screen,
alt_screen=alt_screen,
prompt=self.prompt,
reconnecting=bool(response_id))
pre_offset = len(self.prompt[0]) if self.prompt else 0
self.screen_callback(self.term_name, response_id, "row_update",
[self.alt_mode, full_update, self.active_rows,
self.width, self.height,
self.cursor_x, self.cursor_y, pre_offset,
update_rows, update_scroll])
if not response_id and (update_rows or update_scroll):
self.gterm_output_buf = []
def zero(self, y1, x1, y2, x2, screen=None):
if screen is None: screen = self.screen
w = self.width*(y2-y1) + x2 - x1 + 1
z = create_array(0, w)
screen.data[self.width*y1+x1:self.width*y2+x2+1] = z
def zero_lines(self, y1, y2):
self.zero(y1, 0, y2, self.width-1)
self.screen.meta[y1:y2+1] = [None]*(y2+1-y1)
def zero_screen(self):
self.zero_lines(0, self.height-1)
def peek(self, y1, x1, y2, x2):
return self.screen.data[self.width*y1+x1:self.width*y2+x2]
def poke(self, y, x, s):
pos = self.width*y + x
self.screen.data[pos:pos+len(s)] = s
if not self.alt_mode:
self.active_rows = max(y+1, self.active_rows)
def scroll_up(self, y1, y2):
self.poke(y1, 0, self.peek(y1+1, 0, y2, self.width))
self.screen.meta[y1:y2] = self.screen.meta[y1+1:y2+1]
self.zero_lines(y2, y2)
def scroll_down(self, y1, y2):
self.poke(y1+1, 0, self.peek(y1, 0, y2-1, self.width))
self.screen.meta[y1+1:y2+1] = self.screen.meta[y1:y2]
self.zero_lines(y1, y1)
def scroll_right(self, y, x):
self.poke(y, x+1, self.peek(y, x, y, self.width-1))
self.zero(y, x, y, x)
def cursor_down(self):
if self.cursor_y >= self.scroll_top and self.cursor_y <= self.scroll_bot:
self.cursor_eol = 0
q, r = divmod(self.cursor_y+1, self.scroll_bot+1)
if q:
if not self.alt_mode:
row = self.peek(self.scroll_top, 0, self.scroll_top, self.width)
self.screen_buf.scroll_buf_up(dump(row, trim=True, encoded=True),
self.screen.meta[self.scroll_top],
offset=prompt_offset(dump(row), self.prompt, self.screen.meta[self.scroll_top]))
self.scroll_up(self.scroll_top, self.scroll_bot)
self.cursor_y = self.scroll_bot
else:
self.cursor_y = r
if not self.alt_mode:
self.active_rows = max(self.cursor_y+1, self.active_rows)
if self.current_meta and not self.screen.meta[self.active_rows-1]:
self.current_meta = (self.current_meta[JCURDIR], self.current_meta[JCONTINUATION]+1)
self.screen.meta[self.active_rows-1] = self.current_meta
def cursor_right(self):
q, r = divmod(self.cursor_x+1, self.width)
if q:
self.cursor_eol = 1
else:
self.cursor_x = r
def expect_prompt(self, current_directory):
if not self.active_rows or self.cursor_y+1 == self.active_rows:
self.current_meta = (current_directory, 0)
self.screen.meta[self.cursor_y] = self.current_meta
def enter(self):
"""Called when CR or LF is received from the user to indicate possible end of command"""
self.current_meta = None # Command entry is completed
def echo(self, char):
char_code = ord(char)
if ENCODING == "utf-8" and (char_code & 0x80):
# Multi-byte UTF-8
if char_code & 0x40:
# New UTF-8 sequence
self.echobuf = char
if not (char_code & 0x20):
self.echobuf_count = 2
elif not (char_code & 0x10):
self.echobuf_count = 3
elif not (char_code & 0x08):
self.echobuf_count = 4
else:
# Invalid UTF encoding (> 4 bytes?)
self.echobuf = ""
self.echobuf_count = 0
return
# Continue UTF-8 sequence
if not self.echobuf:
# Ignore incomplete UTF-8 sequence
return
self.echobuf += char
if len(self.echobuf) < self.echobuf_count:
return
# Complete UTF-8 sequence
uchar = self.echobuf.decode("utf-8", "replace")
self.echobuf = ""
self.echobuf_count = 0
else:
uchar = unichr(char_code)
if self.logfile and self.logchars < MAX_LOG_CHARS:
with open(self.logfile, "a") as logf:
if not self.logchars:
logf.write("TXT:")
logf.write(uchar.encode("utf-8", "replace"))
self.logchars += 1
if self.logchars == MAX_LOG_CHARS:
logf.write("\n")
if self.cursor_eol:
self.cursor_down()
self.cursor_x = 0
self.screen.data[(self.cursor_y*self.width)+self.cursor_x] = self.current_nul | ord(uchar)
self.cursor_right()
if not self.alt_mode:
self.active_rows = max(self.cursor_y+1, self.active_rows)
def esc_0x08(self, s):
"""Backspace"""
self.cursor_x = max(0,self.cursor_x-1)
def esc_0x09(self, s):
"""Tab"""
x = self.cursor_x+8
q, r = divmod(x, 8)
self.cursor_x = (q*8)%self.width
def esc_0x0a(self,s):
"""Newline"""
self.cursor_down()
def esc_0x0d(self,s):
"""Carriage Return"""
self.cursor_eol = 0
self.cursor_x = 0
def esc_save(self, s):
self.cursor_x_bak = self.cursor_x
self.cursor_y_bak = self.cursor_y
def esc_restore(self,s):
self.cursor_x = self.cursor_x_bak
self.cursor_y = self.cursor_y_bak
self.cursor_eol = 0
if not self.alt_mode:
self.active_rows = max(self.cursor_y+1, self.active_rows)
def esc_da(self, s):
"""Send primary device attributes"""
self.outbuf = "\x1b[?6c"
def esc_sda(self, s):
"""Send secondary device attributes"""
self.outbuf = "\x1b[>0;0;0c"
def esc_tpr(self, s):
"""Send Terminal Parameter Report"""
self.outbuf = "\x1b[0;0;0;0;0;0;0x"
def esc_sr(self, s):
"""Send Status Report"""
self.outbuf = "\x1b[0n"
def esc_cpr(self, s):
"""Send Cursor Position Report"""
self.outbuf = "\x1b[%d;%dR" % (self.cursor_y+1, self.cursor_x+1)
def esc_nel(self, s):
"""Next Line (NEL)"""
self.cursor_down()
self.cursor_x = 0
def esc_ind(self, s):
"""Index (IND)"""
self.cursor_down()
def esc_ri(self, s):
"""Reverse Index (RI)"""
if self.cursor_y == self.scroll_top:
self.scroll_down(self.scroll_top, self.scroll_bot)
else:
self.cursor_y = max(self.scroll_top, self.cursor_y-1)
if not self.alt_mode:
self.active_rows = max(self.cursor_y+1, self.active_rows)
def esc_ignore(self,*s):
if Log_ignored or self.logfile:
print >> sys.stderr, "lineterm:ignore: %s"%repr(s)
def csi_dispatch(self,seq,mo):
# CSI sequences
s = mo.group(1)
c = mo.group(2)
f = self.csi_seq.get(c, None)
if f:
try:
l = [int(i) for i in s.split(';')]
except ValueError:
l = []
if len(l)==0:
l = f[1]
f[0](l)
elif Log_ignored or self.logfile:
print >> sys.stderr, 'lineterm: csi ignore', s, c
def csi_at(self, l):
for i in range(l[0]):
self.scroll_right(self.cursor_y, self.cursor_x)
def csi_A(self, l):
"""Cursor up (default 1)"""
self.cursor_y = max(self.scroll_top, self.cursor_y-l[0])
def csi_B(self, l):
"""Cursor down (default 1)"""
self.cursor_y = min(self.scroll_bot, self.cursor_y+l[0])