This repository has been archived by the owner on Jan 7, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ui.py
226 lines (200 loc) · 6.94 KB
/
ui.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
#ui.py
#Copyright (C) 2011 Russell Cohen <rcoh@mit.edu>
# Ally Gale <allygale@gmail.com>
#
# This file is part of Rally.
#
# Rally is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# Rally is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Rally. If not, see
# <http://www.gnu.org/licenses/>.
import curses
import curses.ascii
import sys
import time
import math
from util import get_logger
from rally import ReliableChatClient
from model import Message
import threading
import notify
chat_height = 3
class RallyCursesUI(object):
def __init__(self):
self.ready = threading.Semaphore(0)
self.ui_lock = threading.RLock()
self.last_state = ([], {})
self.logger = get_logger(self)
notify.init('Rally')
def notify(self, title, msg):
"""Desktop notifications"""
notify.send(title, msg)
def start(self):
self.init_curses()
self.ready.release()
self.die = False
self.main_loop()
def init_curses(self):
with self.ui_lock:
self.stdscr = curses.initscr()
curses.start_color()
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_RED)
curses.cbreak()
curses.noecho()
self.update_size()
self.create_panels()
def update_size(self):
self.maxyx = self.stdscr.getmaxyx()
def create_panels(self):
my, mx = self.maxyx
self.new_msg_panel = curses.newwin(chat_height, mx, my-chat_height, 0)
self.new_msg_panel.keypad(1)
self.old_chats = curses.newwin(my-chat_height, mx, 0, 0)
self.draw_input_box()
self.old_chats.refresh()
def main_loop(self):
while 1:
self.logger.info('active ui thread count: ' + str(threading.active_count()))
self.read_next_message()
def close(self):
curses.nocbreak()
self.stdscr.keypad(0)
curses.echo()
curses.endwin()
def draw_input_box(self):
self.new_msg_panel.box()
def total_lines_required(self, messages, acked_dict, width):
return sum([self.lines_required(m, m.get_hash() in acked_dict, width)
for m in messages])
def lines_required(self, message, acked, width):
return int(math.ceil((len(self.get_message_text(message, acked)) +
message.content.count('\n'))/float(width)))
def get_message_text(self, message, acked):
localtime = time.localtime(message.timestamp)
base = message.sender + '(' + \
time.strftime("%H:%M", localtime) + '): ' + message.content
if acked:
return base
else:
return base + ' *unreceived'
def render_chats(self, message_pile, acked_dict):
self.block_until_ready()
with self.ui_lock:
self.last_state = (message_pile, acked_dict)
height, width = self.old_chats.getmaxyx()
self.old_chats.erase()
if self.total_lines_required(message_pile, acked_dict, width) < height:
#we can render top down
for message in message_pile:
acked = message.get_hash() in acked_dict
color = curses.COLOR_BLACK if acked else curses.color_pair(1)
self.old_chats.addstr(self.get_message_text(message, acked) + '\n', color)
else:
#we have to render bottom up
cur_y = height
message_index = -1
while cur_y > 0 and message_index * -1 < len(message_pile):
msg = message_pile[message_index]
lines_required = self.lines_required(msg, msg.get_hash() in acked_dict, width)
cur_y -= lines_required
if cur_y >= 0:
color = curses.COLOR_BLACK if \
msg.get_hash() in acked_dict else curses.color_pair(1)
self.old_chats.addstr(cur_y, 0, self.get_message_text(
msg, msg.get_hash() in acked_dict), color)
message_index -= 1
self.old_chats.refresh()
self.new_msg_panel.refresh()
def block_until_ready(self):
self.ready.acquire()
self.ready.release()
def new_outgoing_message(self, message):
"""To be overriden"""
raise NotImplementedError
def new_content_message(self, message):
self.notify(message.sender + ' says:', message.content)
def handle_resize(self):
self.ready.acquire() #we aren't ready
curses.endwin()
self.update_size()
self.create_panels()
self.ready.release() #now we are
self.render_chats(*self.last_state)
def get_str_scrolling(self, window, start):
"""
reads a str. it will call instance functions on scrolling etc.
"""
chars = ''
xpos, ypos = start
while 1:
self.block_until_ready()
new_chr = self.new_msg_panel.getch(ypos, xpos)
if new_chr == curses.KEY_DOWN:
pass
elif new_chr == curses.KEY_UP:
pass
elif new_chr == curses.KEY_LEFT:
if xpos > 1:
xpos -= 1
elif new_chr == curses.KEY_RIGHT:
if xpos <= len(chars):
xpos += 1
#checking ascii.DEL for mac compatibility
elif new_chr == curses.KEY_BACKSPACE or new_chr == curses.ascii.DEL:
if xpos > 1:
xpos -= 1
if xpos == len(chars): #deleting from end
chars = chars[:-1]
else:
chars = chars[:xpos] + chars[xpos+1:]
elif curses.ascii.isalnum(new_chr):
self.logger.info('chars: ' + str(len(chars)))
self.logger.info('max: ' + str(self.max_message_length()))
if len(chars) + 1 <= self.max_message_length():
chars = chars[:xpos-1] + chr(new_chr) + chars[xpos-1:]
xpos += 1
else:
self.logger.error('end of line')
curses.beep() #for some reason the beep isn't happening...
elif new_chr == curses.ascii.LF:
break
elif new_chr == curses.KEY_RESIZE:
self.handle_resize()
else:
chr_str = ''
if new_chr < 255 and new_chr > 0:
chr_str = chr(new_chr)
if len(chars) + 1 <= self.max_message_length():
chars = chars[:xpos-1] + chr_str + chars[xpos-1:]
xpos += 1
else:
self.logger.error('out of space')
curses.flash()
else:
continue
self.new_msg_panel.addstr(1, 1, '')
self.new_msg_panel.addstr(start[0], start[1], chars + ' ')
self.new_msg_panel.refresh()
return chars
def max_message_length(self):
return self.maxyx[1] - 2
def read_next_message(self):
msg = self.get_str_scrolling(self.new_msg_panel, (1,1))
if msg == None:
return True
with self.ui_lock:
self.new_outgoing_message(msg)
self.new_msg_panel.addstr(1, 1, '')
self.new_msg_panel.clrtoeol()
self.draw_input_box()
self.new_msg_panel.refresh()
return True