-
Notifications
You must be signed in to change notification settings - Fork 1
/
chatscreen.py
88 lines (76 loc) · 2.32 KB
/
chatscreen.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
def chopLine(line, maxLen):
if len(line) <= maxLen: return (line, "")
chopLoc = line[:maxLen+1].rfind(" ")
if chopLoc > 0:
return (line[:chopLoc], line[chopLoc+1:])
else:
return (line[:maxLen], line[maxLen:])
def ctrl(s): return curses.ascii.ctrl(ord(s))
import curses
import curses.ascii
import curses.textpad
import threading
import traceback
class ChatScreen(object):
def __init__(self, screenInitCb, outboxCb):
self.screenInitCb = screenInitCb
self.outboxCb = outboxCb
self.done = False
self.cursesLock = threading.RLock()
def cursesApp(self, stdscr):
(maxY, maxX) = stdscr.getmaxyx()
self.win1 = curses.newwin(maxY - 1, maxX, 0, 0)
self.win2 = curses.newwin(1, maxX, maxY - 1, 0)
self.win2.move(0, 0)
self.textbox = curses.textpad.Textbox(self.win2)
self.screenInitCb()
while True:
msg = self.textbox.edit(self.validate)
try:
self.outboxCb(msg)
except: self.log(traceback.format_exc())
with self.cursesLock:
self.win2.deleteln()
self.textbox.do_command(ctrl("A"))
if self.done: return
def validate(self, s):
#self.log(repr(s))
if s == ord("\n"): return ctrl("G")
elif s == 127: return curses.KEY_BACKSPACE
#elif s == curses.KEY_RIGHT:
else: return s
def log(self, msg, indent=0):
(maxy, maxx) = self.win1.getmaxyx()
assert indent < maxx - 1
#indent = " " * indent
if type(msg) is str: pass
elif type(msg) is unicode: msg = msg.encode("ascii", "backslashreplace")
else: msg = repr(msg)
indentSpaces = " " * indent
lines = []
for line in msg.split("\n"):
if not lines:
(firstLine, line) = chopLine(line, maxx - 1)
lines.append(firstLine)
while line:
(firstLine, line) = chopLine(line, maxx - 1 - indent)
lines.append(indentSpaces + firstLine)
with self.cursesLock:
(y2, x2) = self.win2.getyx()
(y1, x1) = self.win1.getyx()
lines = lines[-maxy+1:] # would definitely fail if len(lines) >= maxy
nOverflow = y1 + len(lines) - maxy + 1
if nOverflow:
self.win1.move(0, 0)
for i in range(nOverflow): self.win1.deleteln()
self.win1.move(y1 - nOverflow, x1)
for line in lines:
self.win1.addstr(line + "\n")
self.win1.refresh()
self.win2.move(y2, x2)
self.win2.refresh()
def run(self):
try: curses.wrapper(self.cursesApp)
except KeyboardInterrupt: print "Interrupting curses"
def stop(self):
self.done = True