~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/ui/text.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-10-13 06:08:53 UTC
  • mfrom: (4737.1.1 merge-2.0-into-devel)
  • Revision ID: pqm@pqm.ubuntu.com-20091013060853-erk2aaj80fnkrv25
(andrew) Merge lp:bzr/2.0 into lp:bzr, including fixes for #322807,
        #389413, #402623 and documentation improvements.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005, 2008, 2009 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
18
18
"""Text UI, write output to the console.
19
19
"""
20
20
 
21
 
from __future__ import absolute_import
22
 
 
 
21
import getpass
23
22
import os
24
23
import sys
25
24
import time
 
25
import warnings
26
26
 
27
27
from bzrlib.lazy_import import lazy_import
28
28
lazy_import(globals(), """
29
 
import codecs
30
 
import getpass
31
 
import warnings
32
 
 
33
29
from bzrlib import (
34
30
    debug,
35
31
    progress,
36
32
    osutils,
37
 
    trace,
 
33
    symbol_versioning,
38
34
    )
39
35
 
40
36
""")
45
41
    )
46
42
 
47
43
 
48
 
class _ChooseUI(object):
49
 
 
50
 
    """ Helper class for choose implementation.
51
 
    """
52
 
 
53
 
    def __init__(self, ui, msg, choices, default):
54
 
        self.ui = ui
55
 
        self._setup_mode()
56
 
        self._build_alternatives(msg, choices, default)
57
 
 
58
 
    def _setup_mode(self):
59
 
        """Setup input mode (line-based, char-based) and echo-back.
60
 
 
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
63
 
        terminal.
64
 
        """
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
68
 
            self.echo_back = True
69
 
        else:
70
 
            self.line_based = True
71
 
            self.echo_back = not self.ui.stdin.isatty()
72
 
 
73
 
    def _build_alternatives(self, msg, choices, default):
74
 
        """Parse choices string.
75
 
 
76
 
        Setup final prompt and the lists of choices and associated
77
 
        shortcuts.
78
 
        """
79
 
        index = 0
80
 
        help_list = []
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")
85
 
        for c in choices:
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):
93
 
                help = c[:shortcut]
94
 
                help += '[' + c[shortcut + 1] + ']'
95
 
                help += c[(shortcut + 2):]
96
 
                shortcut = c[shortcut + 1]
97
 
            else:
98
 
                c = c.replace('&', '')
99
 
                shortcut = c[0]
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.
106
 
            if index == default:
107
 
                self.alternatives[''] = choice
108
 
                self.alternatives['\r'] = choice
109
 
            help_list.append(help)
110
 
            index += 1
111
 
 
112
 
        self.prompt = u'%s (%s): ' % (msg, ', '.join(help_list))
113
 
 
114
 
    def _getline(self):
115
 
        line = self.ui.stdin.readline()
116
 
        if '' == line:
117
 
            raise EOFError
118
 
        return line.strip()
119
 
 
120
 
    def _getchar(self):
121
 
        char = osutils.getchar()
122
 
        if char == chr(3): # INTR
123
 
            raise KeyboardInterrupt
124
 
        if char == chr(4): # EOF (^d, C-d)
125
 
            raise EOFError
126
 
        return char
127
 
 
128
 
    def interact(self):
129
 
        """Keep asking the user until a valid choice is made.
130
 
        """
131
 
        if self.line_based:
132
 
            getchoice = self._getline
133
 
        else:
134
 
            getchoice = self._getchar
135
 
        iter = 0
136
 
        while True:
137
 
            iter += 1
138
 
            if 1 == iter or self.line_based:
139
 
                self.ui.prompt(self.prompt)
140
 
            try:
141
 
                choice = getchoice()
142
 
            except EOFError:
143
 
                self.ui.stderr.write('\n')
144
 
                return None
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.
151
 
                continue
152
 
            name, index = self.alternatives[choice]
153
 
            if self.echo_back:
154
 
                self.ui.stderr.write(name + '\n')
155
 
            return index
156
 
 
157
 
 
158
44
class TextUIFactory(UIFactory):
159
45
    """A UI factory for Text user interefaces."""
160
46
 
163
49
                 stdout=None,
164
50
                 stderr=None):
165
51
        """Create a TextUIFactory.
 
52
 
 
53
        :param bar_type: The type of progress bar to create.  Deprecated
 
54
            and ignored; a TextProgressView is always used.
166
55
        """
167
56
        super(TextUIFactory, self).__init__()
168
57
        # TODO: there's no good reason not to pass all three streams, maybe we
172
61
        self.stderr = stderr
173
62
        # paints progress, network activity, etc
174
63
        self._progress_view = self.make_progress_view()
175
 
 
176
 
    def choose(self, msg, choices, default=None):
177
 
        """Prompt the user for a list of alternatives.
178
 
 
179
 
        Support both line-based and char-based editing.
180
 
 
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'.
184
 
 
185
 
        An empty line, when in line-based mode, or pressing enter in char-based
186
 
        mode will select the default choice (if any).
187
 
 
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
192
 
        """
193
 
 
194
 
        choose_ui = _ChooseUI(self, msg, choices, default)
195
 
        return choose_ui.interact()
196
 
 
197
 
    def be_quiet(self, state):
198
 
        if state and not self._quiet:
199
 
            self.clear_term()
200
 
        UIFactory.be_quiet(self, state)
201
 
        self._progress_view = self.make_progress_view()
202
 
 
 
64
        
203
65
    def clear_term(self):
204
66
        """Prepare the terminal for output.
205
67
 
211
73
        # to clear it.  We might need to separately check for the case of
212
74
        self._progress_view.clear()
213
75
 
214
 
    def get_integer(self, prompt):
 
76
    def get_boolean(self, prompt):
215
77
        while True:
216
 
            self.prompt(prompt)
217
 
            line = self.stdin.readline()
218
 
            try:
219
 
                return int(line)
220
 
            except ValueError:
221
 
                pass
 
78
            self.prompt(prompt + "? [y/n]: ")
 
79
            line = self.stdin.readline().lower()
 
80
            if line in ('y\n', 'yes\n'):
 
81
                return True
 
82
            elif line in ('n\n', 'no\n'):
 
83
                return False
 
84
            elif line in ('', None):
 
85
                # end-of-file; possibly should raise an error here instead
 
86
                return None
222
87
 
223
88
    def get_non_echoed_password(self):
224
89
        isatty = getattr(self.stdin, 'isatty', None)
235
100
                password = password[:-1]
236
101
        return password
237
102
 
238
 
    def get_password(self, prompt=u'', **kwargs):
 
103
    def get_password(self, prompt='', **kwargs):
239
104
        """Prompt the user for a password.
240
105
 
241
106
        :param prompt: The prompt to present the user
273
138
    def make_progress_view(self):
274
139
        """Construct and return a new ProgressView subclass for this UI.
275
140
        """
276
 
        # with --quiet, never any progress view
277
 
        # <https://bugs.launchpad.net/bzr/+bug/320035>.  Otherwise if the
278
 
        # user specifically requests either text or no progress bars, always
279
 
        # do that.  otherwise, guess based on $TERM and tty presence.
280
 
        if self.is_quiet():
281
 
            return NullProgressView()
282
 
        elif os.environ.get('BZR_PROGRESS_BAR') == 'text':
 
141
        # if the user specifically requests either text or no progress bars,
 
142
        # always do that.  otherwise, guess based on $TERM and tty presence.
 
143
        if os.environ.get('BZR_PROGRESS_BAR') == 'text':
283
144
            return TextProgressView(self.stderr)
284
145
        elif os.environ.get('BZR_PROGRESS_BAR') == 'none':
285
146
            return NullProgressView()
288
149
        else:
289
150
            return NullProgressView()
290
151
 
291
 
    def _make_output_stream_explicit(self, encoding, encoding_type):
292
 
        if encoding_type == 'exact':
293
 
            # force sys.stdout to be binary stream on win32; 
294
 
            # NB: this leaves the file set in that mode; may cause problems if
295
 
            # one process tries to do binary and then text output
296
 
            if sys.platform == 'win32':
297
 
                fileno = getattr(self.stdout, 'fileno', None)
298
 
                if fileno:
299
 
                    import msvcrt
300
 
                    msvcrt.setmode(fileno(), os.O_BINARY)
301
 
            return TextUIOutputStream(self, self.stdout)
302
 
        else:
303
 
            encoded_stdout = codecs.getwriter(encoding)(self.stdout,
304
 
                errors=encoding_type)
305
 
            # For whatever reason codecs.getwriter() does not advertise its encoding
306
 
            # it just returns the encoding of the wrapped file, which is completely
307
 
            # bogus. So set the attribute, so we can find the correct encoding later.
308
 
            encoded_stdout.encoding = encoding
309
 
            return TextUIOutputStream(self, encoded_stdout)
310
 
 
311
152
    def note(self, msg):
312
153
        """Write an already-formatted message, clearing the progress bar if necessary."""
313
154
        self.clear_term()
319
160
        :param kwargs: Dictionary of arguments to insert into the prompt,
320
161
            to allow UIs to reformat the prompt.
321
162
        """
322
 
        if type(prompt) != unicode:
323
 
            raise ValueError("prompt %r not a unicode string" % prompt)
324
163
        if kwargs:
325
164
            # See <https://launchpad.net/bugs/365891>
326
165
            prompt = prompt % kwargs
327
166
        prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
328
167
        self.clear_term()
329
 
        self.stdout.flush()
330
168
        self.stderr.write(prompt)
331
169
 
332
170
    def report_transport_activity(self, transport, byte_count, direction):
338
176
        self._progress_view.show_transport_activity(transport,
339
177
            direction, byte_count)
340
178
 
341
 
    def log_transport_activity(self, display=False):
342
 
        """See UIFactory.log_transport_activity()"""
343
 
        log = getattr(self._progress_view, 'log_transport_activity', None)
344
 
        if log is not None:
345
 
            log(display=display)
346
 
 
347
 
    def show_error(self, msg):
348
 
        self.clear_term()
349
 
        self.stderr.write("bzr: error: %s\n" % msg)
350
 
 
351
 
    def show_message(self, msg):
352
 
        self.note(msg)
353
 
 
354
 
    def show_warning(self, msg):
355
 
        self.clear_term()
356
 
        if isinstance(msg, unicode):
357
 
            te = osutils.get_terminal_encoding()
358
 
            msg = msg.encode(te, 'replace')
359
 
        self.stderr.write("bzr: warning: %s\n" % msg)
360
 
 
361
179
    def _progress_updated(self, task):
362
180
        """A task has been updated and wants to be displayed.
363
181
        """
365
183
            warnings.warn("%r updated but no tasks are active" %
366
184
                (task,))
367
185
        elif task != self._task_stack[-1]:
368
 
            # We used to check it was the top task, but it's hard to always
369
 
            # get this right and it's not necessarily useful: any actual
370
 
            # problems will be evident in use
371
 
            #warnings.warn("%r is not the top progress task %r" %
372
 
            #     (task, self._task_stack[-1]))
373
 
            pass
 
186
            warnings.warn("%r is not the top progress task %r" %
 
187
                (task, self._task_stack[-1]))
374
188
        self._progress_view.show_progress(task)
375
189
 
376
190
    def _progress_all_finished(self):
377
191
        self._progress_view.clear()
378
192
 
379
 
    def show_user_warning(self, warning_id, **message_args):
380
 
        """Show a text message to the user.
381
 
 
382
 
        Explicitly not for warnings about bzr apis, deprecations or internals.
383
 
        """
384
 
        # eventually trace.warning should migrate here, to avoid logging and
385
 
        # be easier to test; that has a lot of test fallout so for now just
386
 
        # new code can call this
387
 
        if warning_id not in self.suppressed_warnings:
388
 
            self.stderr.write(self.format_user_warning(warning_id, message_args) +
389
 
                '\n')
390
 
 
391
193
 
392
194
class TextProgressView(object):
393
195
    """Display of progress bar and other information on a tty.
408
210
        self._term_file = term_file
409
211
        # true when there's output on the screen we may need to clear
410
212
        self._have_output = False
 
213
        # XXX: We could listen for SIGWINCH and update the terminal width...
 
214
        # https://launchpad.net/bugs/316357
 
215
        self._width = osutils.terminal_width()
411
216
        self._last_transport_msg = ''
412
217
        self._spin_pos = 0
413
218
        # time we last repainted the screen
417
222
        self._last_task = None
418
223
        self._total_byte_count = 0
419
224
        self._bytes_since_update = 0
420
 
        self._bytes_by_direction = {'unknown': 0, 'read': 0, 'write': 0}
421
 
        self._first_byte_time = None
422
225
        self._fraction = 0
423
 
        # force the progress bar to be off, as at the moment it doesn't 
424
 
        # correspond reliably to overall command progress
425
 
        self.enable_bar = False
426
 
 
427
 
    def _avail_width(self):
428
 
        # we need one extra space for terminals that wrap on last char
429
 
        w = osutils.terminal_width() 
430
 
        if w is None:
431
 
            return None
432
 
        else:
433
 
            return w - 1
434
226
 
435
227
    def _show_line(self, s):
436
228
        # sys.stderr.write("progress %r\n" % s)
437
 
        width = self._avail_width()
438
 
        if width is not None:
439
 
            s = '%-*.*s' % (width, width, s)
440
 
        self._term_file.write('\r' + s + '\r')
 
229
        n = self._width - 1
 
230
        self._term_file.write('\r%-*.*s\r' % (n, n, s))
441
231
 
442
232
    def clear(self):
443
233
        if self._have_output:
446
236
 
447
237
    def _render_bar(self):
448
238
        # return a string for the progress bar itself
449
 
        if self.enable_bar and (
450
 
            (self._last_task is None) or self._last_task.show_bar):
 
239
        if (self._last_task is None) or self._last_task.show_bar:
451
240
            # If there's no task object, we show space for the bar anyhow.
452
241
            # That's because most invocations of bzr will end showing progress
453
242
            # at some point, though perhaps only after doing some initial IO.
469
258
            markers = int(round(float(cols) * completion_fraction)) - 1
470
259
            bar_str = '[' + ('#' * markers + spin_str).ljust(cols) + '] '
471
260
            return bar_str
472
 
        elif (self._last_task is None) or self._last_task.show_spinner:
 
261
        elif self._last_task.show_spinner:
473
262
            # The last task wanted just a spinner, no bar
474
263
            spin_str =  r'/-\|'[self._spin_pos % 4]
475
264
            self._spin_pos += 1
478
267
            return ''
479
268
 
480
269
    def _format_task(self, task):
481
 
        """Format task-specific parts of progress bar.
482
 
 
483
 
        :returns: (text_part, counter_part) both unicode strings.
484
 
        """
485
270
        if not task.show_count:
486
271
            s = ''
487
272
        elif task.current_cnt is not None and task.total_cnt is not None:
497
282
            t = t._parent_task
498
283
            if t.msg:
499
284
                m = t.msg + ':' + m
500
 
        return m, s
 
285
        return m + s
501
286
 
502
287
    def _render_line(self):
503
288
        bar_string = self._render_bar()
504
289
        if self._last_task:
505
 
            task_part, counter_part = self._format_task(self._last_task)
 
290
            task_msg = self._format_task(self._last_task)
506
291
        else:
507
 
            task_part = counter_part = ''
 
292
            task_msg = ''
508
293
        if self._last_task and not self._last_task.show_transport_activity:
509
294
            trans = ''
510
295
        else:
511
296
            trans = self._last_transport_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
514
 
        # fields are present
515
 
        if (task_part or trans) and not bar_string:
516
 
            bar_string = '| '
517
 
        # preferentially truncate the task message if we don't have enough
518
 
        # space
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
524
 
            if gap > 0:
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:
531
 
                s = s[:avail_width]
532
 
        return s
 
297
            if trans:
 
298
                trans += ' | '
 
299
        return (bar_string + trans + task_msg)
533
300
 
534
301
    def _repaint(self):
535
302
        s = self._render_line()
559
326
        This may update a progress bar, spinner, or similar display.
560
327
        By default it does nothing.
561
328
        """
562
 
        # XXX: there should be a transport activity model, and that too should
563
 
        #      be seen by the progress view, rather than being poked in here.
 
329
        # XXX: Probably there should be a transport activity model, and that
 
330
        # too should be seen by the progress view, rather than being poked in
 
331
        # here.
 
332
        if not self._have_output:
 
333
            # As a workaround for <https://launchpad.net/bugs/321935> we only
 
334
            # show transport activity when there's already a progress bar
 
335
            # shown, which time the application code is expected to know to
 
336
            # clear off the progress bar when it's going to send some other
 
337
            # output.  Eventually it would be nice to have that automatically
 
338
            # synchronized.
 
339
            return
564
340
        self._total_byte_count += byte_count
565
341
        self._bytes_since_update += byte_count
566
 
        if self._first_byte_time is None:
567
 
            # Note that this isn't great, as technically it should be the time
568
 
            # when the bytes started transferring, not when they completed.
569
 
            # However, we usually start with a small request anyway.
570
 
            self._first_byte_time = time.time()
571
 
        if direction in self._bytes_by_direction:
572
 
            self._bytes_by_direction[direction] += byte_count
573
 
        else:
574
 
            self._bytes_by_direction['unknown'] += byte_count
575
 
        if 'no_activity' in debug.debug_flags:
576
 
            # Can be used as a workaround if
577
 
            # <https://launchpad.net/bugs/321935> reappears and transport
578
 
            # activity is cluttering other output.  However, thanks to
579
 
            # TextUIOutputStream this shouldn't be a problem any more.
580
 
            return
581
342
        now = time.time()
582
343
        if self._total_byte_count < 2000:
583
344
            # a little resistance at first, so it doesn't stay stuck at 0
588
349
        elif now >= (self._transport_update_time + 0.5):
589
350
            # guard against clock stepping backwards, and don't update too
590
351
            # often
591
 
            rate = (self._bytes_since_update
592
 
                    / (now - self._transport_update_time))
593
 
            # using base-10 units (see HACKING.txt).
594
 
            msg = ("%6dkB %5dkB/s " %
595
 
                    (self._total_byte_count / 1000, int(rate) / 1000,))
 
352
            rate = self._bytes_since_update / (now - self._transport_update_time)
 
353
            msg = ("%6dKB %5dKB/s" %
 
354
                    (self._total_byte_count>>10, int(rate)>>10,))
596
355
            self._transport_update_time = now
597
356
            self._last_repaint = now
598
357
            self._bytes_since_update = 0
599
358
            self._last_transport_msg = msg
600
359
            self._repaint()
601
 
 
602
 
    def _format_bytes_by_direction(self):
603
 
        if self._first_byte_time is None:
604
 
            bps = 0.0
605
 
        else:
606
 
            transfer_time = time.time() - self._first_byte_time
607
 
            if transfer_time < 0.001:
608
 
                transfer_time = 0.001
609
 
            bps = self._total_byte_count / transfer_time
610
 
 
611
 
        # using base-10 units (see HACKING.txt).
612
 
        msg = ('Transferred: %.0fkB'
613
 
               ' (%.1fkB/s r:%.0fkB w:%.0fkB'
614
 
               % (self._total_byte_count / 1000.,
615
 
                  bps / 1000.,
616
 
                  self._bytes_by_direction['read'] / 1000.,
617
 
                  self._bytes_by_direction['write'] / 1000.,
618
 
                 ))
619
 
        if self._bytes_by_direction['unknown'] > 0:
620
 
            msg += ' u:%.0fkB)' % (
621
 
                self._bytes_by_direction['unknown'] / 1000.
622
 
                )
623
 
        else:
624
 
            msg += ')'
625
 
        return msg
626
 
 
627
 
    def log_transport_activity(self, display=False):
628
 
        msg = self._format_bytes_by_direction()
629
 
        trace.mutter(msg)
630
 
        if display and self._total_byte_count > 0:
631
 
            self.clear()
632
 
            self._term_file.write(msg + '\n')
633
 
 
634
 
 
635
 
class TextUIOutputStream(object):
636
 
    """Decorates an output stream so that the terminal is cleared before writing.
637
 
 
638
 
    This is supposed to ensure that the progress bar does not conflict with bulk
639
 
    text output.
640
 
    """
641
 
    # XXX: this does not handle the case of writing part of a line, then doing
642
 
    # progress bar output: the progress bar will probably write over it.
643
 
    # one option is just to buffer that text until we have a full line;
644
 
    # another is to save and restore it
645
 
 
646
 
    # XXX: might need to wrap more methods
647
 
 
648
 
    def __init__(self, ui_factory, wrapped_stream):
649
 
        self.ui_factory = ui_factory
650
 
        self.wrapped_stream = wrapped_stream
651
 
        # this does no transcoding, but it must expose the underlying encoding
652
 
        # because some callers need to know what can be written - see for
653
 
        # example unescape_for_display.
654
 
        self.encoding = getattr(wrapped_stream, 'encoding', None)
655
 
 
656
 
    def flush(self):
657
 
        self.ui_factory.clear_term()
658
 
        self.wrapped_stream.flush()
659
 
 
660
 
    def write(self, to_write):
661
 
        self.ui_factory.clear_term()
662
 
        self.wrapped_stream.write(to_write)
663
 
 
664
 
    def writelines(self, lines):
665
 
        self.ui_factory.clear_term()
666
 
        self.wrapped_stream.writelines(lines)