3
if sys.platform == "win32":
11
fd = sys.stdin.fileno()
12
settings = termios.tcgetattr(fd)
15
ch = sys.stdin.read(1)
17
termios.tcsetattr(fd, termios.TCSADRAIN, settings)
22
def __init__(self, char, action, help, default=False):
25
self.default = default
28
class UserInteractor(object):
37
def add_item(self, item):
38
self.items.append(item)
39
self.__total_items = len(self.items)
41
def set_items(self, item_list):
42
self.items = item_list
43
self.__total_items = len(self.items)
45
def set_item_callback(self, cb):
46
self.item_callback = cb
48
def set_start_callback(self, cb):
49
self.start_callback = cb
51
def set_end_callback(self, cb):
52
self.end_callback = cb
54
def set_prompt(self, prompt):
57
def set_options(self, opt_list):
59
self._option_dict = {}
60
for option in opt_list:
61
self.add_option(option)
63
def add_option(self, option):
64
self._options.append(option)
65
self._option_dict[option.char] = option
67
def get_option(self, char):
68
return self._option_dict[char]
70
def __do_action(self, action, item):
71
if type(action) is int:
72
if action == self.QUIT:
74
self.__finished = True
75
elif action == self.RESTART:
77
self.__finished = False
78
elif action == self.FINISH:
79
self.__finished = True
84
def __select_loop(self):
87
while i < len(self.items):
90
self.item_callback(item, i + 1)
92
if self.__ask_once(item, i + 1):
95
if self.__quit or self.__finished:
100
self.__finished = False
102
while not self.__quit and not self.__finished:
103
self.__restart = False
109
if self.end_callback():
112
self.__finished = False
114
self.__ask_once(None, self.__total_items)
115
while not self.__finished and not self.__restart:
116
self.__ask_once(None, -1)
118
return not self.__quit
120
def __ask_once(self, item, count):
121
args = {'count': count, 'total' : self.__total_items}
124
sys.stdout.write(self.prompt % args)
125
sys.stdout.write(' [')
126
for opt in self._options:
129
sys.stdout.write(opt.char)
130
sys.stdout.write('?] (%s): ' % default.char)
134
# default, which we see as newline, is 'n'
135
if response in ['\n', '\r', '\r\n']:
136
response = default.char
138
print response # because echo is off
140
for opt in self._options:
141
if opt.char == response:
142
return self.__do_action(opt.action, item)
146
return False # keep pychecker happy
148
def __show_help(self):
149
for opt in self._options:
150
print ' %s - %s' % (opt.char, opt.help)