1
0
mirror of https://github.com/Foltik/dotfiles synced 2024-11-28 05:27:06 -05:00
dotfiles/lib/menu.py

77 lines
2.0 KiB
Python
Raw Normal View History

2018-10-16 22:02:11 -04:00
import curses
from curses import panel
2018-10-17 01:03:27 -04:00
class BaseMenu:
def __init__(self, stdscreen):
2018-10-16 22:02:11 -04:00
self.window = stdscreen.subwin(0, 0)
self.window.keypad(1)
self.panel = panel.new_panel(self.window)
self.panel.hide()
panel.update_panels()
2018-10-17 01:03:27 -04:00
def up(self):
2018-10-16 22:02:11 -04:00
self.panel.top()
self.panel.show()
self.window.clear()
2018-10-17 01:03:27 -04:00
def down(self):
self.window.clear()
self.panel.hide()
panel.update_panels()
curses.doupdate()
2018-10-16 22:02:11 -04:00
2018-10-17 01:03:27 -04:00
def update(self):
self.window.refresh()
curses.doupdate()
2018-10-16 22:02:11 -04:00
2018-10-17 01:03:27 -04:00
class Menu(BaseMenu):
def __init__(self, stdscreen, items):
super().__init__(stdscreen)
self.should_exit = False
self.position = 0
self.items = items
self.items.append(('exit', self.exit))
2018-10-16 22:02:11 -04:00
2018-10-17 01:03:27 -04:00
def exit(self):
self.should_exit = True
2018-10-16 22:02:11 -04:00
2018-10-17 01:03:27 -04:00
def navigate(self, offset):
self.position += offset
self.position %= len(self.items)
2018-10-16 22:02:11 -04:00
2018-10-17 01:03:27 -04:00
def draw(self):
for index, item in enumerate(self.items):
text = '%d. %s' % (index + 1, item[0])
text_mode = curses.A_REVERSE if index == self.position else curses.A_NORMAL
self.window.addstr(index + 1, 1, text, text_mode)
2018-10-16 22:02:11 -04:00
2018-10-17 01:03:27 -04:00
def get_selection(self, key):
if key in [curses.KEY_ENTER, ord('\n')]:
return self.items[self.position]
elif (key - ord('0')) in range(1, len(self.items) + 1):
return self.items[key - ord('0') - 1]
else:
return None
2018-10-16 22:02:11 -04:00
2018-10-17 01:03:27 -04:00
def input(self):
key = self.window.getch()
selection = self.get_selection(key)
if selection:
selection[1]()
if key == curses.KEY_UP:
self.navigate(-1)
elif key == curses.KEY_DOWN:
self.navigate(1)
def display(self):
self.up()
while not self.should_exit:
self.update()
self.draw()
self.input()
self.should_exit = False
self.down()