2
from bzrlib.osutils import getchar
6
def __init__(self, char, action, help, default=False):
12
class UserInteractor(object):
21
def add_item(self, item):
22
self.items.append(item)
23
self.__total_items = len(self.items)
25
def set_items(self, item_list):
26
self.items = item_list
27
self.__total_items = len(self.items)
29
def set_item_callback(self, cb):
30
self.item_callback = cb
32
def set_start_callback(self, cb):
33
self.start_callback = cb
35
def set_end_callback(self, cb):
36
self.end_callback = cb
38
def set_prompt(self, prompt):
41
def set_options(self, opt_list):
43
self._option_dict = {}
44
for option in opt_list:
45
self.add_option(option)
47
def add_option(self, option):
48
self._options.append(option)
49
self._option_dict[option.char] = option
51
def get_option(self, char):
52
return self._option_dict[char]
54
def __do_action(self, action, item):
55
if type(action) is int:
56
if action == self.QUIT:
58
self.__finished = True
59
elif action == self.RESTART:
61
self.__finished = False
62
elif action == self.FINISH:
63
self.__finished = True
68
def __select_loop(self):
71
while i < len(self.items):
74
self.item_callback(item, i + 1)
76
if self.__ask_once(item, i + 1):
79
if self.__quit or self.__finished:
84
self.__finished = False
86
while not self.__quit and not self.__finished:
87
self.__restart = False
93
if self.end_callback():
96
self.__finished = False
98
self.__ask_once(None, self.__total_items)
99
while not self.__finished and not self.__restart:
100
self.__ask_once(None, -1)
102
return not self.__quit
104
def __ask_once(self, item, count):
105
args = {'count': count, 'total' : self.__total_items}
108
sys.stdout.write(self.prompt % args)
109
sys.stdout.write(' [')
110
for opt in self._options:
113
sys.stdout.write(opt.char)
114
sys.stdout.write('?] (%s): ' % default.char)
118
# default, which we see as newline, is 'n'
119
if response in ['\n', '\r', '\r\n']:
120
response = default.char
122
print response # because echo is off
124
for opt in self._options:
125
if opt.char == response:
126
return self.__do_action(opt.action, item)
130
return False # keep pychecker happy
132
def __show_help(self):
133
for opt in self._options:
134
print ' %s - %s' % (opt.char, opt.help)