~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/ui/text.py

  • Committer: Vincent Ladeuil
  • Date: 2017-01-30 14:30:10 UTC
  • mfrom: (6615.3.7 merges)
  • mto: This revision was merged to the branch mainline in revision 6621.
  • Revision ID: v.ladeuil+lp@free.fr-20170130143010-p31t1ranfeqbaeki
Merge  2.7 into trunk including fix for bug #1657238

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2005-2011 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
 
import getpass
 
21
from __future__ import absolute_import
 
22
 
22
23
import os
23
24
import sys
24
25
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
 
29
33
from bzrlib import (
 
34
    config,
 
35
    debug,
30
36
    progress,
31
37
    osutils,
32
 
    symbol_versioning,
 
38
    trace,
33
39
    )
34
40
 
35
41
""")
40
46
    )
41
47
 
42
48
 
 
49
class _ChooseUI(object):
 
50
 
 
51
    """ Helper class for choose implementation.
 
52
    """
 
53
 
 
54
    def __init__(self, ui, msg, choices, default):
 
55
        self.ui = ui
 
56
        self._setup_mode()
 
57
        self._build_alternatives(msg, choices, default)
 
58
 
 
59
    def _setup_mode(self):
 
60
        """Setup input mode (line-based, char-based) and echo-back.
 
61
 
 
62
        Line-based input is used if the BZR_TEXTUI_INPUT environment
 
63
        variable is set to 'line-based', or if there is no controlling
 
64
        terminal.
 
65
        """
 
66
        if os.environ.get('BZR_TEXTUI_INPUT') != 'line-based' and \
 
67
           self.ui.stdin == sys.stdin and self.ui.stdin.isatty():
 
68
            self.line_based = False
 
69
            self.echo_back = True
 
70
        else:
 
71
            self.line_based = True
 
72
            self.echo_back = not self.ui.stdin.isatty()
 
73
 
 
74
    def _build_alternatives(self, msg, choices, default):
 
75
        """Parse choices string.
 
76
 
 
77
        Setup final prompt and the lists of choices and associated
 
78
        shortcuts.
 
79
        """
 
80
        index = 0
 
81
        help_list = []
 
82
        self.alternatives = {}
 
83
        choices = choices.split('\n')
 
84
        if default is not None and default not in range(0, len(choices)):
 
85
            raise ValueError("invalid default index")
 
86
        for c in choices:
 
87
            name = c.replace('&', '').lower()
 
88
            choice = (name, index)
 
89
            if name in self.alternatives:
 
90
                raise ValueError("duplicated choice: %s" % name)
 
91
            self.alternatives[name] = choice
 
92
            shortcut = c.find('&')
 
93
            if -1 != shortcut and (shortcut + 1) < len(c):
 
94
                help = c[:shortcut]
 
95
                help += '[' + c[shortcut + 1] + ']'
 
96
                help += c[(shortcut + 2):]
 
97
                shortcut = c[shortcut + 1]
 
98
            else:
 
99
                c = c.replace('&', '')
 
100
                shortcut = c[0]
 
101
                help = '[%s]%s' % (shortcut, c[1:])
 
102
            shortcut = shortcut.lower()
 
103
            if shortcut in self.alternatives:
 
104
                raise ValueError("duplicated shortcut: %s" % shortcut)
 
105
            self.alternatives[shortcut] = choice
 
106
            # Add redirections for default.
 
107
            if index == default:
 
108
                self.alternatives[''] = choice
 
109
                self.alternatives['\r'] = choice
 
110
            help_list.append(help)
 
111
            index += 1
 
112
 
 
113
        self.prompt = u'%s (%s): ' % (msg, ', '.join(help_list))
 
114
 
 
115
    def _getline(self):
 
116
        line = self.ui.stdin.readline()
 
117
        if '' == line:
 
118
            raise EOFError
 
119
        return line.strip()
 
120
 
 
121
    def _getchar(self):
 
122
        char = osutils.getchar()
 
123
        if char == chr(3): # INTR
 
124
            raise KeyboardInterrupt
 
125
        if char == chr(4): # EOF (^d, C-d)
 
126
            raise EOFError
 
127
        return char
 
128
 
 
129
    def interact(self):
 
130
        """Keep asking the user until a valid choice is made.
 
131
        """
 
132
        if self.line_based:
 
133
            getchoice = self._getline
 
134
        else:
 
135
            getchoice = self._getchar
 
136
        iter = 0
 
137
        while True:
 
138
            iter += 1
 
139
            if 1 == iter or self.line_based:
 
140
                self.ui.prompt(self.prompt)
 
141
            try:
 
142
                choice = getchoice()
 
143
            except EOFError:
 
144
                self.ui.stderr.write('\n')
 
145
                return None
 
146
            except KeyboardInterrupt:
 
147
                self.ui.stderr.write('\n')
 
148
                raise KeyboardInterrupt
 
149
            choice = choice.lower()
 
150
            if choice not in self.alternatives:
 
151
                # Not a valid choice, keep on asking.
 
152
                continue
 
153
            name, index = self.alternatives[choice]
 
154
            if self.echo_back:
 
155
                self.ui.stderr.write(name + '\n')
 
156
            return index
 
157
 
 
158
 
 
159
opt_progress_bar = config.Option(
 
160
    'progress_bar', help='Progress bar type.',
 
161
    default_from_env=['BZR_PROGRESS_BAR'], default=None,
 
162
    invalid='error')
 
163
 
 
164
 
43
165
class TextUIFactory(UIFactory):
44
 
    """A UI factory for Text user interefaces."""
 
166
    """A UI factory for Text user interfaces."""
45
167
 
46
168
    def __init__(self,
47
169
                 stdin=None,
48
170
                 stdout=None,
49
171
                 stderr=None):
50
172
        """Create a TextUIFactory.
51
 
 
52
 
        :param bar_type: The type of progress bar to create.  Deprecated
53
 
            and ignored; a TextProgressView is always used.
54
173
        """
55
174
        super(TextUIFactory, self).__init__()
56
175
        # TODO: there's no good reason not to pass all three streams, maybe we
60
179
        self.stderr = stderr
61
180
        # paints progress, network activity, etc
62
181
        self._progress_view = self.make_progress_view()
63
 
        
 
182
 
 
183
    def choose(self, msg, choices, default=None):
 
184
        """Prompt the user for a list of alternatives.
 
185
 
 
186
        Support both line-based and char-based editing.
 
187
 
 
188
        In line-based mode, both the shortcut and full choice name are valid
 
189
        answers, e.g. for choose('prompt', '&yes\n&no'): 'y', ' Y ', ' yes',
 
190
        'YES ' are all valid input lines for choosing 'yes'.
 
191
 
 
192
        An empty line, when in line-based mode, or pressing enter in char-based
 
193
        mode will select the default choice (if any).
 
194
 
 
195
        Choice is echoed back if:
 
196
        - input is char-based; which means a controlling terminal is available,
 
197
          and osutils.getchar is used
 
198
        - input is line-based, and no controlling terminal is available
 
199
        """
 
200
 
 
201
        choose_ui = _ChooseUI(self, msg, choices, default)
 
202
        return choose_ui.interact()
 
203
 
 
204
    def be_quiet(self, state):
 
205
        if state and not self._quiet:
 
206
            self.clear_term()
 
207
        UIFactory.be_quiet(self, state)
 
208
        self._progress_view = self.make_progress_view()
 
209
 
64
210
    def clear_term(self):
65
211
        """Prepare the terminal for output.
66
212
 
72
218
        # to clear it.  We might need to separately check for the case of
73
219
        self._progress_view.clear()
74
220
 
75
 
    def get_boolean(self, prompt):
 
221
    def get_integer(self, prompt):
76
222
        while True:
77
 
            self.prompt(prompt + "? [y/n]: ")
78
 
            line = self.stdin.readline().lower()
79
 
            if line in ('y\n', 'yes\n'):
80
 
                return True
81
 
            elif line in ('n\n', 'no\n'):
82
 
                return False
83
 
            elif line in ('', None):
84
 
                # end-of-file; possibly should raise an error here instead
85
 
                return None
 
223
            self.prompt(prompt)
 
224
            line = self.stdin.readline()
 
225
            try:
 
226
                return int(line)
 
227
            except ValueError:
 
228
                pass
86
229
 
87
230
    def get_non_echoed_password(self):
88
231
        isatty = getattr(self.stdin, 'isatty', None)
95
238
            password = self.stdin.readline()
96
239
            if not password:
97
240
                password = None
98
 
            elif password[-1] == '\n':
99
 
                password = password[:-1]
 
241
            else:
 
242
                password = password.decode(self.stdin.encoding)
 
243
 
 
244
                if password[-1] == '\n':
 
245
                    password = password[:-1]
100
246
        return password
101
247
 
102
 
    def get_password(self, prompt='', **kwargs):
 
248
    def get_password(self, prompt=u'', **kwargs):
103
249
        """Prompt the user for a password.
104
250
 
105
251
        :param prompt: The prompt to present the user
130
276
        username = self.stdin.readline()
131
277
        if not username:
132
278
            username = None
133
 
        elif username[-1] == '\n':
134
 
            username = username[:-1]
 
279
        else:
 
280
            username = username.decode(self.stdin.encoding)
 
281
            if username[-1] == '\n':
 
282
                username = username[:-1]
135
283
        return username
136
284
 
137
285
    def make_progress_view(self):
138
286
        """Construct and return a new ProgressView subclass for this UI.
139
287
        """
140
 
        # if the user specifically requests either text or no progress bars,
141
 
        # always do that.  otherwise, guess based on $TERM and tty presence.
142
 
        if os.environ.get('BZR_PROGRESS_BAR') == 'text':
143
 
            return TextProgressView(self.stderr)
144
 
        elif os.environ.get('BZR_PROGRESS_BAR') == 'none':
145
 
            return NullProgressView()
146
 
        elif progress._supports_progress(self.stderr):
147
 
            return TextProgressView(self.stderr)
 
288
        # with --quiet, never any progress view
 
289
        # <https://bugs.launchpad.net/bzr/+bug/320035>.  Otherwise if the
 
290
        # user specifically requests either text or no progress bars, always
 
291
        # do that.  otherwise, guess based on $TERM and tty presence.
 
292
        if self.is_quiet():
 
293
            return NullProgressView()
 
294
        pb_type = config.GlobalStack().get('progress_bar')
 
295
        if pb_type == 'none': # Explicit requirement
 
296
            return NullProgressView()
 
297
        if (pb_type == 'text' # Explicit requirement
 
298
            or progress._supports_progress(self.stderr)): # Guess
 
299
            return TextProgressView(self.stderr)
 
300
        # No explicit requirement and no successful guess
 
301
        return NullProgressView()
 
302
 
 
303
    def _make_output_stream_explicit(self, encoding, encoding_type):
 
304
        if encoding_type == 'exact':
 
305
            # force sys.stdout to be binary stream on win32; 
 
306
            # NB: this leaves the file set in that mode; may cause problems if
 
307
            # one process tries to do binary and then text output
 
308
            if sys.platform == 'win32':
 
309
                fileno = getattr(self.stdout, 'fileno', None)
 
310
                if fileno:
 
311
                    import msvcrt
 
312
                    msvcrt.setmode(fileno(), os.O_BINARY)
 
313
            return TextUIOutputStream(self, self.stdout)
148
314
        else:
149
 
            return NullProgressView()
 
315
            encoded_stdout = codecs.getwriter(encoding)(self.stdout,
 
316
                errors=encoding_type)
 
317
            # For whatever reason codecs.getwriter() does not advertise its encoding
 
318
            # it just returns the encoding of the wrapped file, which is completely
 
319
            # bogus. So set the attribute, so we can find the correct encoding later.
 
320
            encoded_stdout.encoding = encoding
 
321
            return TextUIOutputStream(self, encoded_stdout)
150
322
 
151
323
    def note(self, msg):
152
324
        """Write an already-formatted message, clearing the progress bar if necessary."""
159
331
        :param kwargs: Dictionary of arguments to insert into the prompt,
160
332
            to allow UIs to reformat the prompt.
161
333
        """
 
334
        if type(prompt) != unicode:
 
335
            raise ValueError("prompt %r not a unicode string" % prompt)
162
336
        if kwargs:
163
337
            # See <https://launchpad.net/bugs/365891>
164
338
            prompt = prompt % kwargs
165
 
        prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
 
339
        try:
 
340
            prompt = prompt.encode(self.stderr.encoding)
 
341
        except (UnicodeError, AttributeError):
 
342
            # If stderr has no encoding attribute or can't properly encode,
 
343
            # fallback to terminal encoding for robustness (better display
 
344
            # something to the user than aborting with a traceback).
 
345
            prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
166
346
        self.clear_term()
 
347
        self.stdout.flush()
167
348
        self.stderr.write(prompt)
168
349
 
169
350
    def report_transport_activity(self, transport, byte_count, direction):
175
356
        self._progress_view.show_transport_activity(transport,
176
357
            direction, byte_count)
177
358
 
 
359
    def log_transport_activity(self, display=False):
 
360
        """See UIFactory.log_transport_activity()"""
 
361
        log = getattr(self._progress_view, 'log_transport_activity', None)
 
362
        if log is not None:
 
363
            log(display=display)
 
364
 
 
365
    def show_error(self, msg):
 
366
        self.clear_term()
 
367
        self.stderr.write("bzr: error: %s\n" % msg)
 
368
 
 
369
    def show_message(self, msg):
 
370
        self.note(msg)
 
371
 
 
372
    def show_warning(self, msg):
 
373
        self.clear_term()
 
374
        if isinstance(msg, unicode):
 
375
            te = osutils.get_terminal_encoding()
 
376
            msg = msg.encode(te, 'replace')
 
377
        self.stderr.write("bzr: warning: %s\n" % msg)
 
378
 
178
379
    def _progress_updated(self, task):
179
380
        """A task has been updated and wants to be displayed.
180
381
        """
182
383
            warnings.warn("%r updated but no tasks are active" %
183
384
                (task,))
184
385
        elif task != self._task_stack[-1]:
185
 
            warnings.warn("%r is not the top progress task %r" %
186
 
                (task, self._task_stack[-1]))
 
386
            # We used to check it was the top task, but it's hard to always
 
387
            # get this right and it's not necessarily useful: any actual
 
388
            # problems will be evident in use
 
389
            #warnings.warn("%r is not the top progress task %r" %
 
390
            #     (task, self._task_stack[-1]))
 
391
            pass
187
392
        self._progress_view.show_progress(task)
188
393
 
189
394
    def _progress_all_finished(self):
190
395
        self._progress_view.clear()
191
396
 
 
397
    def show_user_warning(self, warning_id, **message_args):
 
398
        """Show a text message to the user.
 
399
 
 
400
        Explicitly not for warnings about bzr apis, deprecations or internals.
 
401
        """
 
402
        # eventually trace.warning should migrate here, to avoid logging and
 
403
        # be easier to test; that has a lot of test fallout so for now just
 
404
        # new code can call this
 
405
        if warning_id not in self.suppressed_warnings:
 
406
            self.stderr.write(self.format_user_warning(warning_id, message_args) +
 
407
                '\n')
 
408
 
192
409
 
193
410
class TextProgressView(object):
194
411
    """Display of progress bar and other information on a tty.
205
422
    this only prints the stack from the nominated current task up to the root.
206
423
    """
207
424
 
208
 
    def __init__(self, term_file):
 
425
    def __init__(self, term_file, encoding=None, errors="replace"):
209
426
        self._term_file = term_file
 
427
        if encoding is None:
 
428
            self._encoding = getattr(term_file, "encoding", None) or "ascii"
 
429
        else:
 
430
            self._encoding = encoding
 
431
        self._encoding_errors = errors
210
432
        # true when there's output on the screen we may need to clear
211
433
        self._have_output = False
212
 
        # XXX: We could listen for SIGWINCH and update the terminal width...
213
 
        # https://launchpad.net/bugs/316357
214
 
        self._width = osutils.terminal_width()
215
434
        self._last_transport_msg = ''
216
435
        self._spin_pos = 0
217
436
        # time we last repainted the screen
221
440
        self._last_task = None
222
441
        self._total_byte_count = 0
223
442
        self._bytes_since_update = 0
224
 
 
225
 
    def _show_line(self, s):
226
 
        # sys.stderr.write("progress %r\n" % s)
227
 
        n = self._width - 1
228
 
        self._term_file.write('\r%-*.*s\r' % (n, n, s))
 
443
        self._bytes_by_direction = {'unknown': 0, 'read': 0, 'write': 0}
 
444
        self._first_byte_time = None
 
445
        self._fraction = 0
 
446
        # force the progress bar to be off, as at the moment it doesn't 
 
447
        # correspond reliably to overall command progress
 
448
        self.enable_bar = False
 
449
 
 
450
    def _avail_width(self):
 
451
        # we need one extra space for terminals that wrap on last char
 
452
        w = osutils.terminal_width() 
 
453
        if w is None:
 
454
            return None
 
455
        else:
 
456
            return w - 1
 
457
 
 
458
    def _show_line(self, u):
 
459
        s = u.encode(self._encoding, self._encoding_errors)
 
460
        width = self._avail_width()
 
461
        if width is not None:
 
462
            # GZ 2012-03-28: Counting bytes is wrong for calculating width of
 
463
            #                text but better than counting codepoints.
 
464
            s = '%-*.*s' % (width, width, s)
 
465
        self._term_file.write('\r' + s + '\r')
229
466
 
230
467
    def clear(self):
231
468
        if self._have_output:
234
471
 
235
472
    def _render_bar(self):
236
473
        # return a string for the progress bar itself
237
 
        if (self._last_task is None) or self._last_task.show_bar:
 
474
        if self.enable_bar and (
 
475
            (self._last_task is None) or self._last_task.show_bar):
238
476
            # If there's no task object, we show space for the bar anyhow.
239
477
            # That's because most invocations of bzr will end showing progress
240
478
            # at some point, though perhaps only after doing some initial IO.
245
483
            cols = 20
246
484
            if self._last_task is None:
247
485
                completion_fraction = 0
 
486
                self._fraction = 0
248
487
            else:
249
488
                completion_fraction = \
250
489
                    self._last_task._overall_completion_fraction() or 0
 
490
            if (completion_fraction < self._fraction and 'progress' in
 
491
                debug.debug_flags):
 
492
                import pdb;pdb.set_trace()
 
493
            self._fraction = completion_fraction
251
494
            markers = int(round(float(cols) * completion_fraction)) - 1
252
495
            bar_str = '[' + ('#' * markers + spin_str).ljust(cols) + '] '
253
496
            return bar_str
254
 
        elif self._last_task.show_spinner:
 
497
        elif (self._last_task is None) or self._last_task.show_spinner:
255
498
            # The last task wanted just a spinner, no bar
256
499
            spin_str =  r'/-\|'[self._spin_pos % 4]
257
500
            self._spin_pos += 1
260
503
            return ''
261
504
 
262
505
    def _format_task(self, task):
 
506
        """Format task-specific parts of progress bar.
 
507
 
 
508
        :returns: (text_part, counter_part) both unicode strings.
 
509
        """
263
510
        if not task.show_count:
264
511
            s = ''
265
512
        elif task.current_cnt is not None and task.total_cnt is not None:
275
522
            t = t._parent_task
276
523
            if t.msg:
277
524
                m = t.msg + ':' + m
278
 
        return m + s
 
525
        return m, s
279
526
 
280
527
    def _render_line(self):
281
528
        bar_string = self._render_bar()
282
529
        if self._last_task:
283
 
            task_msg = self._format_task(self._last_task)
 
530
            task_part, counter_part = self._format_task(self._last_task)
284
531
        else:
285
 
            task_msg = ''
 
532
            task_part = counter_part = ''
286
533
        if self._last_task and not self._last_task.show_transport_activity:
287
534
            trans = ''
288
535
        else:
289
536
            trans = self._last_transport_msg
290
 
            if trans:
291
 
                trans += ' | '
292
 
        return (bar_string + trans + task_msg)
 
537
        # the bar separates the transport activity from the message, so even
 
538
        # if there's no bar or spinner, we must show something if both those
 
539
        # fields are present
 
540
        if (task_part or trans) and not bar_string:
 
541
            bar_string = '| '
 
542
        # preferentially truncate the task message if we don't have enough
 
543
        # space
 
544
        avail_width = self._avail_width()
 
545
        if avail_width is not None:
 
546
            # if terminal avail_width is unknown, don't truncate
 
547
            current_len = len(bar_string) + len(trans) + len(task_part) + len(counter_part)
 
548
            gap = current_len - avail_width
 
549
            if gap > 0:
 
550
                task_part = task_part[:-gap-2] + '..'
 
551
        s = trans + bar_string + task_part + counter_part
 
552
        if avail_width is not None:
 
553
            if len(s) < avail_width:
 
554
                s = s.ljust(avail_width)
 
555
            elif len(s) > avail_width:
 
556
                s = s[:avail_width]
 
557
        return s
293
558
 
294
559
    def _repaint(self):
295
560
        s = self._render_line()
319
584
        This may update a progress bar, spinner, or similar display.
320
585
        By default it does nothing.
321
586
        """
322
 
        # XXX: Probably there should be a transport activity model, and that
323
 
        # too should be seen by the progress view, rather than being poked in
324
 
        # here.
325
 
        if not self._have_output:
326
 
            # As a workaround for <https://launchpad.net/bugs/321935> we only
327
 
            # show transport activity when there's already a progress bar
328
 
            # shown, which time the application code is expected to know to
329
 
            # clear off the progress bar when it's going to send some other
330
 
            # output.  Eventually it would be nice to have that automatically
331
 
            # synchronized.
332
 
            return
 
587
        # XXX: there should be a transport activity model, and that too should
 
588
        #      be seen by the progress view, rather than being poked in here.
333
589
        self._total_byte_count += byte_count
334
590
        self._bytes_since_update += byte_count
 
591
        if self._first_byte_time is None:
 
592
            # Note that this isn't great, as technically it should be the time
 
593
            # when the bytes started transferring, not when they completed.
 
594
            # However, we usually start with a small request anyway.
 
595
            self._first_byte_time = time.time()
 
596
        if direction in self._bytes_by_direction:
 
597
            self._bytes_by_direction[direction] += byte_count
 
598
        else:
 
599
            self._bytes_by_direction['unknown'] += byte_count
 
600
        if 'no_activity' in debug.debug_flags:
 
601
            # Can be used as a workaround if
 
602
            # <https://launchpad.net/bugs/321935> reappears and transport
 
603
            # activity is cluttering other output.  However, thanks to
 
604
            # TextUIOutputStream this shouldn't be a problem any more.
 
605
            return
335
606
        now = time.time()
336
607
        if self._total_byte_count < 2000:
337
608
            # a little resistance at first, so it doesn't stay stuck at 0
342
613
        elif now >= (self._transport_update_time + 0.5):
343
614
            # guard against clock stepping backwards, and don't update too
344
615
            # often
345
 
            rate = self._bytes_since_update / (now - self._transport_update_time)
346
 
            msg = ("%6dKB %5dKB/s" %
347
 
                    (self._total_byte_count>>10, int(rate)>>10,))
 
616
            rate = (self._bytes_since_update
 
617
                    / (now - self._transport_update_time))
 
618
            # using base-10 units (see HACKING.txt).
 
619
            msg = ("%6dkB %5dkB/s " %
 
620
                    (self._total_byte_count / 1000, int(rate) / 1000,))
348
621
            self._transport_update_time = now
349
622
            self._last_repaint = now
350
623
            self._bytes_since_update = 0
351
624
            self._last_transport_msg = msg
352
625
            self._repaint()
 
626
 
 
627
    def _format_bytes_by_direction(self):
 
628
        if self._first_byte_time is None:
 
629
            bps = 0.0
 
630
        else:
 
631
            transfer_time = time.time() - self._first_byte_time
 
632
            if transfer_time < 0.001:
 
633
                transfer_time = 0.001
 
634
            bps = self._total_byte_count / transfer_time
 
635
 
 
636
        # using base-10 units (see HACKING.txt).
 
637
        msg = ('Transferred: %.0fkB'
 
638
               ' (%.1fkB/s r:%.0fkB w:%.0fkB'
 
639
               % (self._total_byte_count / 1000.,
 
640
                  bps / 1000.,
 
641
                  self._bytes_by_direction['read'] / 1000.,
 
642
                  self._bytes_by_direction['write'] / 1000.,
 
643
                 ))
 
644
        if self._bytes_by_direction['unknown'] > 0:
 
645
            msg += ' u:%.0fkB)' % (
 
646
                self._bytes_by_direction['unknown'] / 1000.
 
647
                )
 
648
        else:
 
649
            msg += ')'
 
650
        return msg
 
651
 
 
652
    def log_transport_activity(self, display=False):
 
653
        msg = self._format_bytes_by_direction()
 
654
        trace.mutter(msg)
 
655
        if display and self._total_byte_count > 0:
 
656
            self.clear()
 
657
            self._term_file.write(msg + '\n')
 
658
 
 
659
 
 
660
class TextUIOutputStream(object):
 
661
    """Decorates an output stream so that the terminal is cleared before writing.
 
662
 
 
663
    This is supposed to ensure that the progress bar does not conflict with bulk
 
664
    text output.
 
665
    """
 
666
    # XXX: this does not handle the case of writing part of a line, then doing
 
667
    # progress bar output: the progress bar will probably write over it.
 
668
    # one option is just to buffer that text until we have a full line;
 
669
    # another is to save and restore it
 
670
 
 
671
    # XXX: might need to wrap more methods
 
672
 
 
673
    def __init__(self, ui_factory, wrapped_stream):
 
674
        self.ui_factory = ui_factory
 
675
        self.wrapped_stream = wrapped_stream
 
676
        # this does no transcoding, but it must expose the underlying encoding
 
677
        # because some callers need to know what can be written - see for
 
678
        # example unescape_for_display.
 
679
        self.encoding = getattr(wrapped_stream, 'encoding', None)
 
680
 
 
681
    def flush(self):
 
682
        self.ui_factory.clear_term()
 
683
        self.wrapped_stream.flush()
 
684
 
 
685
    def write(self, to_write):
 
686
        self.ui_factory.clear_term()
 
687
        self.wrapped_stream.write(to_write)
 
688
 
 
689
    def writelines(self, lines):
 
690
        self.ui_factory.clear_term()
 
691
        self.wrapped_stream.writelines(lines)