blob: 98b09d90f912e71e724c784c490d135b6a4bb61e [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
Greg Clayton3fd1f742015-10-16 23:34:40 +0000405 def get_key(self, timeout_msec=-1):
406 self.timeout(timeout_msec)
407 done = False
408 c = self.window.getch()
409 if c == 27:
410 self.timeout(0)
411 escape_key = 0
412 while True:
413 escape_key = self.window.getch()
414 if escape_key == -1:
415 break
416 else:
417 c = c << 8 | escape_key
418 self.timeout(timeout_msec)
419 return c
420
Greg Clayton87349242015-09-22 00:35:20 +0000421 def key_event_loop(self, timeout_msec=-1, n=sys.maxint):
422 '''Run an event loop to receive key presses and pass them along to the
423 responder chain.
424
425 timeout_msec is the timeout it milliseconds. If the value is -1, an
426 infinite wait will be used. It the value is zero, a non-blocking mode
427 will be used, and if greater than zero it will wait for a key press
428 for timeout_msec milliseconds.
429
430 n is the number of times to go through the event loop before exiting'''
Greg Clayton5ea44832015-10-15 00:49:36 +0000431 done = False
432 while not done and n > 0:
Greg Clayton3fd1f742015-10-16 23:34:40 +0000433 c = self.get_key(timeoue_msec)
Greg Clayton87349242015-09-22 00:35:20 +0000434 if c != -1:
Greg Clayton37191a22015-10-07 20:00:28 +0000435 try:
436 self.handle_key(c)
Greg Clayton5ea44832015-10-15 00:49:36 +0000437 except QuitException:
438 done = True
Greg Clayton87349242015-09-22 00:35:20 +0000439 n -= 1
440
Greg Clayton1827fc22015-09-19 00:39:09 +0000441class Panel(Window):
Greg Clayton87349242015-09-22 00:35:20 +0000442 def __init__(self, frame, delegate = None, can_become_first_responder = True):
Greg Clayton1827fc22015-09-19 00:39:09 +0000443 window = curses.newwin(frame.size.h,frame.size.w, frame.origin.y, frame.origin.x)
Greg Clayton87349242015-09-22 00:35:20 +0000444 super(Panel, self).__init__(window, delegate, can_become_first_responder)
Greg Clayton1827fc22015-09-19 00:39:09 +0000445 self.panel = curses.panel.new_panel(window)
446
Greg Clayton87349242015-09-22 00:35:20 +0000447 def hide(self):
448 return self.panel.hide()
449
450 def hidden(self):
451 return self.panel.hidden()
452
453 def show(self):
454 return self.panel.show()
455
Greg Clayton1827fc22015-09-19 00:39:09 +0000456 def top(self):
Greg Clayton87349242015-09-22 00:35:20 +0000457 return self.panel.top()
Greg Clayton1827fc22015-09-19 00:39:09 +0000458
459 def set_position(self, pt):
460 self.panel.move(pt.y, pt.x)
461
Greg Claytonc12cc592015-10-16 00:34:18 +0000462 def slide_position(self, size):
Greg Clayton1827fc22015-09-19 00:39:09 +0000463 new_position = self.get_position()
Greg Claytonc12cc592015-10-16 00:34:18 +0000464 new_position.x = new_position.x + size.w
465 new_position.y = new_position.y + size.h
Greg Clayton1827fc22015-09-19 00:39:09 +0000466 self.set_position(new_position)
467
468class BoxedPanel(Panel):
Greg Clayton87349242015-09-22 00:35:20 +0000469 def __init__(self, frame, title, delegate = None, can_become_first_responder = True):
470 super(BoxedPanel, self).__init__(frame, delegate, can_become_first_responder)
Greg Clayton1827fc22015-09-19 00:39:09 +0000471 self.title = title
472 self.lines = list()
473 self.first_visible_idx = 0
Greg Clayton87349242015-09-22 00:35:20 +0000474 self.selected_idx = -1
Greg Clayton37191a22015-10-07 20:00:28 +0000475 self.add_key_action(curses.KEY_UP, self.select_prev, "Select the previous item")
476 self.add_key_action(curses.KEY_DOWN, self.select_next, "Select the next item")
477 self.add_key_action(curses.KEY_HOME, self.scroll_begin, "Go to the beginning of the list")
478 self.add_key_action(curses.KEY_END, self.scroll_end, "Go to the end of the list")
Greg Claytonc12cc592015-10-16 00:34:18 +0000479 self.add_key_action(0x1b4f48, self.scroll_begin, "Go to the beginning of the list")
480 self.add_key_action(0x1b4f46, self.scroll_end, "Go to the end of the list")
Greg Clayton37191a22015-10-07 20:00:28 +0000481 self.add_key_action(curses.KEY_PPAGE, self.scroll_page_backward, "Scroll to previous page")
482 self.add_key_action(curses.KEY_NPAGE, self.scroll_page_forward, "Scroll to next forward")
Greg Clayton1827fc22015-09-19 00:39:09 +0000483 self.update()
484
Greg Claytond13c4fb2015-09-22 17:18:15 +0000485 def clear(self, update=True):
486 self.lines = list()
487 self.first_visible_idx = 0
488 self.selected_idx = -1
489 if update:
490 self.update()
491
Greg Clayton1827fc22015-09-19 00:39:09 +0000492 def get_usable_width(self):
493 '''Valid usable width is 0 to (width - 3) since the left and right lines display the box around
494 this frame and we skip a leading space'''
495 w = self.get_size().w
496 if w > 3:
497 return w-3
498 else:
499 return 0
500
501 def get_usable_height(self):
502 '''Valid line indexes are 0 to (height - 2) since the top and bottom lines display the box around this frame.'''
503 h = self.get_size().h
504 if h > 2:
505 return h-2
506 else:
507 return 0
508
509 def get_point_for_line(self, global_line_idx):
510 '''Returns the point to use when displaying a line whose index is "line_idx"'''
511 line_idx = global_line_idx - self.first_visible_idx
512 num_lines = self.get_usable_height()
513 if line_idx < num_lines:
514 return Point(x=2, y=1+line_idx)
515 else:
516 return Point(x=-1, y=-1) # return an invalid coordinate if the line index isn't valid
517
518 def set_title (self, title, update=True):
519 self.title = title
520 if update:
521 self.update()
522
Greg Claytonc12cc592015-10-16 00:34:18 +0000523 def scroll_to_line (self, idx):
524 if idx < len(self.lines):
525 self.selected_idx = idx
526 max_visible_lines = self.get_usable_height()
527 if idx < self.first_visible_idx or idx >= self.first_visible_idx + max_visible_lines:
528 self.first_visible_idx = idx
529 self.refresh()
530
Greg Clayton87349242015-09-22 00:35:20 +0000531 def scroll_begin (self):
532 self.first_visible_idx = 0
533 if len(self.lines) > 0:
534 self.selected_idx = 0
535 else:
536 self.selected_idx = -1
537 self.update()
538
539 def scroll_end (self):
540 max_visible_lines = self.get_usable_height()
541 num_lines = len(self.lines)
Greg Clayton414dba52015-09-24 00:19:42 +0000542 if num_lines > max_visible_lines:
Greg Clayton87349242015-09-22 00:35:20 +0000543 self.first_visible_idx = num_lines - max_visible_lines
544 else:
545 self.first_visible_idx = 0
546 self.selected_idx = num_lines-1
547 self.update()
Greg Clayton37191a22015-10-07 20:00:28 +0000548
549 def scroll_page_backward(self):
550 num_lines = len(self.lines)
551 max_visible_lines = self.get_usable_height()
552 new_index = self.first_visible_idx - max_visible_lines
553 if new_index < 0:
554 self.first_visible_idx = 0
555 else:
556 self.first_visible_idx = new_index
557 self.refresh()
558
559 def scroll_page_forward(self):
560 max_visible_lines = self.get_usable_height()
561 self.first_visible_idx += max_visible_lines
562 self._adjust_first_visible_line()
563 self.refresh()
564
Greg Clayton87349242015-09-22 00:35:20 +0000565 def select_next (self):
566 self.selected_idx += 1
567 if self.selected_idx >= len(self.lines):
568 self.selected_idx = len(self.lines) - 1
Greg Clayton37191a22015-10-07 20:00:28 +0000569 self.refresh()
Greg Clayton87349242015-09-22 00:35:20 +0000570
571 def select_prev (self):
572 self.selected_idx -= 1
573 if self.selected_idx < 0:
574 if len(self.lines) > 0:
575 self.selected_idx = 0
576 else:
577 self.selected_idx = -1
Greg Clayton37191a22015-10-07 20:00:28 +0000578 self.refresh()
Greg Clayton87349242015-09-22 00:35:20 +0000579
580 def get_selected_idx(self):
581 return self.selected_idx
582
Greg Clayton1827fc22015-09-19 00:39:09 +0000583 def _adjust_first_visible_line(self):
584 num_lines = len(self.lines)
585 max_visible_lines = self.get_usable_height()
Greg Clayton37191a22015-10-07 20:00:28 +0000586 if (self.first_visible_idx >= num_lines) or (num_lines - self.first_visible_idx) > max_visible_lines:
Greg Clayton1827fc22015-09-19 00:39:09 +0000587 self.first_visible_idx = num_lines - max_visible_lines
588
589 def append_line(self, s, update=True):
590 self.lines.append(s)
591 self._adjust_first_visible_line()
592 if update:
593 self.update()
594
595 def set_line(self, line_idx, s, update=True):
596 '''Sets a line "line_idx" within the boxed panel to be "s"'''
597 if line_idx < 0:
598 return
599 while line_idx >= len(self.lines):
600 self.lines.append('')
601 self.lines[line_idx] = s
602 self._adjust_first_visible_line()
603 if update:
604 self.update()
605
606 def update(self):
Greg Clayton72d51442015-10-13 23:16:29 +0000607 self.erase()
608 self.draw_title_box(self.title)
Greg Clayton1827fc22015-09-19 00:39:09 +0000609 max_width = self.get_usable_width()
610 for line_idx in range(self.first_visible_idx, len(self.lines)):
611 pt = self.get_point_for_line(line_idx)
612 if pt.is_valid_coordinate():
Greg Clayton87349242015-09-22 00:35:20 +0000613 is_selected = line_idx == self.selected_idx
614 if is_selected:
615 self.attron (curses.A_REVERSE)
Greg Claytonc12cc592015-10-16 00:34:18 +0000616 self.move(pt)
617 self.addnstr(self.lines[line_idx], max_width)
Greg Clayton87349242015-09-22 00:35:20 +0000618 if is_selected:
619 self.attroff (curses.A_REVERSE)
Greg Clayton1827fc22015-09-19 00:39:09 +0000620 else:
621 return
622
Greg Claytonc12cc592015-10-16 00:34:18 +0000623 def load_file(self, path):
624 f = open(path)
625 if f:
626 self.lines = f.read().splitlines()
627 for (idx, line) in enumerate(self.lines):
628 # Remove any tabs from lines since they hose up the display
629 if "\t" in line:
630 self.lines[idx] = (8*' ').join(line.split('\t'))
631 self.selected_idx = 0
632 self.first_visible_idx = 0
633 self.refresh()
634
Greg Clayton37191a22015-10-07 20:00:28 +0000635class Item(object):
636 def __init__(self, title, action):
637 self.title = title
638 self.action = action
Greg Clayton72d51442015-10-13 23:16:29 +0000639
Greg Clayton5ea44832015-10-15 00:49:36 +0000640class TreeItemDelegate(object):
641
642 def might_have_children(self):
643 return False
644
645 def update_children(self, item):
646 '''Return a list of child Item objects'''
647 return None
648
649 def draw_item_string(self, tree_window, item, s):
650 pt = tree_window.get_cursor()
651 width = tree_window.get_size().w - 1
652 if width > pt.x:
653 tree_window.addnstr(s, width - pt.x)
654
655 def draw_item(self, tree_window, item):
656 self.draw_item_string(tree_window, item, item.title)
Greg Claytonc12cc592015-10-16 00:34:18 +0000657
658 def do_action(self):
659 pass
Greg Clayton5ea44832015-10-15 00:49:36 +0000660
Greg Clayton72d51442015-10-13 23:16:29 +0000661class TreeItem(object):
662 def __init__(self, delegate, parent = None, title = None, action = None, is_expanded = False):
663 self.parent = parent
664 self.title = title
665 self.action = action
666 self.delegate = delegate
667 self.is_expanded = not parent or is_expanded == True
Greg Clayton5ea44832015-10-15 00:49:36 +0000668 self._might_have_children = None
Greg Clayton72d51442015-10-13 23:16:29 +0000669 self.children = None
Greg Clayton5ea44832015-10-15 00:49:36 +0000670 self._children_might_have_children = False
Greg Clayton72d51442015-10-13 23:16:29 +0000671
672 def get_children(self):
673 if self.is_expanded and self.might_have_children():
674 if self.children is None:
Greg Clayton5ea44832015-10-15 00:49:36 +0000675 self._children_might_have_children = False
Greg Clayton72d51442015-10-13 23:16:29 +0000676 self.children = self.update_children()
Greg Clayton5ea44832015-10-15 00:49:36 +0000677 for child in self.children:
678 if child.might_have_children():
679 self._children_might_have_children = True
680 break
Greg Clayton72d51442015-10-13 23:16:29 +0000681 else:
Greg Clayton5ea44832015-10-15 00:49:36 +0000682 self._children_might_have_children = False
Greg Clayton72d51442015-10-13 23:16:29 +0000683 self.children = None
684 return self.children
Greg Clayton5ea44832015-10-15 00:49:36 +0000685
Greg Clayton72d51442015-10-13 23:16:29 +0000686 def append_visible_items(self, items):
687 items.append(self)
688 children = self.get_children()
689 if children:
690 for child in children:
691 child.append_visible_items(items)
692
693 def might_have_children(self):
Greg Clayton5ea44832015-10-15 00:49:36 +0000694 if self._might_have_children is None:
Greg Clayton72d51442015-10-13 23:16:29 +0000695 if not self.parent:
696 # Root item always might have children
Greg Clayton5ea44832015-10-15 00:49:36 +0000697 self._might_have_children = True
Greg Clayton72d51442015-10-13 23:16:29 +0000698 else:
699 # Check with the delegate to see if the item might have children
Greg Clayton5ea44832015-10-15 00:49:36 +0000700 self._might_have_children = self.delegate.might_have_children()
701 return self._might_have_children
702
703 def children_might_have_children(self):
704 return self._children_might_have_children
705
Greg Clayton72d51442015-10-13 23:16:29 +0000706 def update_children(self):
707 if self.is_expanded and self.might_have_children():
708 self.children = self.delegate.update_children(self)
709 for child in self.children:
710 child.update_children()
711 else:
712 self.children = None
713 return self.children
Greg Clayton37191a22015-10-07 20:00:28 +0000714
Greg Clayton72d51442015-10-13 23:16:29 +0000715 def get_num_visible_rows(self):
716 rows = 1
717 if self.is_expanded:
718 children = self.get_children()
Greg Claytonc12cc592015-10-16 00:34:18 +0000719 if children:
720 for child in children:
721 rows += child.get_num_visible_rows()
Greg Clayton72d51442015-10-13 23:16:29 +0000722 return rows
723 def draw(self, tree_window, row):
724 display_row = tree_window.get_display_row(row)
725 if display_row >= 0:
726 tree_window.move(tree_window.get_item_draw_point(row))
727 if self.parent:
728 self.parent.draw_tree_for_child(tree_window, self, 0)
729 if self.might_have_children():
730 tree_window.addch (curses.ACS_DIAMOND)
731 tree_window.addch (curses.ACS_HLINE)
Greg Clayton5ea44832015-10-15 00:49:36 +0000732 elif self.parent and self.parent.children_might_have_children():
Greg Claytonc12cc592015-10-16 00:34:18 +0000733 if self.parent.parent:
734 tree_window.addch (curses.ACS_HLINE)
735 tree_window.addch (curses.ACS_HLINE)
736 else:
737 tree_window.addch (' ')
738 tree_window.addch (' ')
Greg Clayton72d51442015-10-13 23:16:29 +0000739 is_selected = tree_window.is_selected(row)
740 if is_selected:
741 tree_window.attron (curses.A_REVERSE)
742 self.delegate.draw_item(tree_window, self)
743 if is_selected:
744 tree_window.attroff (curses.A_REVERSE)
745
746 def draw_tree_for_child (self, tree_window, child, reverse_depth):
747 if self.parent:
748 self.parent.draw_tree_for_child (tree_window, self, reverse_depth + 1)
749 if self.children[-1] == child:
750 # Last child
751 if reverse_depth == 0:
752 tree_window.addch (curses.ACS_LLCORNER)
753 tree_window.addch (curses.ACS_HLINE)
754 else:
755 tree_window.addch (' ')
756 tree_window.addch (' ')
757 else:
758 # Middle child
759 if reverse_depth == 0:
760 tree_window.addch (curses.ACS_LTEE)
761 tree_window.addch (curses.ACS_HLINE)
762 else:
763 tree_window.addch (curses.ACS_VLINE)
764 tree_window.addch (' ')
765
Greg Claytonc12cc592015-10-16 00:34:18 +0000766 def was_selected(self):
767 self.delegate.do_action()
Greg Clayton72d51442015-10-13 23:16:29 +0000768
769class TreePanel(Panel):
770 def __init__(self, frame, title, root_item):
771 self.root_item = root_item
772 self.title = title
773 self.first_visible_idx = 0
774 self.selected_idx = 0
775 self.items = None
776 super(TreePanel, self).__init__(frame)
777 self.add_key_action(curses.KEY_UP, self.select_prev, "Select the previous item")
778 self.add_key_action(curses.KEY_DOWN, self.select_next, "Select the next item")
779 self.add_key_action(curses.KEY_RIGHT,self.right_arrow, "Expand an item")
780 self.add_key_action(curses.KEY_LEFT, self.left_arrow, "Unexpand an item or navigate to parent")
Greg Claytonc12cc592015-10-16 00:34:18 +0000781 self.add_key_action(curses.KEY_HOME, self.scroll_begin, "Go to the beginning of the tree")
782 self.add_key_action(curses.KEY_END, self.scroll_end, "Go to the end of the tree")
783 self.add_key_action(0x1b4f48, self.scroll_begin, "Go to the beginning of the tree")
784 self.add_key_action(0x1b4f46, self.scroll_end, "Go to the end of the tree")
Greg Clayton72d51442015-10-13 23:16:29 +0000785 self.add_key_action(curses.KEY_PPAGE, self.scroll_page_backward, "Scroll to previous page")
786 self.add_key_action(curses.KEY_NPAGE, self.scroll_page_forward, "Scroll to next forward")
787
788 def get_selected_item(self):
789 if self.selected_idx < len(self.items):
790 return self.items[self.selected_idx]
791 else:
792 return None
793
794 def select_item(self, item):
795 if self.items and item in self.items:
796 self.selected_idx = self.items.index(item)
797 return True
798 else:
799 return False
800
801 def get_visible_items(self):
802 # Clear self.items when you want to update all chidren
803 if self.items is None:
804 self.items = list()
805 children = self.root_item.get_children()
806 if children:
807 for child in children:
808 child.append_visible_items(self.items)
809 return self.items
810
811 def update(self):
812 self.erase()
813 self.draw_title_box(self.title)
814 visible_items = self.get_visible_items()
815 for (row, child) in enumerate(visible_items):
816 child.draw(self, row)
817
818 def get_item_draw_point(self, row):
819 display_row = self.get_display_row(row)
820 if display_row >= 0:
821 return Point(2, display_row + 1)
822 else:
823 return Point(-1, -1)
824
825 def get_display_row(self, row):
826 if row >= self.first_visible_idx:
827 display_row = row - self.first_visible_idx
828 if display_row < self.get_size().h-2:
829 return display_row
830 return -1
831
832 def is_selected(self, row):
833 return row == self.selected_idx
834
Greg Claytonc12cc592015-10-16 00:34:18 +0000835 def get_num_lines(self):
836 self.get_visible_items()
837 return len(self.items)
Greg Clayton72d51442015-10-13 23:16:29 +0000838
839 def get_num_visible_lines(self):
840 return self.get_size().h-2
841 def select_next (self):
842 self.selected_idx += 1
843 num_lines = self.get_num_lines()
844 if self.selected_idx >= num_lines:
Greg Claytonc12cc592015-10-16 00:34:18 +0000845 self.selected_idx = num_lines - 1
846 self._selection_changed()
Greg Clayton72d51442015-10-13 23:16:29 +0000847 self.refresh()
848
849 def select_prev (self):
850 self.selected_idx -= 1
851 if self.selected_idx < 0:
852 num_lines = self.get_num_lines()
853 if num_lines > 0:
854 self.selected_idx = 0
855 else:
856 self.selected_idx = -1
Greg Claytonc12cc592015-10-16 00:34:18 +0000857 self._selection_changed()
Greg Clayton72d51442015-10-13 23:16:29 +0000858 self.refresh()
859
860 def scroll_begin (self):
861 self.first_visible_idx = 0
862 num_lines = self.get_num_lines()
863 if num_lines > 0:
864 self.selected_idx = 0
865 else:
866 self.selected_idx = -1
Greg Claytonc12cc592015-10-16 00:34:18 +0000867 self.refresh()
Greg Clayton72d51442015-10-13 23:16:29 +0000868
869 def redisplay_tree(self):
870 self.items = None
871 self.refresh()
872
873 def right_arrow(self):
874 selected_item = self.get_selected_item()
875 if selected_item and selected_item.is_expanded == False:
876 selected_item.is_expanded = True
877 self.redisplay_tree()
878
879 def left_arrow(self):
880 selected_item = self.get_selected_item()
881 if selected_item:
882 if selected_item.is_expanded == True:
883 selected_item.is_expanded = False
884 self.redisplay_tree()
885 elif selected_item.parent:
886 if self.select_item(selected_item.parent):
887 self.refresh()
888
889
890 def scroll_end (self):
891 num_visible_lines = self.get_num_visible_lines()
Greg Claytonc12cc592015-10-16 00:34:18 +0000892 num_lines = self.get_num_lines()
Greg Clayton72d51442015-10-13 23:16:29 +0000893 if num_lines > num_visible_lines:
894 self.first_visible_idx = num_lines - num_visible_lines
895 else:
896 self.first_visible_idx = 0
897 self.selected_idx = num_lines-1
Greg Claytonc12cc592015-10-16 00:34:18 +0000898 self.refresh()
Greg Clayton72d51442015-10-13 23:16:29 +0000899
900 def scroll_page_backward(self):
901 num_visible_lines = self.get_num_visible_lines()
Greg Claytonc12cc592015-10-16 00:34:18 +0000902 new_index = self.selected_idx - num_visible_lines
Greg Clayton72d51442015-10-13 23:16:29 +0000903 if new_index < 0:
Greg Claytonc12cc592015-10-16 00:34:18 +0000904 self.selected_idx = 0
Greg Clayton72d51442015-10-13 23:16:29 +0000905 else:
Greg Claytonc12cc592015-10-16 00:34:18 +0000906 self.selected_idx = new_index
907 self._selection_changed()
Greg Clayton72d51442015-10-13 23:16:29 +0000908 self.refresh()
909
910 def scroll_page_forward(self):
Greg Claytonc12cc592015-10-16 00:34:18 +0000911 num_lines = self.get_num_lines()
Greg Clayton72d51442015-10-13 23:16:29 +0000912 num_visible_lines = self.get_num_visible_lines()
Greg Claytonc12cc592015-10-16 00:34:18 +0000913 new_index = self.selected_idx + num_visible_lines
914 if new_index >= num_lines:
915 new_index = num_lines - 1
916 self.selected_idx = new_index
917 self._selection_changed()
Greg Clayton72d51442015-10-13 23:16:29 +0000918 self.refresh()
919
Greg Claytonc12cc592015-10-16 00:34:18 +0000920 def _selection_changed(self):
921 num_lines = self.get_num_lines()
Greg Clayton72d51442015-10-13 23:16:29 +0000922 num_visible_lines = self.get_num_visible_lines()
Greg Claytonc12cc592015-10-16 00:34:18 +0000923 last_visible_index = self.first_visible_idx + num_visible_lines
924 if self.selected_idx >= last_visible_index:
925 self.first_visible_idx += (self.selected_idx - last_visible_index + 1)
926 if self.selected_idx < self.first_visible_idx:
927 self.first_visible_idx = self.selected_idx
928 if self.selected_idx >= 0 and self.selected_idx < len(self.items):
929 item = self.items[self.selected_idx]
930 item.was_selected()
Greg Clayton72d51442015-10-13 23:16:29 +0000931
932
Greg Clayton37191a22015-10-07 20:00:28 +0000933class Menu(BoxedPanel):
934 def __init__(self, title, items):
935 max_title_width = 0
936 for item in items:
937 if max_title_width < len(item.title):
938 max_title_width = len(item.title)
939 frame = Rect(x=0, y=0, w=max_title_width+4, h=len(items)+2)
940 super(Menu, self).__init__(frame, title=None, delegate=None, can_become_first_responder=True)
941 self.selected_idx = 0
942 self.title = title
943 self.items = items
944 for (item_idx, item) in enumerate(items):
945 self.set_line(item_idx, item.title)
946 self.hide()
947
948 def update(self):
949 super(Menu, self).update()
950
951 def relinquish_first_responder(self):
952 if not self.hidden():
953 self.hide()
954
955 def perform_action(self):
956 selected_idx = self.get_selected_idx()
957 if selected_idx < len(self.items):
958 action = self.items[selected_idx].action
959 if action:
960 action()
961
962class MenuBar(Panel):
963 def __init__(self, frame):
964 super(MenuBar, self).__init__(frame, can_become_first_responder=True)
965 self.menus = list()
966 self.selected_menu_idx = -1
967 self.add_key_action(curses.KEY_LEFT, self.select_prev, "Select the previous menu")
968 self.add_key_action(curses.KEY_RIGHT, self.select_next, "Select the next menu")
969 self.add_key_action(curses.KEY_DOWN, lambda: self.select(0), "Select the first menu")
970 self.add_key_action(27, self.relinquish_first_responder, "Hide current menu")
971 self.add_key_action(curses.KEY_ENTER, self.perform_action, "Select the next menu item")
972 self.add_key_action(10, self.perform_action, "Select the next menu item")
973
974 def insert_menu(self, menu, index=sys.maxint):
975 if index >= len(self.menus):
976 self.menus.append(menu)
977 else:
978 self.menus.insert(index, menu)
979 pt = self.get_position()
980 for menu in self.menus:
981 menu.set_position(pt)
982 pt.x += len(menu.title) + 5
983
984 def perform_action(self):
985 '''If no menu is visible, show the first menu. If a menu is visible, perform the action
986 associated with the selected menu item in the menu'''
987 menu_visible = False
988 for menu in self.menus:
989 if not menu.hidden():
990 menu_visible = True
991 break
992 if menu_visible:
993 menu.perform_action()
994 self.selected_menu_idx = -1
995 self._selected_menu_changed()
996 else:
997 self.select(0)
998
999 def relinquish_first_responder(self):
1000 if self.selected_menu_idx >= 0:
1001 self.selected_menu_idx = -1
1002 self._selected_menu_changed()
1003
1004 def _selected_menu_changed(self):
1005 for (menu_idx, menu) in enumerate(self.menus):
1006 is_hidden = menu.hidden()
1007 if menu_idx != self.selected_menu_idx:
1008 if not is_hidden:
1009 if self.parent.pop_first_responder(menu) == False:
1010 menu.hide()
1011 for (menu_idx, menu) in enumerate(self.menus):
1012 is_hidden = menu.hidden()
1013 if menu_idx == self.selected_menu_idx:
1014 if is_hidden:
1015 menu.show()
1016 self.parent.push_first_responder(menu)
1017 menu.top()
1018 self.parent.refresh()
1019
1020 def select(self, index):
1021 if index < len(self.menus):
1022 self.selected_menu_idx = index
1023 self._selected_menu_changed()
1024
1025 def select_next (self):
1026 num_menus = len(self.menus)
1027 if self.selected_menu_idx == -1:
1028 if num_menus > 0:
1029 self.selected_menu_idx = 0
1030 self._selected_menu_changed()
1031 else:
1032 if self.selected_menu_idx + 1 < num_menus:
1033 self.selected_menu_idx += 1
1034 else:
1035 self.selected_menu_idx = -1
1036 self._selected_menu_changed()
1037
1038 def select_prev (self):
1039 num_menus = len(self.menus)
1040 if self.selected_menu_idx == -1:
1041 if num_menus > 0:
1042 self.selected_menu_idx = num_menus - 1
1043 self._selected_menu_changed()
1044 else:
1045 if self.selected_menu_idx - 1 >= 0:
1046 self.selected_menu_idx -= 1
1047 else:
1048 self.selected_menu_idx = -1
1049 self._selected_menu_changed()
1050
1051 def update(self):
1052 self.erase()
1053 is_in_first_responder_chain = self.is_in_first_responder_chain()
1054 if is_in_first_responder_chain:
1055 self.attron (curses.A_REVERSE)
1056 pt = Point(x=0, y=0)
1057 for menu in self.menus:
1058 self.addstr(pt, '| ' + menu.title + ' ')
1059 pt.x += len(menu.title) + 5
1060 self.addstr(pt, '|')
1061 width = self.get_size().w
1062 while pt.x < width:
Greg Clayton72d51442015-10-13 23:16:29 +00001063 self.addch_at_point(pt, ' ')
Greg Clayton37191a22015-10-07 20:00:28 +00001064 pt.x += 1
1065 if is_in_first_responder_chain:
1066 self.attroff (curses.A_REVERSE)
1067
1068 for menu in self.menus:
1069 menu.update()
1070
1071
Greg Clayton1827fc22015-09-19 00:39:09 +00001072class StatusPanel(Panel):
1073 def __init__(self, frame):
Greg Clayton87349242015-09-22 00:35:20 +00001074 super(StatusPanel, self).__init__(frame, delegate=None, can_become_first_responder=False)
Greg Clayton1827fc22015-09-19 00:39:09 +00001075 self.status_items = list()
1076 self.status_dicts = dict()
1077 self.next_status_x = 1
1078
1079 def add_status_item(self, name, title, format, width, value, update=True):
1080 status_item_dict = { 'name': name,
1081 'title' : title,
1082 'width' : width,
1083 'format' : format,
1084 'value' : value,
1085 'x' : self.next_status_x }
1086 index = len(self.status_items)
1087 self.status_items.append(status_item_dict)
1088 self.status_dicts[name] = index
1089 self.next_status_x += width + 2;
1090 if update:
1091 self.update()
1092
1093 def increment_status(self, name, update=True):
1094 if name in self.status_dicts:
1095 status_item_idx = self.status_dicts[name]
1096 status_item_dict = self.status_items[status_item_idx]
1097 status_item_dict['value'] = status_item_dict['value'] + 1
1098 if update:
1099 self.update()
1100
1101 def update_status(self, name, value, update=True):
1102 if name in self.status_dicts:
1103 status_item_idx = self.status_dicts[name]
1104 status_item_dict = self.status_items[status_item_idx]
1105 status_item_dict['value'] = status_item_dict['format'] % (value)
1106 if update:
1107 self.update()
1108 def update(self):
1109 self.erase();
1110 for status_item_dict in self.status_items:
Greg Clayton72d51442015-10-13 23:16:29 +00001111 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 +00001112
1113stdscr = None
1114
1115def intialize_curses():
1116 global stdscr
1117 stdscr = curses.initscr()
1118 curses.noecho()
1119 curses.cbreak()
1120 stdscr.keypad(1)
1121 try:
1122 curses.start_color()
1123 except:
1124 pass
1125 return Window(stdscr)
1126
1127def terminate_curses():
1128 global stdscr
1129 if stdscr:
1130 stdscr.keypad(0)
1131 curses.echo()
1132 curses.nocbreak()
1133 curses.endwin()
1134