18
18
"""Text UI, write output to the console.
28
25
from bzrlib.lazy_import import lazy_import
29
26
lazy_import(globals(), """
30
31
from bzrlib import (
40
from bzrlib.osutils import watch_sigwinch
42
40
from bzrlib.ui import (
46
class _ChooseUI(object):
48
""" Helper class for choose implementation.
51
def __init__(self, ui, msg, choices, default):
54
self._build_alternatives(msg, choices, default)
56
def _setup_mode(self):
57
"""Setup input mode (line-based, char-based) and echo-back.
59
Line-based input is used if the BZR_TEXTUI_INPUT environment
60
variable is set to 'line-based', or if there is no controlling
63
if os.environ.get('BZR_TEXTUI_INPUT') != 'line-based' and \
64
self.ui.stdin == sys.stdin and self.ui.stdin.isatty():
65
self.line_based = False
68
self.line_based = True
69
self.echo_back = not self.ui.stdin.isatty()
71
def _build_alternatives(self, msg, choices, default):
72
"""Parse choices string.
74
Setup final prompt and the lists of choices and associated
79
self.alternatives = {}
80
choices = choices.split('\n')
81
if default is not None and default not in range(0, len(choices)):
82
raise ValueError("invalid default index")
84
name = c.replace('&', '').lower()
85
choice = (name, index)
86
if name in self.alternatives:
87
raise ValueError("duplicated choice: %s" % name)
88
self.alternatives[name] = choice
89
shortcut = c.find('&')
90
if -1 != shortcut and (shortcut + 1) < len(c):
92
help += '[' + c[shortcut + 1] + ']'
93
help += c[(shortcut + 2):]
94
shortcut = c[shortcut + 1]
96
c = c.replace('&', '')
98
help = '[%s]%s' % (shortcut, c[1:])
99
shortcut = shortcut.lower()
100
if shortcut in self.alternatives:
101
raise ValueError("duplicated shortcut: %s" % shortcut)
102
self.alternatives[shortcut] = choice
103
# Add redirections for default.
105
self.alternatives[''] = choice
106
self.alternatives['\r'] = choice
107
help_list.append(help)
110
self.prompt = u'%s (%s): ' % (msg, ', '.join(help_list))
113
line = self.ui.stdin.readline()
119
char = osutils.getchar()
120
if char == chr(3): # INTR
121
raise KeyboardInterrupt
122
if char == chr(4): # EOF (^d, C-d)
127
"""Keep asking the user until a valid choice is made.
130
getchoice = self._getline
132
getchoice = self._getchar
136
if 1 == iter or self.line_based:
137
self.ui.prompt(self.prompt)
141
self.ui.stderr.write('\n')
143
except KeyboardInterrupt:
144
self.ui.stderr.write('\n')
145
raise KeyboardInterrupt
146
choice = choice.lower()
147
if choice not in self.alternatives:
148
# Not a valid choice, keep on asking.
150
name, index = self.alternatives[choice]
152
self.ui.stderr.write(name + '\n')
48
156
class TextUIFactory(UIFactory):
49
157
"""A UI factory for Text user interefaces."""
62
170
self.stderr = stderr
63
171
# paints progress, network activity, etc
64
172
self._progress_view = self.make_progress_view()
65
# hook up the signals to watch for terminal size changes
174
def choose(self, msg, choices, default=None):
175
"""Prompt the user for a list of alternatives.
177
Support both line-based and char-based editing.
179
In line-based mode, both the shortcut and full choice name are valid
180
answers, e.g. for choose('prompt', '&yes\n&no'): 'y', ' Y ', ' yes',
181
'YES ' are all valid input lines for choosing 'yes'.
183
An empty line, when in line-based mode, or pressing enter in char-based
184
mode will select the default choice (if any).
186
Choice is echoed back if:
187
- input is char-based; which means a controlling terminal is available,
188
and osutils.getchar is used
189
- input is line-based, and no controlling terminal is available
192
choose_ui = _ChooseUI(self, msg, choices, default)
193
return choose_ui.interact()
68
195
def be_quiet(self, state):
69
196
if state and not self._quiet:
82
209
# to clear it. We might need to separately check for the case of
83
210
self._progress_view.clear()
85
def get_boolean(self, prompt):
87
self.prompt(prompt + "? [y/n]: ")
88
line = self.stdin.readline().lower()
89
if line in ('y\n', 'yes\n'):
91
elif line in ('n\n', 'no\n'):
93
elif line in ('', None):
94
# end-of-file; possibly should raise an error here instead
97
212
def get_integer(self, prompt):
99
214
self.prompt(prompt)
202
317
:param kwargs: Dictionary of arguments to insert into the prompt,
203
318
to allow UIs to reformat the prompt.
320
if type(prompt) != unicode:
321
raise ValueError("prompt %r not a unicode string" % prompt)
206
323
# See <https://launchpad.net/bugs/365891>
207
324
prompt = prompt % kwargs
208
325
prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
209
326
self.clear_term()
210
328
self.stderr.write(prompt)
212
330
def report_transport_activity(self, transport, byte_count, direction):
301
422
# correspond reliably to overall command progress
302
423
self.enable_bar = False
425
def _avail_width(self):
426
# we need one extra space for terminals that wrap on last char
427
w = osutils.terminal_width()
304
433
def _show_line(self, s):
305
434
# sys.stderr.write("progress %r\n" % s)
306
width = osutils.terminal_width()
435
width = self._avail_width()
307
436
if width is not None:
308
# we need one extra space for terminals that wrap on last char
310
437
s = '%-*.*s' % (width, width, s)
311
438
self._term_file.write('\r' + s + '\r')
364
495
t = t._parent_task
366
497
m = t.msg + ':' + m
369
500
def _render_line(self):
370
501
bar_string = self._render_bar()
371
502
if self._last_task:
372
task_msg = self._format_task(self._last_task)
503
task_part, counter_part = self._format_task(self._last_task)
505
task_part = counter_part = ''
375
506
if self._last_task and not self._last_task.show_transport_activity:
378
509
trans = self._last_transport_msg
381
return (bar_string + trans + task_msg)
510
# the bar separates the transport activity from the message, so even
511
# if there's no bar or spinner, we must show something if both those
513
if (task_part or trans) and not bar_string:
515
# preferentially truncate the task message if we don't have enough
517
avail_width = self._avail_width()
518
if avail_width is not None:
519
# if terminal avail_width is unknown, don't truncate
520
current_len = len(bar_string) + len(trans) + len(task_part) + len(counter_part)
521
gap = current_len - avail_width
523
task_part = task_part[:-gap-2] + '..'
524
s = trans + bar_string + task_part + counter_part
525
if avail_width is not None:
526
if len(s) < avail_width:
527
s = s.ljust(avail_width)
528
elif len(s) > avail_width:
383
532
def _repaint(self):
384
533
s = self._render_line()