blob: a5d5c4418906d623542d36ab3be9abb2900e1d50 [file] [log] [blame]
Greg Clayton1827fc22015-09-19 00:39:09 +00001import curses, curses.panel
Greg Clayton87349242015-09-22 00:35:20 +00002import sys
3import time
Greg Clayton1827fc22015-09-19 00:39:09 +00004
5class Point(object):
6 def __init__(self, x, y):
7 self.x = x
8 self.y = y
9
10 def __repr__(self):
11 return str(self)
12
13 def __str__(self):
14 return "(x=%u, y=%u)" % (self.x, self.y)
Greg Claytonc12cc592015-10-16 00:34:18 +000015
16 def __eq__(self, rhs):
17 return self.x == rhs.x and self.y == rhs.y
18
19 def __ne__(self, rhs):
20 return self.x != rhs.x or self.y != rhs.y
Greg Clayton1827fc22015-09-19 00:39:09 +000021
22 def is_valid_coordinate(self):
23 return self.x >= 0 and self.y >= 0
24
25class Size(object):
26 def __init__(self, w, h):
27 self.w = w
28 self.h = h
29
30 def __repr__(self):
31 return str(self)
32
33 def __str__(self):
34 return "(w=%u, h=%u)" % (self.w, self.h)
35
Greg Claytonc12cc592015-10-16 00:34:18 +000036 def __eq__(self, rhs):
37 return self.w == rhs.w and self.h == rhs.h
38
39 def __ne__(self, rhs):
40 return self.w != rhs.w or self.h != rhs.h
41
Greg Clayton1827fc22015-09-19 00:39:09 +000042class Rect(object):
43 def __init__(self, x=0, y=0, w=0, h=0):
44 self.origin = Point(x, y)
45 self.size = Size(w, h)
46
47 def __repr__(self):
48 return str(self)
49
50 def __str__(self):
51 return "{ %s, %s }" % (str(self.origin), str(self.size))
52
53 def get_min_x(self):
54 return self.origin.x
55
56 def get_max_x(self):
57 return self.origin.x + self.size.w
58
59 def get_min_y(self):
60 return self.origin.y
61
62 def get_max_y(self):
63 return self.origin.y + self.size.h
64
65 def contains_point(self, pt):
66 if pt.x < self.get_max_x():
67 if pt.y < self.get_max_y():
68 if pt.x >= self.get_min_y():
69 return pt.y >= self.get_min_y()
70 return False
71
Greg Claytonc12cc592015-10-16 00:34:18 +000072 def __eq__(self, rhs):
73 return self.origin == rhs.origin and self.size == rhs.size
74
75 def __ne__(self, rhs):
76 return self.origin != rhs.origin or self.size != rhs.size
77
Greg Clayton5ea44832015-10-15 00:49:36 +000078class QuitException(Exception):
79 def __init__(self):
80 super(QuitException, self).__init__('QuitException')
81
Greg Clayton1827fc22015-09-19 00:39:09 +000082class Window(object):
Greg Clayton87349242015-09-22 00:35:20 +000083 def __init__(self, window, delegate = None, can_become_first_responder = True):
Greg Clayton1827fc22015-09-19 00:39:09 +000084 self.window = window
Greg Clayton87349242015-09-22 00:35:20 +000085 self.parent = None
86 self.delegate = delegate
87 self.children = list()
Greg Clayton37191a22015-10-07 20:00:28 +000088 self.first_responders = list()
Greg Clayton87349242015-09-22 00:35:20 +000089 self.can_become_first_responder = can_become_first_responder
Greg Clayton414dba52015-09-24 00:19:42 +000090 self.key_actions = dict()
Greg Clayton87349242015-09-22 00:35:20 +000091
92 def add_child(self, window):
93 self.children.append(window)
94 window.parent = self
Greg Claytonc12cc592015-10-16 00:34:18 +000095
96 def resize(self, size):
97 self.window.resize(size.h, size.w)
Greg Clayton414dba52015-09-24 00:19:42 +000098
Greg Claytonc12cc592015-10-16 00:34:18 +000099 def resize_child(self, child, delta_size, adjust_neighbors):
100 if child in self.children:
101 frame = self.get_frame()
102 orig_frame = child.get_frame()
103 new_frame = Rect(x=orig_frame.origin.x, y=orig_frame.origin.y, w=orig_frame.size.w + delta_size.w, h=orig_frame.size.h + delta_size.h)
104 old_child_max_x = orig_frame.get_max_x()
105 new_child_max_x = new_frame.get_max_x()
106 window_max_x = frame.get_max_x()
107 if new_child_max_x < window_max_x:
108 child.resize(new_frame.size)
109 if old_child_max_x == window_max_x:
110 new_frame.origin.x += window_max_x - new_child_max_x
111 child.set_position(new_frame.origin)
112 elif new_child_max_x > window_max_x:
113 new_frame.origin.x -= new_child_max_x - window_max_x
114 child.set_position(new_frame.origin)
115 child.resize(new_frame.size)
116
117 if adjust_neighbors:
118 #print 'orig_frame = %s\r\n' % (str(orig_frame)),
119 for curr_child in self.children:
120 if curr_child is child:
121 continue
122 curr_child_frame = curr_child.get_frame()
123 if delta_size.w != 0:
124 #print 'curr_child_frame = %s\r\n' % (str(curr_child_frame)),
125 if curr_child_frame.get_min_x() == orig_frame.get_max_x():
126 curr_child_frame.origin.x += delta_size.w
127 curr_child_frame.size.w -= delta_size.w
128 #print 'adjusted curr_child_frame = %s\r\n' % (str(curr_child_frame)),
129 curr_child.resize (curr_child_frame.size)
130 curr_child.slide_position (Size(w=delta_size.w, h=0))
131 elif curr_child_frame.get_max_x() == orig_frame.get_min_x():
132 curr_child_frame.size.w -= delta_size.w
133 #print 'adjusted curr_child_frame = %s\r\n' % (str(curr_child_frame)),
134 curr_child.resize (curr_child_frame.size)
135
Greg Clayton414dba52015-09-24 00:19:42 +0000136 def add_key_action(self, arg, callback, decription):
137 if isinstance(arg, list):
138 for key in arg:
139 self.add_key_action(key, callback, description)
140 else:
141 if isinstance(arg, ( int, long )):
142 key_action_dict = { 'key' : arg,
143 'callback' : callback,
144 'description' : decription }
145 self.key_actions[arg] = key_action_dict
146 elif isinstance(arg, basestring):
147 key_integer = ord(arg)
148 key_action_dict = { 'key' : key_integer,
149 'callback' : callback,
150 'description' : decription }
151 self.key_actions[key_integer] = key_action_dict
152 else:
153 raise ValueError
Greg Clayton72d51442015-10-13 23:16:29 +0000154
155 def draw_title_box(self, title):
156 is_in_first_responder_chain = self.is_in_first_responder_chain()
157 if is_in_first_responder_chain:
158 self.attron (curses.A_REVERSE)
159 self.box()
160 if is_in_first_responder_chain:
161 self.attroff (curses.A_REVERSE)
162 if title:
163 self.addstr(Point(x=2, y=0), ' ' + title + ' ')
164
Greg Clayton87349242015-09-22 00:35:20 +0000165 def remove_child(self, window):
166 self.children.remove(window)
Greg Clayton37191a22015-10-07 20:00:28 +0000167
168 def get_first_responder(self):
169 if len(self.first_responders):
170 return self.first_responders[-1]
171 else:
172 return None
173
Greg Clayton87349242015-09-22 00:35:20 +0000174 def set_first_responder(self, window):
175 if window.can_become_first_responder:
176 if callable(getattr(window, "hidden", None)) and window.hidden():
177 return False
178 if not window in self.children:
179 self.add_child(window)
Greg Clayton37191a22015-10-07 20:00:28 +0000180 # See if we have a current first responder, and if we do, let it know that
181 # it will be resigning as first responder
182 first_responder = self.get_first_responder()
183 if first_responder:
184 first_responder.relinquish_first_responder()
185 # Now set the first responder to "window"
186 if len(self.first_responders) == 0:
187 self.first_responders.append(window)
188 else:
189 self.first_responders[-1] = window
Greg Clayton87349242015-09-22 00:35:20 +0000190 return True
191 else:
192 return False
193
Greg Clayton37191a22015-10-07 20:00:28 +0000194 def push_first_responder(self, window):
195 # Only push the window as the new first responder if the window isn't already the first responder
196 if window != self.get_first_responder():
197 self.first_responders.append(window)
198
199 def pop_first_responder(self, window):
200 # Only pop the window from the first responder list if it is the first responder
201 if window == self.get_first_responder():
202 old_first_responder = self.first_responders.pop()
203 old_first_responder.relinquish_first_responder()
204 return True
205 else:
206 return False
207
208 def relinquish_first_responder(self):
209 '''Override if there is something that you need to do when you lose first responder status.'''
210 pass
211
212 # def resign_first_responder(self, remove_from_parent, new_first_responder):
213 # success = False
214 # if self.parent:
215 # if self.is_first_responder():
216 # self.relinquish_first_responder()
217 # if len(self.parent.first_responder):
218 # self.parent.first_responder = None
219 # success = True
220 # if remove_from_parent:
221 # self.parent.remove_child(self)
222 # if new_first_responder:
223 # self.parent.set_first_responder(new_first_responder)
224 # else:
225 # self.parent.select_next_first_responder()
226 # return success
Greg Clayton1827fc22015-09-19 00:39:09 +0000227
Greg Clayton87349242015-09-22 00:35:20 +0000228 def is_first_responder(self):
229 if self.parent:
Greg Clayton37191a22015-10-07 20:00:28 +0000230 return self.parent.get_first_responder() == self
231 else:
232 return False
233
234 def is_in_first_responder_chain(self):
235 if self.parent:
236 return self in self.parent.first_responders
Greg Clayton87349242015-09-22 00:35:20 +0000237 else:
238 return False
239
240 def select_next_first_responder(self):
Greg Clayton37191a22015-10-07 20:00:28 +0000241 if len(self.first_responders) > 1:
242 self.pop_first_responder(self.first_responders[-1])
243 else:
244 num_children = len(self.children)
245 if num_children == 1:
246 return self.set_first_responder(self.children[0])
247 for (i,window) in enumerate(self.children):
248 if window.is_first_responder():
249 break
250 if i < num_children:
251 for i in range(i+1,num_children):
252 if self.set_first_responder(self.children[i]):
253 return True
254 for i in range(0, i):
255 if self.set_first_responder(self.children[i]):
256 return True
Greg Clayton87349242015-09-22 00:35:20 +0000257
Greg Clayton1827fc22015-09-19 00:39:09 +0000258 def point_in_window(self, pt):
259 size = self.get_size()
260 return pt.x >= 0 and pt.x < size.w and pt.y >= 0 and pt.y < size.h
Greg Clayton37191a22015-10-07 20:00:28 +0000261
Greg Clayton72d51442015-10-13 23:16:29 +0000262 def addch(self, c):
263 try:
264 self.window.addch(c)
265 except:
266 pass
267
268 def addch_at_point(self, pt, c):
Greg Clayton37191a22015-10-07 20:00:28 +0000269 try:
270 self.window.addch(pt.y, pt.x, c)
271 except:
272 pass
Greg Clayton1827fc22015-09-19 00:39:09 +0000273
274 def addstr(self, pt, str):
275 try:
276 self.window.addstr(pt.y, pt.x, str)
277 except:
278 pass
279
Greg Clayton72d51442015-10-13 23:16:29 +0000280 def addnstr_at_point(self, pt, str, n):
Greg Clayton1827fc22015-09-19 00:39:09 +0000281 try:
282 self.window.addnstr(pt.y, pt.x, str, n)
283 except:
284 pass
Greg Clayton72d51442015-10-13 23:16:29 +0000285 def addnstr(self, str, n):
286 try:
287 self.window.addnstr(str, n)
288 except:
289 pass
Greg Clayton1827fc22015-09-19 00:39:09 +0000290
Greg Clayton87349242015-09-22 00:35:20 +0000291 def attron(self, attr):
292 return self.window.attron (attr)
293
294 def attroff(self, attr):
295 return self.window.attroff (attr)
296
297 def box(self, vertch=0, horch=0):
298 if vertch == 0:
299 vertch = curses.ACS_VLINE
300 if horch == 0:
301 horch = curses.ACS_HLINE
302 self.window.box(vertch, horch)
Greg Clayton1827fc22015-09-19 00:39:09 +0000303
304 def get_contained_rect(self, top_inset=0, bottom_inset=0, left_inset=0, right_inset=0, height=-1, width=-1):
305 '''Get a rectangle based on the top "height" lines of this window'''
306 rect = self.get_frame()
307 x = rect.origin.x + left_inset
308 y = rect.origin.y + top_inset
309 if height == -1:
310 h = rect.size.h - (top_inset + bottom_inset)
311 else:
312 h = height
313 if width == -1:
314 w = rect.size.w - (left_inset + right_inset)
315 else:
316 w = width
317 return Rect (x = x, y = y, w = w, h = h)
318
319 def erase(self):
320 self.window.erase()
Greg Clayton72d51442015-10-13 23:16:29 +0000321
322 def get_cursor(self):
323 (y, x) = self.window.getyx()
324 return Point(x=x, y=y)
Greg Clayton1827fc22015-09-19 00:39:09 +0000325
326 def get_frame(self):
327 position = self.get_position()
328 size = self.get_size()
329 return Rect(x=position.x, y=position.y, w=size.w, h=size.h)
330
Greg Claytonc12cc592015-10-16 00:34:18 +0000331 def get_frame_in_parent(self):
332 position = self.get_position_in_parent()
333 size = self.get_size()
334 return Rect(x=position.x, y=position.y, w=size.w, h=size.h)
335
336 def get_position_in_parent(self):
337 (y, x) = self.window.getparyx()
338 return Point(x, y)
339
Greg Clayton1827fc22015-09-19 00:39:09 +0000340 def get_position(self):
341 (y, x) = self.window.getbegyx()
342 return Point(x, y)
343
344 def get_size(self):
345 (y, x) = self.window.getmaxyx()
346 return Size(w=x, h=y)
Greg Clayton37191a22015-10-07 20:00:28 +0000347
Greg Clayton72d51442015-10-13 23:16:29 +0000348 def move(self, pt):
349 self.window.move(pt.y, pt.x)
350
Greg Clayton1827fc22015-09-19 00:39:09 +0000351 def refresh(self):
Greg Clayton87349242015-09-22 00:35:20 +0000352 self.update()
Greg Clayton1827fc22015-09-19 00:39:09 +0000353 curses.panel.update_panels()
Greg Clayton72d51442015-10-13 23:16:29 +0000354 self.move(Point(x=0, y=0))
Greg Clayton1827fc22015-09-19 00:39:09 +0000355 return self.window.refresh()
356
357 def resize(self, size):
Greg Clayton87349242015-09-22 00:35:20 +0000358 return self.window.resize(size.h, size.w)
Greg Clayton1827fc22015-09-19 00:39:09 +0000359
Greg Clayton87349242015-09-22 00:35:20 +0000360 def timeout(self, timeout_msec):
361 return self.window.timeout(timeout_msec)
362
363 def handle_key(self, key, check_parent=True):
364 '''Handle a key press in this window.'''
365
366 # First try the first responder if this window has one, but don't allow
367 # it to check with its parent (False second parameter) so we don't recurse
368 # and get a stack overflow
Greg Clayton37191a22015-10-07 20:00:28 +0000369 for first_responder in reversed(self.first_responders):
370 if first_responder.handle_key(key, False):
Greg Clayton87349242015-09-22 00:35:20 +0000371 return True
Greg Clayton414dba52015-09-24 00:19:42 +0000372
373 # Check our key map to see if we have any actions. Actions don't take
374 # any arguments, they must be callable
375 if key in self.key_actions:
376 key_action = self.key_actions[key]
377 key_action['callback']()
378 return True
379 # Check if there is a wildcard key for any key
380 if -1 in self.key_actions:
381 key_action = self.key_actions[-1]
382 key_action['callback']()
383 return True
Greg Clayton87349242015-09-22 00:35:20 +0000384 # Check if the window delegate wants to handle this key press
385 if self.delegate:
386 if callable(getattr(self.delegate, "handle_key", None)):
387 if self.delegate.handle_key(self, key):
388 return True
389 if self.delegate(self, key):
390 return True
391 # Check if we have a parent window and if so, let the parent
392 # window handle the key press
393 if check_parent and self.parent:
394 return self.parent.handle_key(key, True)
395 else:
396 return False # Key not handled
397
398 def update(self):
399 for child in self.children:
400 child.update()
Greg Clayton5ea44832015-10-15 00:49:36 +0000401
402 def quit_action(self):
403 raise QuitException
Greg Clayton87349242015-09-22 00:35:20 +0000404
405 def key_event_loop(self, timeout_msec=-1, n=sys.maxint):
406 '''Run an event loop to receive key presses and pass them along to the
407 responder chain.
408
409 timeout_msec is the timeout it milliseconds. If the value is -1, an
410 infinite wait will be used. It the value is zero, a non-blocking mode
411 will be used, and if greater than zero it will wait for a key press
412 for timeout_msec milliseconds.
413
414 n is the number of times to go through the event loop before exiting'''
415 self.timeout(timeout_msec)
Greg Clayton5ea44832015-10-15 00:49:36 +0000416 done = False
417 while not done and n > 0:
Greg Clayton87349242015-09-22 00:35:20 +0000418 c = self.window.getch()
Greg Claytonc12cc592015-10-16 00:34:18 +0000419 if c == 27:
420 self.timeout(0)
421 escape_key = 0
422 while True:
423 escape_key = self.window.getch()
424 if escape_key == -1:
425 break
426 else:
427 c = c << 8 | escape_key
428 self.timeout(timeout_msec)
Greg Clayton87349242015-09-22 00:35:20 +0000429 if c != -1:
Greg Clayton37191a22015-10-07 20:00:28 +0000430 try:
431 self.handle_key(c)
Greg Clayton5ea44832015-10-15 00:49:36 +0000432 except QuitException:
433 done = True
Greg Clayton87349242015-09-22 00:35:20 +0000434 n -= 1
435
Greg Clayton1827fc22015-09-19 00:39:09 +0000436class Panel(Window):
Greg Clayton87349242015-09-22 00:35:20 +0000437 def __init__(self, frame, delegate = None, can_become_first_responder = True):
Greg Clayton1827fc22015-09-19 00:39:09 +0000438 window = curses.newwin(frame.size.h,frame.size.w, frame.origin.y, frame.origin.x)
Greg Clayton87349242015-09-22 00:35:20 +0000439 super(Panel, self).__init__(window, delegate, can_become_first_responder)
Greg Clayton1827fc22015-09-19 00:39:09 +0000440 self.panel = curses.panel.new_panel(window)
441
Greg Clayton87349242015-09-22 00:35:20 +0000442 def hide(self):
443 return self.panel.hide()
444
445 def hidden(self):
446 return self.panel.hidden()
447
448 def show(self):
449 return self.panel.show()
450
Greg Clayton1827fc22015-09-19 00:39:09 +0000451 def top(self):
Greg Clayton87349242015-09-22 00:35:20 +0000452 return self.panel.top()
Greg Clayton1827fc22015-09-19 00:39:09 +0000453
454 def set_position(self, pt):
455 self.panel.move(pt.y, pt.x)
456
Greg Claytonc12cc592015-10-16 00:34:18 +0000457 def slide_position(self, size):
Greg Clayton1827fc22015-09-19 00:39:09 +0000458 new_position = self.get_position()
Greg Claytonc12cc592015-10-16 00:34:18 +0000459 new_position.x = new_position.x + size.w
460 new_position.y = new_position.y + size.h
Greg Clayton1827fc22015-09-19 00:39:09 +0000461 self.set_position(new_position)
462
463class BoxedPanel(Panel):
Greg Clayton87349242015-09-22 00:35:20 +0000464 def __init__(self, frame, title, delegate = None, can_become_first_responder = True):
465 super(BoxedPanel, self).__init__(frame, delegate, can_become_first_responder)
Greg Clayton1827fc22015-09-19 00:39:09 +0000466 self.title = title
467 self.lines = list()
468 self.first_visible_idx = 0
Greg Clayton87349242015-09-22 00:35:20 +0000469 self.selected_idx = -1
Greg Clayton37191a22015-10-07 20:00:28 +0000470 self.add_key_action(curses.KEY_UP, self.select_prev, "Select the previous item")
471 self.add_key_action(curses.KEY_DOWN, self.select_next, "Select the next item")
472 self.add_key_action(curses.KEY_HOME, self.scroll_begin, "Go to the beginning of the list")
473 self.add_key_action(curses.KEY_END, self.scroll_end, "Go to the end of the list")
Greg Claytonc12cc592015-10-16 00:34:18 +0000474 self.add_key_action(0x1b4f48, self.scroll_begin, "Go to the beginning of the list")
475 self.add_key_action(0x1b4f46, self.scroll_end, "Go to the end of the list")
Greg Clayton37191a22015-10-07 20:00:28 +0000476 self.add_key_action(curses.KEY_PPAGE, self.scroll_page_backward, "Scroll to previous page")
477 self.add_key_action(curses.KEY_NPAGE, self.scroll_page_forward, "Scroll to next forward")
Greg Clayton1827fc22015-09-19 00:39:09 +0000478 self.update()
479
Greg Claytond13c4fb2015-09-22 17:18:15 +0000480 def clear(self, update=True):
481 self.lines = list()
482 self.first_visible_idx = 0
483 self.selected_idx = -1
484 if update:
485 self.update()
486
Greg Clayton1827fc22015-09-19 00:39:09 +0000487 def get_usable_width(self):
488 '''Valid usable width is 0 to (width - 3) since the left and right lines display the box around
489 this frame and we skip a leading space'''
490 w = self.get_size().w
491 if w > 3:
492 return w-3
493 else:
494 return 0
495
496 def get_usable_height(self):
497 '''Valid line indexes are 0 to (height - 2) since the top and bottom lines display the box around this frame.'''
498 h = self.get_size().h
499 if h > 2:
500 return h-2
501 else:
502 return 0
503
504 def get_point_for_line(self, global_line_idx):
505 '''Returns the point to use when displaying a line whose index is "line_idx"'''
506 line_idx = global_line_idx - self.first_visible_idx
507 num_lines = self.get_usable_height()
508 if line_idx < num_lines:
509 return Point(x=2, y=1+line_idx)
510 else:
511 return Point(x=-1, y=-1) # return an invalid coordinate if the line index isn't valid
512
513 def set_title (self, title, update=True):
514 self.title = title
515 if update:
516 self.update()
517
Greg Claytonc12cc592015-10-16 00:34:18 +0000518 def scroll_to_line (self, idx):
519 if idx < len(self.lines):
520 self.selected_idx = idx
521 max_visible_lines = self.get_usable_height()
522 if idx < self.first_visible_idx or idx >= self.first_visible_idx + max_visible_lines:
523 self.first_visible_idx = idx
524 self.refresh()
525
Greg Clayton87349242015-09-22 00:35:20 +0000526 def scroll_begin (self):
527 self.first_visible_idx = 0
528 if len(self.lines) > 0:
529 self.selected_idx = 0
530 else:
531 self.selected_idx = -1
532 self.update()
533
534 def scroll_end (self):
535 max_visible_lines = self.get_usable_height()
536 num_lines = len(self.lines)
Greg Clayton414dba52015-09-24 00:19:42 +0000537 if num_lines > max_visible_lines:
Greg Clayton87349242015-09-22 00:35:20 +0000538 self.first_visible_idx = num_lines - max_visible_lines
539 else:
540 self.first_visible_idx = 0
541 self.selected_idx = num_lines-1
542 self.update()
Greg Clayton37191a22015-10-07 20:00:28 +0000543
544 def scroll_page_backward(self):
545 num_lines = len(self.lines)
546 max_visible_lines = self.get_usable_height()
547 new_index = self.first_visible_idx - max_visible_lines
548 if new_index < 0:
549 self.first_visible_idx = 0
550 else:
551 self.first_visible_idx = new_index
552 self.refresh()
553
554 def scroll_page_forward(self):
555 max_visible_lines = self.get_usable_height()
556 self.first_visible_idx += max_visible_lines
557 self._adjust_first_visible_line()
558 self.refresh()
559
Greg Clayton87349242015-09-22 00:35:20 +0000560 def select_next (self):
561 self.selected_idx += 1
562 if self.selected_idx >= len(self.lines):
563 self.selected_idx = len(self.lines) - 1
Greg Clayton37191a22015-10-07 20:00:28 +0000564 self.refresh()
Greg Clayton87349242015-09-22 00:35:20 +0000565
566 def select_prev (self):
567 self.selected_idx -= 1
568 if self.selected_idx < 0:
569 if len(self.lines) > 0:
570 self.selected_idx = 0
571 else:
572 self.selected_idx = -1
Greg Clayton37191a22015-10-07 20:00:28 +0000573 self.refresh()
Greg Clayton87349242015-09-22 00:35:20 +0000574
575 def get_selected_idx(self):
576 return self.selected_idx
577
Greg Clayton1827fc22015-09-19 00:39:09 +0000578 def _adjust_first_visible_line(self):
579 num_lines = len(self.lines)
580 max_visible_lines = self.get_usable_height()
Greg Clayton37191a22015-10-07 20:00:28 +0000581 if (self.first_visible_idx >= num_lines) or (num_lines - self.first_visible_idx) > max_visible_lines:
Greg Clayton1827fc22015-09-19 00:39:09 +0000582 self.first_visible_idx = num_lines - max_visible_lines
583
584 def append_line(self, s, update=True):
585 self.lines.append(s)
586 self._adjust_first_visible_line()
587 if update:
588 self.update()
589
590 def set_line(self, line_idx, s, update=True):
591 '''Sets a line "line_idx" within the boxed panel to be "s"'''
592 if line_idx < 0:
593 return
594 while line_idx >= len(self.lines):
595 self.lines.append('')
596 self.lines[line_idx] = s
597 self._adjust_first_visible_line()
598 if update:
599 self.update()
600
601 def update(self):
Greg Clayton72d51442015-10-13 23:16:29 +0000602 self.erase()
603 self.draw_title_box(self.title)
Greg Clayton1827fc22015-09-19 00:39:09 +0000604 max_width = self.get_usable_width()
605 for line_idx in range(self.first_visible_idx, len(self.lines)):
606 pt = self.get_point_for_line(line_idx)
607 if pt.is_valid_coordinate():
Greg Clayton87349242015-09-22 00:35:20 +0000608 is_selected = line_idx == self.selected_idx
609 if is_selected:
610 self.attron (curses.A_REVERSE)
Greg Claytonc12cc592015-10-16 00:34:18 +0000611 self.move(pt)
612 self.addnstr(self.lines[line_idx], max_width)
Greg Clayton87349242015-09-22 00:35:20 +0000613 if is_selected:
614 self.attroff (curses.A_REVERSE)
Greg Clayton1827fc22015-09-19 00:39:09 +0000615 else:
616 return
617
Greg Claytonc12cc592015-10-16 00:34:18 +0000618 def load_file(self, path):
619 f = open(path)
620 if f:
621 self.lines = f.read().splitlines()
622 for (idx, line) in enumerate(self.lines):
623 # Remove any tabs from lines since they hose up the display
624 if "\t" in line:
625 self.lines[idx] = (8*' ').join(line.split('\t'))
626 self.selected_idx = 0
627 self.first_visible_idx = 0
628 self.refresh()
629
Greg Clayton37191a22015-10-07 20:00:28 +0000630class Item(object):
631 def __init__(self, title, action):
632 self.title = title
633 self.action = action
Greg Clayton72d51442015-10-13 23:16:29 +0000634
Greg Clayton5ea44832015-10-15 00:49:36 +0000635class TreeItemDelegate(object):
636
637 def might_have_children(self):
638 return False
639
640 def update_children(self, item):
641 '''Return a list of child Item objects'''
642 return None
643
644 def draw_item_string(self, tree_window, item, s):
645 pt = tree_window.get_cursor()
646 width = tree_window.get_size().w - 1
647 if width > pt.x:
648 tree_window.addnstr(s, width - pt.x)
649
650 def draw_item(self, tree_window, item):
651 self.draw_item_string(tree_window, item, item.title)
Greg Claytonc12cc592015-10-16 00:34:18 +0000652
653 def do_action(self):
654 pass
Greg Clayton5ea44832015-10-15 00:49:36 +0000655
Greg Clayton72d51442015-10-13 23:16:29 +0000656class TreeItem(object):
657 def __init__(self, delegate, parent = None, title = None, action = None, is_expanded = False):
658 self.parent = parent
659 self.title = title
660 self.action = action
661 self.delegate = delegate
662 self.is_expanded = not parent or is_expanded == True
Greg Clayton5ea44832015-10-15 00:49:36 +0000663 self._might_have_children = None
Greg Clayton72d51442015-10-13 23:16:29 +0000664 self.children = None
Greg Clayton5ea44832015-10-15 00:49:36 +0000665 self._children_might_have_children = False
Greg Clayton72d51442015-10-13 23:16:29 +0000666
667 def get_children(self):
668 if self.is_expanded and self.might_have_children():
669 if self.children is None:
Greg Clayton5ea44832015-10-15 00:49:36 +0000670 self._children_might_have_children = False
Greg Clayton72d51442015-10-13 23:16:29 +0000671 self.children = self.update_children()
Greg Clayton5ea44832015-10-15 00:49:36 +0000672 for child in self.children:
673 if child.might_have_children():
674 self._children_might_have_children = True
675 break
Greg Clayton72d51442015-10-13 23:16:29 +0000676 else:
Greg Clayton5ea44832015-10-15 00:49:36 +0000677 self._children_might_have_children = False
Greg Clayton72d51442015-10-13 23:16:29 +0000678 self.children = None
679 return self.children
Greg Clayton5ea44832015-10-15 00:49:36 +0000680
Greg Clayton72d51442015-10-13 23:16:29 +0000681 def append_visible_items(self, items):
682 items.append(self)
683 children = self.get_children()
684 if children:
685 for child in children:
686 child.append_visible_items(items)
687
688 def might_have_children(self):
Greg Clayton5ea44832015-10-15 00:49:36 +0000689 if self._might_have_children is None:
Greg Clayton72d51442015-10-13 23:16:29 +0000690 if not self.parent:
691 # Root item always might have children
Greg Clayton5ea44832015-10-15 00:49:36 +0000692 self._might_have_children = True
Greg Clayton72d51442015-10-13 23:16:29 +0000693 else:
694 # Check with the delegate to see if the item might have children
Greg Clayton5ea44832015-10-15 00:49:36 +0000695 self._might_have_children = self.delegate.might_have_children()
696 return self._might_have_children
697
698 def children_might_have_children(self):
699 return self._children_might_have_children
700
Greg Clayton72d51442015-10-13 23:16:29 +0000701 def update_children(self):
702 if self.is_expanded and self.might_have_children():
703 self.children = self.delegate.update_children(self)
704 for child in self.children:
705 child.update_children()
706 else:
707 self.children = None
708 return self.children
Greg Clayton37191a22015-10-07 20:00:28 +0000709
Greg Clayton72d51442015-10-13 23:16:29 +0000710 def get_num_visible_rows(self):
711 rows = 1
712 if self.is_expanded:
713 children = self.get_children()
Greg Claytonc12cc592015-10-16 00:34:18 +0000714 if children:
715 for child in children:
716 rows += child.get_num_visible_rows()
Greg Clayton72d51442015-10-13 23:16:29 +0000717 return rows
718 def draw(self, tree_window, row):
719 display_row = tree_window.get_display_row(row)
720 if display_row >= 0:
721 tree_window.move(tree_window.get_item_draw_point(row))
722 if self.parent:
723 self.parent.draw_tree_for_child(tree_window, self, 0)
724 if self.might_have_children():
725 tree_window.addch (curses.ACS_DIAMOND)
726 tree_window.addch (curses.ACS_HLINE)
Greg Clayton5ea44832015-10-15 00:49:36 +0000727 elif self.parent and self.parent.children_might_have_children():
Greg Claytonc12cc592015-10-16 00:34:18 +0000728 if self.parent.parent:
729 tree_window.addch (curses.ACS_HLINE)
730 tree_window.addch (curses.ACS_HLINE)
731 else:
732 tree_window.addch (' ')
733 tree_window.addch (' ')
Greg Clayton72d51442015-10-13 23:16:29 +0000734 is_selected = tree_window.is_selected(row)
735 if is_selected:
736 tree_window.attron (curses.A_REVERSE)
737 self.delegate.draw_item(tree_window, self)
738 if is_selected:
739 tree_window.attroff (curses.A_REVERSE)
740
741 def draw_tree_for_child (self, tree_window, child, reverse_depth):
742 if self.parent:
743 self.parent.draw_tree_for_child (tree_window, self, reverse_depth + 1)
744 if self.children[-1] == child:
745 # Last child
746 if reverse_depth == 0:
747 tree_window.addch (curses.ACS_LLCORNER)
748 tree_window.addch (curses.ACS_HLINE)
749 else:
750 tree_window.addch (' ')
751 tree_window.addch (' ')
752 else:
753 # Middle child
754 if reverse_depth == 0:
755 tree_window.addch (curses.ACS_LTEE)
756 tree_window.addch (curses.ACS_HLINE)
757 else:
758 tree_window.addch (curses.ACS_VLINE)
759 tree_window.addch (' ')
760
Greg Claytonc12cc592015-10-16 00:34:18 +0000761 def was_selected(self):
762 self.delegate.do_action()
Greg Clayton72d51442015-10-13 23:16:29 +0000763
764class TreePanel(Panel):
765 def __init__(self, frame, title, root_item):
766 self.root_item = root_item
767 self.title = title
768 self.first_visible_idx = 0
769 self.selected_idx = 0
770 self.items = None
771 super(TreePanel, self).__init__(frame)
772 self.add_key_action(curses.KEY_UP, self.select_prev, "Select the previous item")
773 self.add_key_action(curses.KEY_DOWN, self.select_next, "Select the next item")
774 self.add_key_action(curses.KEY_RIGHT,self.right_arrow, "Expand an item")
775 self.add_key_action(curses.KEY_LEFT, self.left_arrow, "Unexpand an item or navigate to parent")
Greg Claytonc12cc592015-10-16 00:34:18 +0000776 self.add_key_action(curses.KEY_HOME, self.scroll_begin, "Go to the beginning of the tree")
777 self.add_key_action(curses.KEY_END, self.scroll_end, "Go to the end of the tree")
778 self.add_key_action(0x1b4f48, self.scroll_begin, "Go to the beginning of the tree")
779 self.add_key_action(0x1b4f46, self.scroll_end, "Go to the end of the tree")
Greg Clayton72d51442015-10-13 23:16:29 +0000780 self.add_key_action(curses.KEY_PPAGE, self.scroll_page_backward, "Scroll to previous page")
781 self.add_key_action(curses.KEY_NPAGE, self.scroll_page_forward, "Scroll to next forward")
782
783 def get_selected_item(self):
784 if self.selected_idx < len(self.items):
785 return self.items[self.selected_idx]
786 else:
787 return None
788
789 def select_item(self, item):
790 if self.items and item in self.items:
791 self.selected_idx = self.items.index(item)
792 return True
793 else:
794 return False
795
796 def get_visible_items(self):
797 # Clear self.items when you want to update all chidren
798 if self.items is None:
799 self.items = list()
800 children = self.root_item.get_children()
801 if children:
802 for child in children:
803 child.append_visible_items(self.items)
804 return self.items
805
806 def update(self):
807 self.erase()
808 self.draw_title_box(self.title)
809 visible_items = self.get_visible_items()
810 for (row, child) in enumerate(visible_items):
811 child.draw(self, row)
812
813 def get_item_draw_point(self, row):
814 display_row = self.get_display_row(row)
815 if display_row >= 0:
816 return Point(2, display_row + 1)
817 else:
818 return Point(-1, -1)
819
820 def get_display_row(self, row):
821 if row >= self.first_visible_idx:
822 display_row = row - self.first_visible_idx
823 if display_row < self.get_size().h-2:
824 return display_row
825 return -1
826
827 def is_selected(self, row):
828 return row == self.selected_idx
829
Greg Claytonc12cc592015-10-16 00:34:18 +0000830 def get_num_lines(self):
831 self.get_visible_items()
832 return len(self.items)
Greg Clayton72d51442015-10-13 23:16:29 +0000833
834 def get_num_visible_lines(self):
835 return self.get_size().h-2
836 def select_next (self):
837 self.selected_idx += 1
838 num_lines = self.get_num_lines()
839 if self.selected_idx >= num_lines:
Greg Claytonc12cc592015-10-16 00:34:18 +0000840 self.selected_idx = num_lines - 1
841 self._selection_changed()
Greg Clayton72d51442015-10-13 23:16:29 +0000842 self.refresh()
843
844 def select_prev (self):
845 self.selected_idx -= 1
846 if self.selected_idx < 0:
847 num_lines = self.get_num_lines()
848 if num_lines > 0:
849 self.selected_idx = 0
850 else:
851 self.selected_idx = -1
Greg Claytonc12cc592015-10-16 00:34:18 +0000852 self._selection_changed()
Greg Clayton72d51442015-10-13 23:16:29 +0000853 self.refresh()
854
855 def scroll_begin (self):
856 self.first_visible_idx = 0
857 num_lines = self.get_num_lines()
858 if num_lines > 0:
859 self.selected_idx = 0
860 else:
861 self.selected_idx = -1
Greg Claytonc12cc592015-10-16 00:34:18 +0000862 self.refresh()
Greg Clayton72d51442015-10-13 23:16:29 +0000863
864 def redisplay_tree(self):
865 self.items = None
866 self.refresh()
867
868 def right_arrow(self):
869 selected_item = self.get_selected_item()
870 if selected_item and selected_item.is_expanded == False:
871 selected_item.is_expanded = True
872 self.redisplay_tree()
873
874 def left_arrow(self):
875 selected_item = self.get_selected_item()
876 if selected_item:
877 if selected_item.is_expanded == True:
878 selected_item.is_expanded = False
879 self.redisplay_tree()
880 elif selected_item.parent:
881 if self.select_item(selected_item.parent):
882 self.refresh()
883
884
885 def scroll_end (self):
886 num_visible_lines = self.get_num_visible_lines()
Greg Claytonc12cc592015-10-16 00:34:18 +0000887 num_lines = self.get_num_lines()
Greg Clayton72d51442015-10-13 23:16:29 +0000888 if num_lines > num_visible_lines:
889 self.first_visible_idx = num_lines - num_visible_lines
890 else:
891 self.first_visible_idx = 0
892 self.selected_idx = num_lines-1
Greg Claytonc12cc592015-10-16 00:34:18 +0000893 self.refresh()
Greg Clayton72d51442015-10-13 23:16:29 +0000894
895 def scroll_page_backward(self):
896 num_visible_lines = self.get_num_visible_lines()
Greg Claytonc12cc592015-10-16 00:34:18 +0000897 new_index = self.selected_idx - num_visible_lines
Greg Clayton72d51442015-10-13 23:16:29 +0000898 if new_index < 0:
Greg Claytonc12cc592015-10-16 00:34:18 +0000899 self.selected_idx = 0
Greg Clayton72d51442015-10-13 23:16:29 +0000900 else:
Greg Claytonc12cc592015-10-16 00:34:18 +0000901 self.selected_idx = new_index
902 self._selection_changed()
Greg Clayton72d51442015-10-13 23:16:29 +0000903 self.refresh()
904
905 def scroll_page_forward(self):
Greg Claytonc12cc592015-10-16 00:34:18 +0000906 num_lines = self.get_num_lines()
Greg Clayton72d51442015-10-13 23:16:29 +0000907 num_visible_lines = self.get_num_visible_lines()
Greg Claytonc12cc592015-10-16 00:34:18 +0000908 new_index = self.selected_idx + num_visible_lines
909 if new_index >= num_lines:
910 new_index = num_lines - 1
911 self.selected_idx = new_index
912 self._selection_changed()
Greg Clayton72d51442015-10-13 23:16:29 +0000913 self.refresh()
914
Greg Claytonc12cc592015-10-16 00:34:18 +0000915 def _selection_changed(self):
916 num_lines = self.get_num_lines()
Greg Clayton72d51442015-10-13 23:16:29 +0000917 num_visible_lines = self.get_num_visible_lines()
Greg Claytonc12cc592015-10-16 00:34:18 +0000918 last_visible_index = self.first_visible_idx + num_visible_lines
919 if self.selected_idx >= last_visible_index:
920 self.first_visible_idx += (self.selected_idx - last_visible_index + 1)
921 if self.selected_idx < self.first_visible_idx:
922 self.first_visible_idx = self.selected_idx
923 if self.selected_idx >= 0 and self.selected_idx < len(self.items):
924 item = self.items[self.selected_idx]
925 item.was_selected()
Greg Clayton72d51442015-10-13 23:16:29 +0000926
927
Greg Clayton37191a22015-10-07 20:00:28 +0000928class Menu(BoxedPanel):
929 def __init__(self, title, items):
930 max_title_width = 0
931 for item in items:
932 if max_title_width < len(item.title):
933 max_title_width = len(item.title)
934 frame = Rect(x=0, y=0, w=max_title_width+4, h=len(items)+2)
935 super(Menu, self).__init__(frame, title=None, delegate=None, can_become_first_responder=True)
936 self.selected_idx = 0
937 self.title = title
938 self.items = items
939 for (item_idx, item) in enumerate(items):
940 self.set_line(item_idx, item.title)
941 self.hide()
942
943 def update(self):
944 super(Menu, self).update()
945
946 def relinquish_first_responder(self):
947 if not self.hidden():
948 self.hide()
949
950 def perform_action(self):
951 selected_idx = self.get_selected_idx()
952 if selected_idx < len(self.items):
953 action = self.items[selected_idx].action
954 if action:
955 action()
956
957class MenuBar(Panel):
958 def __init__(self, frame):
959 super(MenuBar, self).__init__(frame, can_become_first_responder=True)
960 self.menus = list()
961 self.selected_menu_idx = -1
962 self.add_key_action(curses.KEY_LEFT, self.select_prev, "Select the previous menu")
963 self.add_key_action(curses.KEY_RIGHT, self.select_next, "Select the next menu")
964 self.add_key_action(curses.KEY_DOWN, lambda: self.select(0), "Select the first menu")
965 self.add_key_action(27, self.relinquish_first_responder, "Hide current menu")
966 self.add_key_action(curses.KEY_ENTER, self.perform_action, "Select the next menu item")
967 self.add_key_action(10, self.perform_action, "Select the next menu item")
968
969 def insert_menu(self, menu, index=sys.maxint):
970 if index >= len(self.menus):
971 self.menus.append(menu)
972 else:
973 self.menus.insert(index, menu)
974 pt = self.get_position()
975 for menu in self.menus:
976 menu.set_position(pt)
977 pt.x += len(menu.title) + 5
978
979 def perform_action(self):
980 '''If no menu is visible, show the first menu. If a menu is visible, perform the action
981 associated with the selected menu item in the menu'''
982 menu_visible = False
983 for menu in self.menus:
984 if not menu.hidden():
985 menu_visible = True
986 break
987 if menu_visible:
988 menu.perform_action()
989 self.selected_menu_idx = -1
990 self._selected_menu_changed()
991 else:
992 self.select(0)
993
994 def relinquish_first_responder(self):
995 if self.selected_menu_idx >= 0:
996 self.selected_menu_idx = -1
997 self._selected_menu_changed()
998
999 def _selected_menu_changed(self):
1000 for (menu_idx, menu) in enumerate(self.menus):
1001 is_hidden = menu.hidden()
1002 if menu_idx != self.selected_menu_idx:
1003 if not is_hidden:
1004 if self.parent.pop_first_responder(menu) == False:
1005 menu.hide()
1006 for (menu_idx, menu) in enumerate(self.menus):
1007 is_hidden = menu.hidden()
1008 if menu_idx == self.selected_menu_idx:
1009 if is_hidden:
1010 menu.show()
1011 self.parent.push_first_responder(menu)
1012 menu.top()
1013 self.parent.refresh()
1014
1015 def select(self, index):
1016 if index < len(self.menus):
1017 self.selected_menu_idx = index
1018 self._selected_menu_changed()
1019
1020 def select_next (self):
1021 num_menus = len(self.menus)
1022 if self.selected_menu_idx == -1:
1023 if num_menus > 0:
1024 self.selected_menu_idx = 0
1025 self._selected_menu_changed()
1026 else:
1027 if self.selected_menu_idx + 1 < num_menus:
1028 self.selected_menu_idx += 1
1029 else:
1030 self.selected_menu_idx = -1
1031 self._selected_menu_changed()
1032
1033 def select_prev (self):
1034 num_menus = len(self.menus)
1035 if self.selected_menu_idx == -1:
1036 if num_menus > 0:
1037 self.selected_menu_idx = num_menus - 1
1038 self._selected_menu_changed()
1039 else:
1040 if self.selected_menu_idx - 1 >= 0:
1041 self.selected_menu_idx -= 1
1042 else:
1043 self.selected_menu_idx = -1
1044 self._selected_menu_changed()
1045
1046 def update(self):
1047 self.erase()
1048 is_in_first_responder_chain = self.is_in_first_responder_chain()
1049 if is_in_first_responder_chain:
1050 self.attron (curses.A_REVERSE)
1051 pt = Point(x=0, y=0)
1052 for menu in self.menus:
1053 self.addstr(pt, '| ' + menu.title + ' ')
1054 pt.x += len(menu.title) + 5
1055 self.addstr(pt, '|')
1056 width = self.get_size().w
1057 while pt.x < width:
Greg Clayton72d51442015-10-13 23:16:29 +00001058 self.addch_at_point(pt, ' ')
Greg Clayton37191a22015-10-07 20:00:28 +00001059 pt.x += 1
1060 if is_in_first_responder_chain:
1061 self.attroff (curses.A_REVERSE)
1062
1063 for menu in self.menus:
1064 menu.update()
1065
1066
Greg Clayton1827fc22015-09-19 00:39:09 +00001067class StatusPanel(Panel):
1068 def __init__(self, frame):
Greg Clayton87349242015-09-22 00:35:20 +00001069 super(StatusPanel, self).__init__(frame, delegate=None, can_become_first_responder=False)
Greg Clayton1827fc22015-09-19 00:39:09 +00001070 self.status_items = list()
1071 self.status_dicts = dict()
1072 self.next_status_x = 1
1073
1074 def add_status_item(self, name, title, format, width, value, update=True):
1075 status_item_dict = { 'name': name,
1076 'title' : title,
1077 'width' : width,
1078 'format' : format,
1079 'value' : value,
1080 'x' : self.next_status_x }
1081 index = len(self.status_items)
1082 self.status_items.append(status_item_dict)
1083 self.status_dicts[name] = index
1084 self.next_status_x += width + 2;
1085 if update:
1086 self.update()
1087
1088 def increment_status(self, name, update=True):
1089 if name in self.status_dicts:
1090 status_item_idx = self.status_dicts[name]
1091 status_item_dict = self.status_items[status_item_idx]
1092 status_item_dict['value'] = status_item_dict['value'] + 1
1093 if update:
1094 self.update()
1095
1096 def update_status(self, name, value, update=True):
1097 if name in self.status_dicts:
1098 status_item_idx = self.status_dicts[name]
1099 status_item_dict = self.status_items[status_item_idx]
1100 status_item_dict['value'] = status_item_dict['format'] % (value)
1101 if update:
1102 self.update()
1103 def update(self):
1104 self.erase();
1105 for status_item_dict in self.status_items:
Greg Clayton72d51442015-10-13 23:16:29 +00001106 self.addnstr_at_point(Point(x=status_item_dict['x'], y=0), '%s: %s' % (status_item_dict['title'], status_item_dict['value']), status_item_dict['width'])
Greg Clayton1827fc22015-09-19 00:39:09 +00001107
1108stdscr = None
1109
1110def intialize_curses():
1111 global stdscr
1112 stdscr = curses.initscr()
1113 curses.noecho()
1114 curses.cbreak()
1115 stdscr.keypad(1)
1116 try:
1117 curses.start_color()
1118 except:
1119 pass
1120 return Window(stdscr)
1121
1122def terminate_curses():
1123 global stdscr
1124 if stdscr:
1125 stdscr.keypad(0)
1126 curses.echo()
1127 curses.nocbreak()
1128 curses.endwin()
1129