4
def __init__(self, char, action, help, default=False):
10
class UserInteractor(object):
19
def add_item(self, item):
20
self.items.append(item)
21
self.__total_items = len(self.items)
23
def set_items(self, item_list):
24
self.items = item_list
25
self.__total_items = len(self.items)
27
def set_item_callback(self, cb):
28
self.item_callback = cb
30
def set_start_callback(self, cb):
31
self.start_callback = cb
33
def set_end_callback(self, cb):
34
self.end_callback = cb
36
def set_prompt(self, prompt):
39
def set_options(self, opt_list):
41
self._option_dict = {}
42
for option in opt_list:
43
self.add_option(option)
45
def add_option(self, option):
46
self._options.append(option)
47
self._option_dict[option.char] = option
49
def get_option(self, char):
50
return self._option_dict[char]
52
def __do_action(self, action, item):
53
if type(action) is int:
54
if action == self.QUIT:
56
self.__finished = True
57
elif action == self.RESTART:
59
self.__finished = False
60
elif action == self.FINISH:
61
self.__finished = True
66
def __select_loop(self):
69
while i < len(self.items):
72
self.item_callback(item, i + 1)
74
if self.__ask_once(item, i + 1):
77
if self.__quit or self.__finished:
82
self.__finished = False
84
while not self.__quit and not self.__finished:
85
self.__restart = False
91
if self.end_callback():
94
self.__finished = False
96
self.__ask_once(None, self.__total_items)
97
while not self.__finished and not self.__restart:
98
self.__ask_once(None, -1)
100
return not self.__quit
102
def __ask_once(self, item, count):
103
args = {'count': count, 'total' : self.__total_items}
106
sys.stdout.write(self.prompt % args)
107
sys.stdout.write(' [')
108
for opt in self._options:
111
sys.stdout.write(opt.char)
112
sys.stdout.write('?] (%s): ' % default.char)
114
response = self.__getchar()
116
# default, which we see as newline, is 'n'
117
if response in ['\n', '\r', '\r\n']:
118
response = default.char
120
print response # because echo is off
122
for opt in self._options:
123
if opt.char == response:
124
return self.__do_action(opt.action, item)
128
return False # keep pychecker happy
130
def __show_help(self):
131
for opt in self._options:
132
print ' %s - %s' % (opt.char, opt.help)
134
if sys.platform == "win32":
137
return msvcrt.getch()
142
fd = sys.stdin.fileno()
143
settings = termios.tcgetattr(fd)
146
ch = sys.stdin.read(1)
148
termios.tcsetattr(fd, termios.TCSADRAIN, settings)