blob: 4f190adb44adc23fe0e5e13cfdabdd934f691d63 [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)
15
16 def is_valid_coordinate(self):
17 return self.x >= 0 and self.y >= 0
18
19class Size(object):
20 def __init__(self, w, h):
21 self.w = w
22 self.h = h
23
24 def __repr__(self):
25 return str(self)
26
27 def __str__(self):
28 return "(w=%u, h=%u)" % (self.w, self.h)
29
30class Rect(object):
31 def __init__(self, x=0, y=0, w=0, h=0):
32 self.origin = Point(x, y)
33 self.size = Size(w, h)
34
35 def __repr__(self):
36 return str(self)
37
38 def __str__(self):
39 return "{ %s, %s }" % (str(self.origin), str(self.size))
40
41 def get_min_x(self):
42 return self.origin.x
43
44 def get_max_x(self):
45 return self.origin.x + self.size.w
46
47 def get_min_y(self):
48 return self.origin.y
49
50 def get_max_y(self):
51 return self.origin.y + self.size.h
52
53 def contains_point(self, pt):
54 if pt.x < self.get_max_x():
55 if pt.y < self.get_max_y():
56 if pt.x >= self.get_min_y():
57 return pt.y >= self.get_min_y()
58 return False
59
Greg Clayton5ea44832015-10-15 00:49:36 +000060class QuitException(Exception):
61 def __init__(self):
62 super(QuitException, self).__init__('QuitException')
63
Greg Clayton1827fc22015-09-19 00:39:09 +000064class Window(object):
Greg Clayton87349242015-09-22 00:35:20 +000065 def __init__(self, window, delegate = None, can_become_first_responder = True):
Greg Clayton1827fc22015-09-19 00:39:09 +000066 self.window = window
Greg Clayton87349242015-09-22 00:35:20 +000067 self.parent = None
68 self.delegate = delegate
69 self.children = list()
Greg Clayton37191a22015-10-07 20:00:28 +000070 self.first_responders = list()
Greg Clayton87349242015-09-22 00:35:20 +000071 self.can_become_first_responder = can_become_first_responder
Greg Clayton414dba52015-09-24 00:19:42 +000072 self.key_actions = dict()
Greg Clayton87349242015-09-22 00:35:20 +000073
74 def add_child(self, window):
75 self.children.append(window)
76 window.parent = self
Greg Clayton414dba52015-09-24 00:19:42 +000077
78 def add_key_action(self, arg, callback, decription):
79 if isinstance(arg, list):
80 for key in arg:
81 self.add_key_action(key, callback, description)
82 else:
83 if isinstance(arg, ( int, long )):
84 key_action_dict = { 'key' : arg,
85 'callback' : callback,
86 'description' : decription }
87 self.key_actions[arg] = key_action_dict
88 elif isinstance(arg, basestring):
89 key_integer = ord(arg)
90 key_action_dict = { 'key' : key_integer,
91 'callback' : callback,
92 'description' : decription }
93 self.key_actions[key_integer] = key_action_dict
94 else:
95 raise ValueError
Greg Clayton72d51442015-10-13 23:16:29 +000096
97 def draw_title_box(self, title):
98 is_in_first_responder_chain = self.is_in_first_responder_chain()
99 if is_in_first_responder_chain:
100 self.attron (curses.A_REVERSE)
101 self.box()
102 if is_in_first_responder_chain:
103 self.attroff (curses.A_REVERSE)
104 if title:
105 self.addstr(Point(x=2, y=0), ' ' + title + ' ')
106
Greg Clayton87349242015-09-22 00:35:20 +0000107 def remove_child(self, window):
108 self.children.remove(window)
Greg Clayton37191a22015-10-07 20:00:28 +0000109
110 def get_first_responder(self):
111 if len(self.first_responders):
112 return self.first_responders[-1]
113 else:
114 return None
115
Greg Clayton87349242015-09-22 00:35:20 +0000116 def set_first_responder(self, window):
117 if window.can_become_first_responder:
118 if callable(getattr(window, "hidden", None)) and window.hidden():
119 return False
120 if not window in self.children:
121 self.add_child(window)
Greg Clayton37191a22015-10-07 20:00:28 +0000122 # See if we have a current first responder, and if we do, let it know that
123 # it will be resigning as first responder
124 first_responder = self.get_first_responder()
125 if first_responder:
126 first_responder.relinquish_first_responder()
127 # Now set the first responder to "window"
128 if len(self.first_responders) == 0:
129 self.first_responders.append(window)
130 else:
131 self.first_responders[-1] = window
Greg Clayton87349242015-09-22 00:35:20 +0000132 return True
133 else:
134 return False
135
Greg Clayton37191a22015-10-07 20:00:28 +0000136 def push_first_responder(self, window):
137 # Only push the window as the new first responder if the window isn't already the first responder
138 if window != self.get_first_responder():
139 self.first_responders.append(window)
140
141 def pop_first_responder(self, window):
142 # Only pop the window from the first responder list if it is the first responder
143 if window == self.get_first_responder():
144 old_first_responder = self.first_responders.pop()
145 old_first_responder.relinquish_first_responder()
146 return True
147 else:
148 return False
149
150 def relinquish_first_responder(self):
151 '''Override if there is something that you need to do when you lose first responder status.'''
152 pass
153
154 # def resign_first_responder(self, remove_from_parent, new_first_responder):
155 # success = False
156 # if self.parent:
157 # if self.is_first_responder():
158 # self.relinquish_first_responder()
159 # if len(self.parent.first_responder):
160 # self.parent.first_responder = None
161 # success = True
162 # if remove_from_parent:
163 # self.parent.remove_child(self)
164 # if new_first_responder:
165 # self.parent.set_first_responder(new_first_responder)
166 # else:
167 # self.parent.select_next_first_responder()
168 # return success
Greg Clayton1827fc22015-09-19 00:39:09 +0000169
Greg Clayton87349242015-09-22 00:35:20 +0000170 def is_first_responder(self):
171 if self.parent:
Greg Clayton37191a22015-10-07 20:00:28 +0000172 return self.parent.get_first_responder() == self
173 else:
174 return False
175
176 def is_in_first_responder_chain(self):
177 if self.parent:
178 return self in self.parent.first_responders
Greg Clayton87349242015-09-22 00:35:20 +0000179 else:
180 return False
181
182 def select_next_first_responder(self):
Greg Clayton37191a22015-10-07 20:00:28 +0000183 if len(self.first_responders) > 1:
184 self.pop_first_responder(self.first_responders[-1])
185 else:
186 num_children = len(self.children)
187 if num_children == 1:
188 return self.set_first_responder(self.children[0])
189 for (i,window) in enumerate(self.children):
190 if window.is_first_responder():
191 break
192 if i < num_children:
193 for i in range(i+1,num_children):
194 if self.set_first_responder(self.children[i]):
195 return True
196 for i in range(0, i):
197 if self.set_first_responder(self.children[i]):
198 return True
Greg Clayton87349242015-09-22 00:35:20 +0000199
Greg Clayton1827fc22015-09-19 00:39:09 +0000200 def point_in_window(self, pt):
201 size = self.get_size()
202 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 +0000203
Greg Clayton72d51442015-10-13 23:16:29 +0000204 def addch(self, c):
205 try:
206 self.window.addch(c)
207 except:
208 pass
209
210 def addch_at_point(self, pt, c):
Greg Clayton37191a22015-10-07 20:00:28 +0000211 try:
212 self.window.addch(pt.y, pt.x, c)
213 except:
214 pass
Greg Clayton1827fc22015-09-19 00:39:09 +0000215
216 def addstr(self, pt, str):
217 try:
218 self.window.addstr(pt.y, pt.x, str)
219 except:
220 pass
221
Greg Clayton72d51442015-10-13 23:16:29 +0000222 def addnstr_at_point(self, pt, str, n):
Greg Clayton1827fc22015-09-19 00:39:09 +0000223 try:
224 self.window.addnstr(pt.y, pt.x, str, n)
225 except:
226 pass
Greg Clayton72d51442015-10-13 23:16:29 +0000227 def addnstr(self, str, n):
228 try:
229 self.window.addnstr(str, n)
230 except:
231 pass
Greg Clayton1827fc22015-09-19 00:39:09 +0000232
Greg Clayton87349242015-09-22 00:35:20 +0000233 def attron(self, attr):
234 return self.window.attron (attr)
235
236 def attroff(self, attr):
237 return self.window.attroff (attr)
238
239 def box(self, vertch=0, horch=0):
240 if vertch == 0:
241 vertch = curses.ACS_VLINE
242 if horch == 0:
243 horch = curses.ACS_HLINE
244 self.window.box(vertch, horch)
Greg Clayton1827fc22015-09-19 00:39:09 +0000245
246 def get_contained_rect(self, top_inset=0, bottom_inset=0, left_inset=0, right_inset=0, height=-1, width=-1):
247 '''Get a rectangle based on the top "height" lines of this window'''
248 rect = self.get_frame()
249 x = rect.origin.x + left_inset
250 y = rect.origin.y + top_inset
251 if height == -1:
252 h = rect.size.h - (top_inset + bottom_inset)
253 else:
254 h = height
255 if width == -1:
256 w = rect.size.w - (left_inset + right_inset)
257 else:
258 w = width
259 return Rect (x = x, y = y, w = w, h = h)
260
261 def erase(self):
262 self.window.erase()
Greg Clayton72d51442015-10-13 23:16:29 +0000263
264 def get_cursor(self):
265 (y, x) = self.window.getyx()
266 return Point(x=x, y=y)
Greg Clayton1827fc22015-09-19 00:39:09 +0000267
268 def get_frame(self):
269 position = self.get_position()
270 size = self.get_size()
271 return Rect(x=position.x, y=position.y, w=size.w, h=size.h)
272
273 def get_position(self):
274 (y, x) = self.window.getbegyx()
275 return Point(x, y)
276
277 def get_size(self):
278 (y, x) = self.window.getmaxyx()
279 return Size(w=x, h=y)
Greg Clayton37191a22015-10-07 20:00:28 +0000280
Greg Clayton72d51442015-10-13 23:16:29 +0000281 def move(self, pt):
282 self.window.move(pt.y, pt.x)
283
Greg Clayton1827fc22015-09-19 00:39:09 +0000284 def refresh(self):
Greg Clayton87349242015-09-22 00:35:20 +0000285 self.update()
Greg Clayton1827fc22015-09-19 00:39:09 +0000286 curses.panel.update_panels()
Greg Clayton72d51442015-10-13 23:16:29 +0000287 self.move(Point(x=0, y=0))
Greg Clayton1827fc22015-09-19 00:39:09 +0000288 return self.window.refresh()
289
290 def resize(self, size):
Greg Clayton87349242015-09-22 00:35:20 +0000291 return self.window.resize(size.h, size.w)
Greg Clayton1827fc22015-09-19 00:39:09 +0000292
Greg Clayton87349242015-09-22 00:35:20 +0000293 def timeout(self, timeout_msec):
294 return self.window.timeout(timeout_msec)
295
296 def handle_key(self, key, check_parent=True):
297 '''Handle a key press in this window.'''
298
299 # First try the first responder if this window has one, but don't allow
300 # it to check with its parent (False second parameter) so we don't recurse
301 # and get a stack overflow
Greg Clayton37191a22015-10-07 20:00:28 +0000302 for first_responder in reversed(self.first_responders):
303 if first_responder.handle_key(key, False):
Greg Clayton87349242015-09-22 00:35:20 +0000304 return True
Greg Clayton414dba52015-09-24 00:19:42 +0000305
306 # Check our key map to see if we have any actions. Actions don't take
307 # any arguments, they must be callable
308 if key in self.key_actions:
309 key_action = self.key_actions[key]
310 key_action['callback']()
311 return True
312 # Check if there is a wildcard key for any key
313 if -1 in self.key_actions:
314 key_action = self.key_actions[-1]
315 key_action['callback']()
316 return True
Greg Clayton87349242015-09-22 00:35:20 +0000317 # Check if the window delegate wants to handle this key press
318 if self.delegate:
319 if callable(getattr(self.delegate, "handle_key", None)):
320 if self.delegate.handle_key(self, key):
321 return True
322 if self.delegate(self, key):
323 return True
324 # Check if we have a parent window and if so, let the parent
325 # window handle the key press
326 if check_parent and self.parent:
327 return self.parent.handle_key(key, True)
328 else:
329 return False # Key not handled
330
331 def update(self):
332 for child in self.children:
333 child.update()
Greg Clayton5ea44832015-10-15 00:49:36 +0000334
335 def quit_action(self):
336 raise QuitException
Greg Clayton87349242015-09-22 00:35:20 +0000337
338 def key_event_loop(self, timeout_msec=-1, n=sys.maxint):
339 '''Run an event loop to receive key presses and pass them along to the
340 responder chain.
341
342 timeout_msec is the timeout it milliseconds. If the value is -1, an
343 infinite wait will be used. It the value is zero, a non-blocking mode
344 will be used, and if greater than zero it will wait for a key press
345 for timeout_msec milliseconds.
346
347 n is the number of times to go through the event loop before exiting'''
348 self.timeout(timeout_msec)
Greg Clayton5ea44832015-10-15 00:49:36 +0000349 done = False
350 while not done and n > 0:
Greg Clayton87349242015-09-22 00:35:20 +0000351 c = self.window.getch()
352 if c != -1:
Greg Clayton37191a22015-10-07 20:00:28 +0000353 try:
354 self.handle_key(c)
Greg Clayton5ea44832015-10-15 00:49:36 +0000355 except QuitException:
356 done = True
Greg Clayton87349242015-09-22 00:35:20 +0000357 n -= 1
358
Greg Clayton1827fc22015-09-19 00:39:09 +0000359class Panel(Window):
Greg Clayton87349242015-09-22 00:35:20 +0000360 def __init__(self, frame, delegate = None, can_become_first_responder = True):
Greg Clayton1827fc22015-09-19 00:39:09 +0000361 window = curses.newwin(frame.size.h,frame.size.w, frame.origin.y, frame.origin.x)
Greg Clayton87349242015-09-22 00:35:20 +0000362 super(Panel, self).__init__(window, delegate, can_become_first_responder)
Greg Clayton1827fc22015-09-19 00:39:09 +0000363 self.panel = curses.panel.new_panel(window)
364
Greg Clayton87349242015-09-22 00:35:20 +0000365 def hide(self):
366 return self.panel.hide()
367
368 def hidden(self):
369 return self.panel.hidden()
370
371 def show(self):
372 return self.panel.show()
373
Greg Clayton1827fc22015-09-19 00:39:09 +0000374 def top(self):
Greg Clayton87349242015-09-22 00:35:20 +0000375 return self.panel.top()
Greg Clayton1827fc22015-09-19 00:39:09 +0000376
377 def set_position(self, pt):
378 self.panel.move(pt.y, pt.x)
379
380 def slide_position(self, pt):
381 new_position = self.get_position()
382 new_position.x = new_position.x + pt.x
383 new_position.y = new_position.y + pt.y
384 self.set_position(new_position)
385
386class BoxedPanel(Panel):
Greg Clayton87349242015-09-22 00:35:20 +0000387 def __init__(self, frame, title, delegate = None, can_become_first_responder = True):
388 super(BoxedPanel, self).__init__(frame, delegate, can_become_first_responder)
Greg Clayton1827fc22015-09-19 00:39:09 +0000389 self.title = title
390 self.lines = list()
391 self.first_visible_idx = 0
Greg Clayton87349242015-09-22 00:35:20 +0000392 self.selected_idx = -1
Greg Clayton37191a22015-10-07 20:00:28 +0000393 self.add_key_action(curses.KEY_UP, self.select_prev, "Select the previous item")
394 self.add_key_action(curses.KEY_DOWN, self.select_next, "Select the next item")
395 self.add_key_action(curses.KEY_HOME, self.scroll_begin, "Go to the beginning of the list")
396 self.add_key_action(curses.KEY_END, self.scroll_end, "Go to the end of the list")
397 self.add_key_action(curses.KEY_PPAGE, self.scroll_page_backward, "Scroll to previous page")
398 self.add_key_action(curses.KEY_NPAGE, self.scroll_page_forward, "Scroll to next forward")
Greg Clayton1827fc22015-09-19 00:39:09 +0000399 self.update()
400
Greg Claytond13c4fb2015-09-22 17:18:15 +0000401 def clear(self, update=True):
402 self.lines = list()
403 self.first_visible_idx = 0
404 self.selected_idx = -1
405 if update:
406 self.update()
407
Greg Clayton1827fc22015-09-19 00:39:09 +0000408 def get_usable_width(self):
409 '''Valid usable width is 0 to (width - 3) since the left and right lines display the box around
410 this frame and we skip a leading space'''
411 w = self.get_size().w
412 if w > 3:
413 return w-3
414 else:
415 return 0
416
417 def get_usable_height(self):
418 '''Valid line indexes are 0 to (height - 2) since the top and bottom lines display the box around this frame.'''
419 h = self.get_size().h
420 if h > 2:
421 return h-2
422 else:
423 return 0
424
425 def get_point_for_line(self, global_line_idx):
426 '''Returns the point to use when displaying a line whose index is "line_idx"'''
427 line_idx = global_line_idx - self.first_visible_idx
428 num_lines = self.get_usable_height()
429 if line_idx < num_lines:
430 return Point(x=2, y=1+line_idx)
431 else:
432 return Point(x=-1, y=-1) # return an invalid coordinate if the line index isn't valid
433
434 def set_title (self, title, update=True):
435 self.title = title
436 if update:
437 self.update()
438
Greg Clayton87349242015-09-22 00:35:20 +0000439 def scroll_begin (self):
440 self.first_visible_idx = 0
441 if len(self.lines) > 0:
442 self.selected_idx = 0
443 else:
444 self.selected_idx = -1
445 self.update()
446
447 def scroll_end (self):
448 max_visible_lines = self.get_usable_height()
449 num_lines = len(self.lines)
Greg Clayton414dba52015-09-24 00:19:42 +0000450 if num_lines > max_visible_lines:
Greg Clayton87349242015-09-22 00:35:20 +0000451 self.first_visible_idx = num_lines - max_visible_lines
452 else:
453 self.first_visible_idx = 0
454 self.selected_idx = num_lines-1
455 self.update()
Greg Clayton37191a22015-10-07 20:00:28 +0000456
457 def scroll_page_backward(self):
458 num_lines = len(self.lines)
459 max_visible_lines = self.get_usable_height()
460 new_index = self.first_visible_idx - max_visible_lines
461 if new_index < 0:
462 self.first_visible_idx = 0
463 else:
464 self.first_visible_idx = new_index
465 self.refresh()
466
467 def scroll_page_forward(self):
468 max_visible_lines = self.get_usable_height()
469 self.first_visible_idx += max_visible_lines
470 self._adjust_first_visible_line()
471 self.refresh()
472
Greg Clayton87349242015-09-22 00:35:20 +0000473 def select_next (self):
474 self.selected_idx += 1
475 if self.selected_idx >= len(self.lines):
476 self.selected_idx = len(self.lines) - 1
Greg Clayton37191a22015-10-07 20:00:28 +0000477 self.refresh()
Greg Clayton87349242015-09-22 00:35:20 +0000478
479 def select_prev (self):
480 self.selected_idx -= 1
481 if self.selected_idx < 0:
482 if len(self.lines) > 0:
483 self.selected_idx = 0
484 else:
485 self.selected_idx = -1
Greg Clayton37191a22015-10-07 20:00:28 +0000486 self.refresh()
Greg Clayton87349242015-09-22 00:35:20 +0000487
488 def get_selected_idx(self):
489 return self.selected_idx
490
Greg Clayton1827fc22015-09-19 00:39:09 +0000491 def _adjust_first_visible_line(self):
492 num_lines = len(self.lines)
493 max_visible_lines = self.get_usable_height()
Greg Clayton37191a22015-10-07 20:00:28 +0000494 if (self.first_visible_idx >= num_lines) or (num_lines - self.first_visible_idx) > max_visible_lines:
Greg Clayton1827fc22015-09-19 00:39:09 +0000495 self.first_visible_idx = num_lines - max_visible_lines
496
497 def append_line(self, s, update=True):
498 self.lines.append(s)
499 self._adjust_first_visible_line()
500 if update:
501 self.update()
502
503 def set_line(self, line_idx, s, update=True):
504 '''Sets a line "line_idx" within the boxed panel to be "s"'''
505 if line_idx < 0:
506 return
507 while line_idx >= len(self.lines):
508 self.lines.append('')
509 self.lines[line_idx] = s
510 self._adjust_first_visible_line()
511 if update:
512 self.update()
513
514 def update(self):
Greg Clayton72d51442015-10-13 23:16:29 +0000515 self.erase()
516 self.draw_title_box(self.title)
Greg Clayton1827fc22015-09-19 00:39:09 +0000517 max_width = self.get_usable_width()
518 for line_idx in range(self.first_visible_idx, len(self.lines)):
519 pt = self.get_point_for_line(line_idx)
520 if pt.is_valid_coordinate():
Greg Clayton87349242015-09-22 00:35:20 +0000521 is_selected = line_idx == self.selected_idx
522 if is_selected:
523 self.attron (curses.A_REVERSE)
Greg Clayton72d51442015-10-13 23:16:29 +0000524 self.addnstr_at_point(pt, self.lines[line_idx], max_width)
Greg Clayton87349242015-09-22 00:35:20 +0000525 if is_selected:
526 self.attroff (curses.A_REVERSE)
Greg Clayton1827fc22015-09-19 00:39:09 +0000527 else:
528 return
529
Greg Clayton37191a22015-10-07 20:00:28 +0000530class Item(object):
531 def __init__(self, title, action):
532 self.title = title
533 self.action = action
Greg Clayton72d51442015-10-13 23:16:29 +0000534
Greg Clayton5ea44832015-10-15 00:49:36 +0000535class TreeItemDelegate(object):
536
537 def might_have_children(self):
538 return False
539
540 def update_children(self, item):
541 '''Return a list of child Item objects'''
542 return None
543
544 def draw_item_string(self, tree_window, item, s):
545 pt = tree_window.get_cursor()
546 width = tree_window.get_size().w - 1
547 if width > pt.x:
548 tree_window.addnstr(s, width - pt.x)
549
550 def draw_item(self, tree_window, item):
551 self.draw_item_string(tree_window, item, item.title)
552
Greg Clayton72d51442015-10-13 23:16:29 +0000553class TreeItem(object):
554 def __init__(self, delegate, parent = None, title = None, action = None, is_expanded = False):
555 self.parent = parent
556 self.title = title
557 self.action = action
558 self.delegate = delegate
559 self.is_expanded = not parent or is_expanded == True
Greg Clayton5ea44832015-10-15 00:49:36 +0000560 self._might_have_children = None
Greg Clayton72d51442015-10-13 23:16:29 +0000561 self.children = None
Greg Clayton5ea44832015-10-15 00:49:36 +0000562 self._children_might_have_children = False
Greg Clayton72d51442015-10-13 23:16:29 +0000563
564 def get_children(self):
565 if self.is_expanded and self.might_have_children():
566 if self.children is None:
Greg Clayton5ea44832015-10-15 00:49:36 +0000567 self._children_might_have_children = False
Greg Clayton72d51442015-10-13 23:16:29 +0000568 self.children = self.update_children()
Greg Clayton5ea44832015-10-15 00:49:36 +0000569 for child in self.children:
570 if child.might_have_children():
571 self._children_might_have_children = True
572 break
Greg Clayton72d51442015-10-13 23:16:29 +0000573 else:
Greg Clayton5ea44832015-10-15 00:49:36 +0000574 self._children_might_have_children = False
Greg Clayton72d51442015-10-13 23:16:29 +0000575 self.children = None
576 return self.children
Greg Clayton5ea44832015-10-15 00:49:36 +0000577
Greg Clayton72d51442015-10-13 23:16:29 +0000578 def append_visible_items(self, items):
579 items.append(self)
580 children = self.get_children()
581 if children:
582 for child in children:
583 child.append_visible_items(items)
584
585 def might_have_children(self):
Greg Clayton5ea44832015-10-15 00:49:36 +0000586 if self._might_have_children is None:
Greg Clayton72d51442015-10-13 23:16:29 +0000587 if not self.parent:
588 # Root item always might have children
Greg Clayton5ea44832015-10-15 00:49:36 +0000589 self._might_have_children = True
Greg Clayton72d51442015-10-13 23:16:29 +0000590 else:
591 # Check with the delegate to see if the item might have children
Greg Clayton5ea44832015-10-15 00:49:36 +0000592 self._might_have_children = self.delegate.might_have_children()
593 return self._might_have_children
594
595 def children_might_have_children(self):
596 return self._children_might_have_children
597
Greg Clayton72d51442015-10-13 23:16:29 +0000598 def update_children(self):
599 if self.is_expanded and self.might_have_children():
600 self.children = self.delegate.update_children(self)
601 for child in self.children:
602 child.update_children()
603 else:
604 self.children = None
605 return self.children
Greg Clayton37191a22015-10-07 20:00:28 +0000606
Greg Clayton72d51442015-10-13 23:16:29 +0000607 def get_num_visible_rows(self):
608 rows = 1
609 if self.is_expanded:
610 children = self.get_children()
611 for child in children:
612 rows += child.get_num_visible_rows()
613 return rows
614 def draw(self, tree_window, row):
615 display_row = tree_window.get_display_row(row)
616 if display_row >= 0:
617 tree_window.move(tree_window.get_item_draw_point(row))
618 if self.parent:
619 self.parent.draw_tree_for_child(tree_window, self, 0)
620 if self.might_have_children():
621 tree_window.addch (curses.ACS_DIAMOND)
622 tree_window.addch (curses.ACS_HLINE)
Greg Clayton5ea44832015-10-15 00:49:36 +0000623 elif self.parent and self.parent.children_might_have_children():
624 tree_window.addch (curses.ACS_HLINE)
625 tree_window.addch (curses.ACS_HLINE)
Greg Clayton72d51442015-10-13 23:16:29 +0000626 is_selected = tree_window.is_selected(row)
627 if is_selected:
628 tree_window.attron (curses.A_REVERSE)
629 self.delegate.draw_item(tree_window, self)
630 if is_selected:
631 tree_window.attroff (curses.A_REVERSE)
632
633 def draw_tree_for_child (self, tree_window, child, reverse_depth):
634 if self.parent:
635 self.parent.draw_tree_for_child (tree_window, self, reverse_depth + 1)
636 if self.children[-1] == child:
637 # Last child
638 if reverse_depth == 0:
639 tree_window.addch (curses.ACS_LLCORNER)
640 tree_window.addch (curses.ACS_HLINE)
641 else:
642 tree_window.addch (' ')
643 tree_window.addch (' ')
644 else:
645 # Middle child
646 if reverse_depth == 0:
647 tree_window.addch (curses.ACS_LTEE)
648 tree_window.addch (curses.ACS_HLINE)
649 else:
650 tree_window.addch (curses.ACS_VLINE)
651 tree_window.addch (' ')
652
653 def was_selected(self):
654 pass
655
656class TreePanel(Panel):
657 def __init__(self, frame, title, root_item):
658 self.root_item = root_item
659 self.title = title
660 self.first_visible_idx = 0
661 self.selected_idx = 0
662 self.items = None
663 super(TreePanel, self).__init__(frame)
664 self.add_key_action(curses.KEY_UP, self.select_prev, "Select the previous item")
665 self.add_key_action(curses.KEY_DOWN, self.select_next, "Select the next item")
666 self.add_key_action(curses.KEY_RIGHT,self.right_arrow, "Expand an item")
667 self.add_key_action(curses.KEY_LEFT, self.left_arrow, "Unexpand an item or navigate to parent")
668 self.add_key_action(curses.KEY_HOME, self.scroll_begin, "Go to the beginning of the list")
669 self.add_key_action(curses.KEY_END, self.scroll_end, "Go to the end of the list")
670 self.add_key_action(curses.KEY_PPAGE, self.scroll_page_backward, "Scroll to previous page")
671 self.add_key_action(curses.KEY_NPAGE, self.scroll_page_forward, "Scroll to next forward")
672
673 def get_selected_item(self):
674 if self.selected_idx < len(self.items):
675 return self.items[self.selected_idx]
676 else:
677 return None
678
679 def select_item(self, item):
680 if self.items and item in self.items:
681 self.selected_idx = self.items.index(item)
682 return True
683 else:
684 return False
685
686 def get_visible_items(self):
687 # Clear self.items when you want to update all chidren
688 if self.items is None:
689 self.items = list()
690 children = self.root_item.get_children()
691 if children:
692 for child in children:
693 child.append_visible_items(self.items)
694 return self.items
695
696 def update(self):
697 self.erase()
698 self.draw_title_box(self.title)
699 visible_items = self.get_visible_items()
700 for (row, child) in enumerate(visible_items):
701 child.draw(self, row)
702
703 def get_item_draw_point(self, row):
704 display_row = self.get_display_row(row)
705 if display_row >= 0:
706 return Point(2, display_row + 1)
707 else:
708 return Point(-1, -1)
709
710 def get_display_row(self, row):
711 if row >= self.first_visible_idx:
712 display_row = row - self.first_visible_idx
713 if display_row < self.get_size().h-2:
714 return display_row
715 return -1
716
717 def is_selected(self, row):
718 return row == self.selected_idx
719
720 def get_num_lines(self):
721 rows = 0
722 children = self.root_item.get_children()
723 for child in children:
724 rows += child.get_num_visible_rows()
725 return rows
726
727 def get_num_visible_lines(self):
728 return self.get_size().h-2
729 def select_next (self):
730 self.selected_idx += 1
731 num_lines = self.get_num_lines()
732 if self.selected_idx >= num_lines:
733 self.selected_idx = num_lines - 1
734 self.refresh()
735
736 def select_prev (self):
737 self.selected_idx -= 1
738 if self.selected_idx < 0:
739 num_lines = self.get_num_lines()
740 if num_lines > 0:
741 self.selected_idx = 0
742 else:
743 self.selected_idx = -1
744 self.refresh()
745
746 def scroll_begin (self):
747 self.first_visible_idx = 0
748 num_lines = self.get_num_lines()
749 if num_lines > 0:
750 self.selected_idx = 0
751 else:
752 self.selected_idx = -1
753 self.update()
754
755 def redisplay_tree(self):
756 self.items = None
757 self.refresh()
758
759 def right_arrow(self):
760 selected_item = self.get_selected_item()
761 if selected_item and selected_item.is_expanded == False:
762 selected_item.is_expanded = True
763 self.redisplay_tree()
764
765 def left_arrow(self):
766 selected_item = self.get_selected_item()
767 if selected_item:
768 if selected_item.is_expanded == True:
769 selected_item.is_expanded = False
770 self.redisplay_tree()
771 elif selected_item.parent:
772 if self.select_item(selected_item.parent):
773 self.refresh()
774
775
776 def scroll_end (self):
777 num_visible_lines = self.get_num_visible_lines()
778 num_lines = len(self.lines)
779 if num_lines > num_visible_lines:
780 self.first_visible_idx = num_lines - num_visible_lines
781 else:
782 self.first_visible_idx = 0
783 self.selected_idx = num_lines-1
784 self.update()
785
786 def scroll_page_backward(self):
787 num_visible_lines = self.get_num_visible_lines()
788 new_index = self.first_visible_idx - num_visible_lines
789 if new_index < 0:
790 self.first_visible_idx = 0
791 else:
792 self.first_visible_idx = new_index
793 self.refresh()
794
795 def scroll_page_forward(self):
796 num_visible_lines = self.get_num_visible_lines()
797 self.first_visible_idx += num_visible_lines
798 self._adjust_first_visible_line()
799 self.refresh()
800
801 def _adjust_first_visible_line(self):
802 num_lines = len(self.lines)
803 num_visible_lines = self.get_num_visible_lines()
804 if (self.first_visible_idx >= num_lines) or (num_lines - self.first_visible_idx) > num_visible_lines:
805 self.first_visible_idx = num_lines - num_visible_lines
806
807
808
Greg Clayton37191a22015-10-07 20:00:28 +0000809class Menu(BoxedPanel):
810 def __init__(self, title, items):
811 max_title_width = 0
812 for item in items:
813 if max_title_width < len(item.title):
814 max_title_width = len(item.title)
815 frame = Rect(x=0, y=0, w=max_title_width+4, h=len(items)+2)
816 super(Menu, self).__init__(frame, title=None, delegate=None, can_become_first_responder=True)
817 self.selected_idx = 0
818 self.title = title
819 self.items = items
820 for (item_idx, item) in enumerate(items):
821 self.set_line(item_idx, item.title)
822 self.hide()
823
824 def update(self):
825 super(Menu, self).update()
826
827 def relinquish_first_responder(self):
828 if not self.hidden():
829 self.hide()
830
831 def perform_action(self):
832 selected_idx = self.get_selected_idx()
833 if selected_idx < len(self.items):
834 action = self.items[selected_idx].action
835 if action:
836 action()
837
838class MenuBar(Panel):
839 def __init__(self, frame):
840 super(MenuBar, self).__init__(frame, can_become_first_responder=True)
841 self.menus = list()
842 self.selected_menu_idx = -1
843 self.add_key_action(curses.KEY_LEFT, self.select_prev, "Select the previous menu")
844 self.add_key_action(curses.KEY_RIGHT, self.select_next, "Select the next menu")
845 self.add_key_action(curses.KEY_DOWN, lambda: self.select(0), "Select the first menu")
846 self.add_key_action(27, self.relinquish_first_responder, "Hide current menu")
847 self.add_key_action(curses.KEY_ENTER, self.perform_action, "Select the next menu item")
848 self.add_key_action(10, self.perform_action, "Select the next menu item")
849
850 def insert_menu(self, menu, index=sys.maxint):
851 if index >= len(self.menus):
852 self.menus.append(menu)
853 else:
854 self.menus.insert(index, menu)
855 pt = self.get_position()
856 for menu in self.menus:
857 menu.set_position(pt)
858 pt.x += len(menu.title) + 5
859
860 def perform_action(self):
861 '''If no menu is visible, show the first menu. If a menu is visible, perform the action
862 associated with the selected menu item in the menu'''
863 menu_visible = False
864 for menu in self.menus:
865 if not menu.hidden():
866 menu_visible = True
867 break
868 if menu_visible:
869 menu.perform_action()
870 self.selected_menu_idx = -1
871 self._selected_menu_changed()
872 else:
873 self.select(0)
874
875 def relinquish_first_responder(self):
876 if self.selected_menu_idx >= 0:
877 self.selected_menu_idx = -1
878 self._selected_menu_changed()
879
880 def _selected_menu_changed(self):
881 for (menu_idx, menu) in enumerate(self.menus):
882 is_hidden = menu.hidden()
883 if menu_idx != self.selected_menu_idx:
884 if not is_hidden:
885 if self.parent.pop_first_responder(menu) == False:
886 menu.hide()
887 for (menu_idx, menu) in enumerate(self.menus):
888 is_hidden = menu.hidden()
889 if menu_idx == self.selected_menu_idx:
890 if is_hidden:
891 menu.show()
892 self.parent.push_first_responder(menu)
893 menu.top()
894 self.parent.refresh()
895
896 def select(self, index):
897 if index < len(self.menus):
898 self.selected_menu_idx = index
899 self._selected_menu_changed()
900
901 def select_next (self):
902 num_menus = len(self.menus)
903 if self.selected_menu_idx == -1:
904 if num_menus > 0:
905 self.selected_menu_idx = 0
906 self._selected_menu_changed()
907 else:
908 if self.selected_menu_idx + 1 < num_menus:
909 self.selected_menu_idx += 1
910 else:
911 self.selected_menu_idx = -1
912 self._selected_menu_changed()
913
914 def select_prev (self):
915 num_menus = len(self.menus)
916 if self.selected_menu_idx == -1:
917 if num_menus > 0:
918 self.selected_menu_idx = num_menus - 1
919 self._selected_menu_changed()
920 else:
921 if self.selected_menu_idx - 1 >= 0:
922 self.selected_menu_idx -= 1
923 else:
924 self.selected_menu_idx = -1
925 self._selected_menu_changed()
926
927 def update(self):
928 self.erase()
929 is_in_first_responder_chain = self.is_in_first_responder_chain()
930 if is_in_first_responder_chain:
931 self.attron (curses.A_REVERSE)
932 pt = Point(x=0, y=0)
933 for menu in self.menus:
934 self.addstr(pt, '| ' + menu.title + ' ')
935 pt.x += len(menu.title) + 5
936 self.addstr(pt, '|')
937 width = self.get_size().w
938 while pt.x < width:
Greg Clayton72d51442015-10-13 23:16:29 +0000939 self.addch_at_point(pt, ' ')
Greg Clayton37191a22015-10-07 20:00:28 +0000940 pt.x += 1
941 if is_in_first_responder_chain:
942 self.attroff (curses.A_REVERSE)
943
944 for menu in self.menus:
945 menu.update()
946
947
Greg Clayton1827fc22015-09-19 00:39:09 +0000948class StatusPanel(Panel):
949 def __init__(self, frame):
Greg Clayton87349242015-09-22 00:35:20 +0000950 super(StatusPanel, self).__init__(frame, delegate=None, can_become_first_responder=False)
Greg Clayton1827fc22015-09-19 00:39:09 +0000951 self.status_items = list()
952 self.status_dicts = dict()
953 self.next_status_x = 1
954
955 def add_status_item(self, name, title, format, width, value, update=True):
956 status_item_dict = { 'name': name,
957 'title' : title,
958 'width' : width,
959 'format' : format,
960 'value' : value,
961 'x' : self.next_status_x }
962 index = len(self.status_items)
963 self.status_items.append(status_item_dict)
964 self.status_dicts[name] = index
965 self.next_status_x += width + 2;
966 if update:
967 self.update()
968
969 def increment_status(self, name, update=True):
970 if name in self.status_dicts:
971 status_item_idx = self.status_dicts[name]
972 status_item_dict = self.status_items[status_item_idx]
973 status_item_dict['value'] = status_item_dict['value'] + 1
974 if update:
975 self.update()
976
977 def update_status(self, name, value, update=True):
978 if name in self.status_dicts:
979 status_item_idx = self.status_dicts[name]
980 status_item_dict = self.status_items[status_item_idx]
981 status_item_dict['value'] = status_item_dict['format'] % (value)
982 if update:
983 self.update()
984 def update(self):
985 self.erase();
986 for status_item_dict in self.status_items:
Greg Clayton72d51442015-10-13 23:16:29 +0000987 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 +0000988
989stdscr = None
990
991def intialize_curses():
992 global stdscr
993 stdscr = curses.initscr()
994 curses.noecho()
995 curses.cbreak()
996 stdscr.keypad(1)
997 try:
998 curses.start_color()
999 except:
1000 pass
1001 return Window(stdscr)
1002
1003def terminate_curses():
1004 global stdscr
1005 if stdscr:
1006 stdscr.keypad(0)
1007 curses.echo()
1008 curses.nocbreak()
1009 curses.endwin()
1010