-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathChatUI.py
More file actions
89 lines (71 loc) · 2.84 KB
/
ChatUI.py
File metadata and controls
89 lines (71 loc) · 2.84 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
import curses
import logging
from Network import Message
class ChatInterface:
def __init__(self, stdscr, chatbox_lines=2):
stdscr.clear()
stdscr.scrollok(True)
curses.use_default_colors()
# nlines, ncols, begin_y, begin_x
win_messages_props = [curses.LINES - chatbox_lines, curses.COLS, 0, 0]
win_chatbox_props = [chatbox_lines, curses.COLS,
curses.LINES - chatbox_lines, 0]
self.win_messages = stdscr.derwin(*win_messages_props)
self.win_messages.scrollok(True)
self.win_chatbox = stdscr.derwin(*win_chatbox_props)
self.stdscr = stdscr
self.chatbuffer = []
self.stdscr.refresh()
def redraw_chatbox(self):
self.win_chatbox.clear()
message = ''.join(self.chatbuffer)
self.win_chatbox.addstr(0, 0, message)
self.win_chatbox.refresh()
def get_input(self, prompt=''):
del self.chatbuffer[:]
self.chatbuffer.append(prompt)
self.redraw_chatbox()
while True:
inch = self.win_chatbox.getch()
xpos = self.win_chatbox.getyx()[1]
if inch == curses.KEY_BACKSPACE or inch == 127:
if len(self.chatbuffer) - 1 > 0:
self.chatbuffer.pop()
elif inch == ord('\n'):
message = ''.join(self.chatbuffer[1:])
del self.chatbuffer[:]
self.redraw_chatbox()
return message
elif xpos >= self.win_chatbox.getmaxyx()[1] - 2:
continue
elif 32 <= inch <= 255:
self.chatbuffer.append(chr(inch))
self.redraw_chatbox()
def add_message(self, message, username=''):
if type(message) is str:
if not message.endswith('\n'):
message = message + '\n'
if username:
self.win_messages.addstr('{')
self.win_messages.addstr(username)
self.win_messages.addstr('}: ')
self.win_messages.addstr(message)
self.win_messages.refresh()
elif isinstance(message, Message) and message.msgtype == Message.CHAT:
msgtext = ''
if not message.text.endswith('\n'):
msgtext = message.text + '\n'
else:
msgtext = message.text
if message.username:
self.win_messages.addstr('{')
self.win_messages.addstr(message.username)
self.win_messages.addstr('}: ')
elif username:
self.win_messages.addstr('{')
self.win_messages.addstr(username)
self.win_messages.addstr('}: ')
self.win_messages.addstr(msgtext)
self.win_messages.refresh()
else:
logging.error('Msg is broken: ' + str(message))