18
18
"""Text UI, write output to the console.
21
from __future__ import absolute_import
28
27
from bzrlib.lazy_import import lazy_import
29
28
lazy_import(globals(), """
30
33
from bzrlib import (
40
from bzrlib.osutils import watch_sigwinch
42
42
from bzrlib.ui import (
48
class _ChooseUI(object):
50
""" Helper class for choose implementation.
53
def __init__(self, ui, msg, choices, default):
56
self._build_alternatives(msg, choices, default)
58
def _setup_mode(self):
59
"""Setup input mode (line-based, char-based) and echo-back.
61
Line-based input is used if the BZR_TEXTUI_INPUT environment
62
variable is set to 'line-based', or if there is no controlling
65
if os.environ.get('BZR_TEXTUI_INPUT') != 'line-based' and \
66
self.ui.stdin == sys.stdin and self.ui.stdin.isatty():
67
self.line_based = False
70
self.line_based = True
71
self.echo_back = not self.ui.stdin.isatty()
73
def _build_alternatives(self, msg, choices, default):
74
"""Parse choices string.
76
Setup final prompt and the lists of choices and associated
81
self.alternatives = {}
82
choices = choices.split('\n')
83
if default is not None and default not in range(0, len(choices)):
84
raise ValueError("invalid default index")
86
name = c.replace('&', '').lower()
87
choice = (name, index)
88
if name in self.alternatives:
89
raise ValueError("duplicated choice: %s" % name)
90
self.alternatives[name] = choice
91
shortcut = c.find('&')
92
if -1 != shortcut and (shortcut + 1) < len(c):
94
help += '[' + c[shortcut + 1] + ']'
95
help += c[(shortcut + 2):]
96
shortcut = c[shortcut + 1]
98
c = c.replace('&', '')
100
help = '[%s]%s' % (shortcut, c[1:])
101
shortcut = shortcut.lower()
102
if shortcut in self.alternatives:
103
raise ValueError("duplicated shortcut: %s" % shortcut)
104
self.alternatives[shortcut] = choice
105
# Add redirections for default.
107
self.alternatives[''] = choice
108
self.alternatives['\r'] = choice
109
help_list.append(help)
112
self.prompt = u'%s (%s): ' % (msg, ', '.join(help_list))
115
line = self.ui.stdin.readline()
121
char = osutils.getchar()
122
if char == chr(3): # INTR
123
raise KeyboardInterrupt
124
if char == chr(4): # EOF (^d, C-d)
129
"""Keep asking the user until a valid choice is made.
132
getchoice = self._getline
134
getchoice = self._getchar
138
if 1 == iter or self.line_based:
139
self.ui.prompt(self.prompt)
143
self.ui.stderr.write('\n')
145
except KeyboardInterrupt:
146
self.ui.stderr.write('\n')
147
raise KeyboardInterrupt
148
choice = choice.lower()
149
if choice not in self.alternatives:
150
# Not a valid choice, keep on asking.
152
name, index = self.alternatives[choice]
154
self.ui.stderr.write(name + '\n')
48
158
class TextUIFactory(UIFactory):
49
159
"""A UI factory for Text user interefaces."""
62
172
self.stderr = stderr
63
173
# paints progress, network activity, etc
64
174
self._progress_view = self.make_progress_view()
65
# hook up the signals to watch for terminal size changes
176
def choose(self, msg, choices, default=None):
177
"""Prompt the user for a list of alternatives.
179
Support both line-based and char-based editing.
181
In line-based mode, both the shortcut and full choice name are valid
182
answers, e.g. for choose('prompt', '&yes\n&no'): 'y', ' Y ', ' yes',
183
'YES ' are all valid input lines for choosing 'yes'.
185
An empty line, when in line-based mode, or pressing enter in char-based
186
mode will select the default choice (if any).
188
Choice is echoed back if:
189
- input is char-based; which means a controlling terminal is available,
190
and osutils.getchar is used
191
- input is line-based, and no controlling terminal is available
194
choose_ui = _ChooseUI(self, msg, choices, default)
195
return choose_ui.interact()
68
197
def be_quiet(self, state):
69
198
if state and not self._quiet:
82
211
# to clear it. We might need to separately check for the case of
83
212
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
214
def get_integer(self, prompt):
99
216
self.prompt(prompt)
202
319
:param kwargs: Dictionary of arguments to insert into the prompt,
203
320
to allow UIs to reformat the prompt.
322
if type(prompt) != unicode:
323
raise ValueError("prompt %r not a unicode string" % prompt)
206
325
# See <https://launchpad.net/bugs/365891>
207
326
prompt = prompt % kwargs
208
327
prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
209
328
self.clear_term()
210
330
self.stderr.write(prompt)
212
332
def report_transport_activity(self, transport, byte_count, direction):
301
424
# correspond reliably to overall command progress
302
425
self.enable_bar = False
427
def _avail_width(self):
428
# we need one extra space for terminals that wrap on last char
429
w = osutils.terminal_width()
304
435
def _show_line(self, s):
305
436
# sys.stderr.write("progress %r\n" % s)
306
width = osutils.terminal_width()
437
width = self._avail_width()
307
438
if width is not None:
308
# we need one extra space for terminals that wrap on last char
310
439
s = '%-*.*s' % (width, width, s)
311
440
self._term_file.write('\r' + s + '\r')
364
497
t = t._parent_task
366
499
m = t.msg + ':' + m
369
502
def _render_line(self):
370
503
bar_string = self._render_bar()
371
504
if self._last_task:
372
task_msg = self._format_task(self._last_task)
505
task_part, counter_part = self._format_task(self._last_task)
507
task_part = counter_part = ''
375
508
if self._last_task and not self._last_task.show_transport_activity:
378
511
trans = self._last_transport_msg
381
return (bar_string + trans + task_msg)
512
# the bar separates the transport activity from the message, so even
513
# if there's no bar or spinner, we must show something if both those
515
if (task_part or trans) and not bar_string:
517
# preferentially truncate the task message if we don't have enough
519
avail_width = self._avail_width()
520
if avail_width is not None:
521
# if terminal avail_width is unknown, don't truncate
522
current_len = len(bar_string) + len(trans) + len(task_part) + len(counter_part)
523
gap = current_len - avail_width
525
task_part = task_part[:-gap-2] + '..'
526
s = trans + bar_string + task_part + counter_part
527
if avail_width is not None:
528
if len(s) < avail_width:
529
s = s.ljust(avail_width)
530
elif len(s) > avail_width:
383
534
def _repaint(self):
384
535
s = self._render_line()