-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.py
282 lines (213 loc) · 8.23 KB
/
client.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
# https://github.com/sushi-irc/nigiri
import urwid
import sys
import extends
import re
from extends import *
from urwid import MetaSignals
from block_type import BlockType
class ClientWindow(object):
__metaclass__ = MetaSignals
signals = ["quit", "keypress", "tab_switched"]
_palette = [
('divider', '', '', '', '#fff', '#2c5'),
('text', 'light gray', 'default'),
('bold_text', 'light gray', 'default', 'bold'),
('warning_text', '', '', '', '#e1d', '#fff'),
('pending_text', '', '', '', '#bbb', '#fff'),
('confirmed_text', '', '', '', '#2c5', '#fff'),
("body", '', '', '', '#f00', '#fff'),
("footer", "text"),
("header", "text"),
]
for type, bg in (
("div_fg_", "dark cyan"),
("", "default")):
for name, color in (
("red", "dark red"),
("blue", "dark blue"),
("green", "dark green"),
("yellow", "yellow"),
("magenta", "dark magenta"),
("gray", "light gray"),
("white", "white"),
("black", "black")):
_palette.append((type + name, color, bg))
def __init__(self, blockchain, peers, msgq):
self.shall_quit = False
self.blockchain = blockchain
self.peers = peers
self.msgq = msgq
self.texts = ["empty"]
def start(self):
""" entry point to start UI """
self.ui = urwid.raw_display.Screen()
self.ui.set_terminal_properties(colors=256)
self.ui.register_palette(self._palette)
self.build_interface()
self.ui.run_wrapper(self.run)
def run(self):
""" setup input handler, invalidate handler to
automatically redraw the interface if needed.
connect to dbus, start mainloop.
"""
def input_cb(key):
if self.shall_quit:
raise urwid.ExitMainLoop
self.keypress(self.size, key)
self.size = self.ui.get_cols_rows()
self.main_loop = urwid.MainLoop(
self.context,
screen=self.ui,
handle_mouse=False,
unhandled_input=input_cb,
)
def call_redraw(*x):
self.draw_interface()
invalidate.locked = False
return True
inv = urwid.canvas.CanvasCache.invalidate
def invalidate (cls, *a, **k):
inv(*a, **k)
if not invalidate.locked:
invalidate.locked = True
self.main_loop.set_alarm_in(0, call_redraw)
invalidate.locked = False
urwid.canvas.CanvasCache.invalidate = classmethod(invalidate)
try:
self.main_loop.run()
except KeyboardInterrupt:
self.quit()
def quit(self, _exit=True):
""" stops the ui, exits the application (if exit=True)
After the UI is stopped, the config is written.
"""
urwid.emit_signal(self, "quit")
self.shall_quit = True
if _exit:
sys.exit(0)
def _create_widgets(self):
""" create the UI widgets """
self.header = urwid.Text(" SHOUT ", align="center")
self.footer = extends.Edit.ExtendedEdit("> ")
self.divider = urwid.Text(" Shout your message: ")
self.generic_output_walker = urwid.SimpleListWalker([])
self.body = extends.ListBox.ExtendedListBox(self.generic_output_walker)
urwid.connect_signal(self.body, "set_auto_scroll", self.handle_body_auto_scroll)
def _setup_widgets(self):
""" set coloring and attributes of the UI widgets
created in _create_widgets
"""
self.header = urwid.AttrWrap(self.header, "divider")
self.footer = urwid.AttrWrap(self.footer, "footer")
self.divider = urwid.AttrWrap(self.divider, "divider")
self.body = urwid.AttrWrap(self.body, "body")
self.footer.set_wrap_mode("space")
def _setup_context(self):
""" wrap a Frame called context around the widgets
created in _create_widgets
"""
self.context = urwid.Frame(self.body, header=self.header, footer=self.divider)
self.context = urwid.Frame(self.context, footer=self.footer)
self.context.set_focus("footer")
def build_interface(self):
""" call the widget methods to build the UI """
self._create_widgets()
self._setup_widgets()
self._setup_context()
def draw_interface(self):
self.main_loop.draw_screen()
def keypress(self, size, key):
""" handle keypress events """
urwid.emit_signal(self, "keypress", size, key)
if key == "window resize":
self.size = self.ui.get_cols_rows()
elif key == "enter":
text = self.footer.get_edit_text()
self.footer.set_edit_text(" "*len(text))
self.footer.set_edit_text("")
p = re.compile(ur'^name:(.+)')
match = re.search(p, text)
if(match != None):
name = match.group(1).strip()
self.msgq.user_id = name
self.print_text("Changed your name to: " + name, "warning_text")
else:
# self.print_text(text, "pending_text")
self.msgq.add_message(text)
elif key == "up":
w = self.generic_output_walker
prev = w.get_prev(w.get_focus()[1])[1]
if prev is not None:
w.set_focus(prev)
# self.body.keypress(size, key)
elif key == "ctrl b":
self.print_text(str(self.blockchain), "confirmed_text")
elif key == "ctrl p":
self.print_text(str(self.peers), "confirmed_text")
elif key == "down":
w = self.generic_output_walker
next = w.get_next(w.get_focus()[1])[1]
if next is not None:
w.set_focus(next)
elif key == "ctrl u":
# clear the edit line
self.footer.set_edit_text ("")
self.footer.set_edit_pos (0)
elif key == "ctrl w":
# remove the text from cursor
# position to previous space
def ctrlw(et, ep):
i = et[:ep].rfind(" ")
if i == -1:
et = et[ep:]
else:
et = et[:i+1] + et[ep:]
return et
# FIXME: fix position setting
new = ctrlw(
self.footer.get_edit_text(),
self.footer.edit_pos)
self.footer.set_edit_text(new)
else:
self.context.keypress(size, key)
def print_text(self, text, format="confirmed_text"):
"""print the given text in the _current_ window"""
walker = self.generic_output_walker
if text and text[-1] == "\n":
text = text[:-1]
text_obj = urwid.Text((format, text))
walker.append(text_obj)
walker.set_focus(len(walker) - 1)
self.draw_interface()
return text_obj
def update(self):
for index, block in enumerate(self.blockchain.items):
type = block.block_type
if type != BlockType.empty:
format = "confirmed_text"
text = block.creator_id + ": " + block.payload
if type == BlockType.nSync:
format = "pending_text"
text = "Missing blocks..."
if block.blocksRequested == block.maxRequests:
text = "Older chats omitted."
if index < len(self.texts):
handle = self.texts[index]
if handle.text != text:
handle.set_text((format, text))
self.draw_interface()
else:
self.texts.append(self.print_text(text, format))
# Signal handlers
def handle_body_auto_scroll(self, auto_scroll):
self.body.auto_scroll = auto_scroll
# if __name__ == "__main__":
# global main_window, stderr
# window = ClientWindow()
# # sys.excepthook = except_hook
# # signals.setup(window)
# # messages.setup(window)
# # tabcompletion.setup(window)
#
# window.start()