/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/ui/text.py

  • Committer: Robert Collins
  • Date: 2012-09-25 08:26:01 UTC
  • mto: This revision was merged to the branch mainline in revision 6566.
  • Revision ID: robertc@robertcollins.net-20120925082601-sykhddmq2sxdt6oq
* ``bzr help env-variables`` now points users at ``bzr help configuration``
  which has much more detailed information on the same stuff.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005-2011 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
 
 
18
"""Text UI, write output to the console.
 
19
"""
 
20
 
 
21
from __future__ import absolute_import
 
22
 
 
23
import os
 
24
import sys
 
25
import time
 
26
 
 
27
from bzrlib.lazy_import import lazy_import
 
28
lazy_import(globals(), """
 
29
import codecs
 
30
import getpass
 
31
import warnings
 
32
 
 
33
from bzrlib import (
 
34
    config,
 
35
    debug,
 
36
    progress,
 
37
    osutils,
 
38
    trace,
 
39
    )
 
40
 
 
41
""")
 
42
 
 
43
from bzrlib.ui import (
 
44
    UIFactory,
 
45
    NullProgressView,
 
46
    )
 
47
 
 
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
 
 
165
class TextUIFactory(UIFactory):
 
166
    """A UI factory for Text user interfaces."""
 
167
 
 
168
    def __init__(self,
 
169
                 stdin=None,
 
170
                 stdout=None,
 
171
                 stderr=None):
 
172
        """Create a TextUIFactory.
 
173
        """
 
174
        super(TextUIFactory, self).__init__()
 
175
        # TODO: there's no good reason not to pass all three streams, maybe we
 
176
        # should deprecate the default values...
 
177
        self.stdin = stdin
 
178
        self.stdout = stdout
 
179
        self.stderr = stderr
 
180
        # paints progress, network activity, etc
 
181
        self._progress_view = self.make_progress_view()
 
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
 
 
210
    def clear_term(self):
 
211
        """Prepare the terminal for output.
 
212
 
 
213
        This will, clear any progress bars, and leave the cursor at the
 
214
        leftmost position."""
 
215
        # XXX: If this is preparing to write to stdout, but that's for example
 
216
        # directed into a file rather than to the terminal, and the progress
 
217
        # bar _is_ going to the terminal, we shouldn't need
 
218
        # to clear it.  We might need to separately check for the case of
 
219
        self._progress_view.clear()
 
220
 
 
221
    def get_integer(self, prompt):
 
222
        while True:
 
223
            self.prompt(prompt)
 
224
            line = self.stdin.readline()
 
225
            try:
 
226
                return int(line)
 
227
            except ValueError:
 
228
                pass
 
229
 
 
230
    def get_non_echoed_password(self):
 
231
        isatty = getattr(self.stdin, 'isatty', None)
 
232
        if isatty is not None and isatty():
 
233
            # getpass() ensure the password is not echoed and other
 
234
            # cross-platform niceties
 
235
            password = getpass.getpass('')
 
236
        else:
 
237
            # echo doesn't make sense without a terminal
 
238
            password = self.stdin.readline()
 
239
            if not password:
 
240
                password = None
 
241
            elif password[-1] == '\n':
 
242
                password = password[:-1]
 
243
        return password
 
244
 
 
245
    def get_password(self, prompt=u'', **kwargs):
 
246
        """Prompt the user for a password.
 
247
 
 
248
        :param prompt: The prompt to present the user
 
249
        :param kwargs: Arguments which will be expanded into the prompt.
 
250
                       This lets front ends display different things if
 
251
                       they so choose.
 
252
        :return: The password string, return None if the user
 
253
                 canceled the request.
 
254
        """
 
255
        prompt += ': '
 
256
        self.prompt(prompt, **kwargs)
 
257
        # There's currently no way to say 'i decline to enter a password'
 
258
        # as opposed to 'my password is empty' -- does it matter?
 
259
        return self.get_non_echoed_password()
 
260
 
 
261
    def get_username(self, prompt, **kwargs):
 
262
        """Prompt the user for a username.
 
263
 
 
264
        :param prompt: The prompt to present the user
 
265
        :param kwargs: Arguments which will be expanded into the prompt.
 
266
                       This lets front ends display different things if
 
267
                       they so choose.
 
268
        :return: The username string, return None if the user
 
269
                 canceled the request.
 
270
        """
 
271
        prompt += ': '
 
272
        self.prompt(prompt, **kwargs)
 
273
        username = self.stdin.readline()
 
274
        if not username:
 
275
            username = None
 
276
        elif username[-1] == '\n':
 
277
            username = username[:-1]
 
278
        return username
 
279
 
 
280
    def make_progress_view(self):
 
281
        """Construct and return a new ProgressView subclass for this UI.
 
282
        """
 
283
        # with --quiet, never any progress view
 
284
        # <https://bugs.launchpad.net/bzr/+bug/320035>.  Otherwise if the
 
285
        # user specifically requests either text or no progress bars, always
 
286
        # do that.  otherwise, guess based on $TERM and tty presence.
 
287
        if self.is_quiet():
 
288
            return NullProgressView()
 
289
        pb_type = config.GlobalStack().get('progress_bar')
 
290
        if pb_type == 'none': # Explicit requirement
 
291
            return NullProgressView()
 
292
        if (pb_type == 'text' # Explicit requirement
 
293
            or progress._supports_progress(self.stderr)): # Guess
 
294
            return TextProgressView(self.stderr)
 
295
        # No explicit requirement and no successful guess
 
296
        return NullProgressView()
 
297
 
 
298
    def _make_output_stream_explicit(self, encoding, encoding_type):
 
299
        if encoding_type == 'exact':
 
300
            # force sys.stdout to be binary stream on win32; 
 
301
            # NB: this leaves the file set in that mode; may cause problems if
 
302
            # one process tries to do binary and then text output
 
303
            if sys.platform == 'win32':
 
304
                fileno = getattr(self.stdout, 'fileno', None)
 
305
                if fileno:
 
306
                    import msvcrt
 
307
                    msvcrt.setmode(fileno(), os.O_BINARY)
 
308
            return TextUIOutputStream(self, self.stdout)
 
309
        else:
 
310
            encoded_stdout = codecs.getwriter(encoding)(self.stdout,
 
311
                errors=encoding_type)
 
312
            # For whatever reason codecs.getwriter() does not advertise its encoding
 
313
            # it just returns the encoding of the wrapped file, which is completely
 
314
            # bogus. So set the attribute, so we can find the correct encoding later.
 
315
            encoded_stdout.encoding = encoding
 
316
            return TextUIOutputStream(self, encoded_stdout)
 
317
 
 
318
    def note(self, msg):
 
319
        """Write an already-formatted message, clearing the progress bar if necessary."""
 
320
        self.clear_term()
 
321
        self.stdout.write(msg + '\n')
 
322
 
 
323
    def prompt(self, prompt, **kwargs):
 
324
        """Emit prompt on the CLI.
 
325
        
 
326
        :param kwargs: Dictionary of arguments to insert into the prompt,
 
327
            to allow UIs to reformat the prompt.
 
328
        """
 
329
        if type(prompt) != unicode:
 
330
            raise ValueError("prompt %r not a unicode string" % prompt)
 
331
        if kwargs:
 
332
            # See <https://launchpad.net/bugs/365891>
 
333
            prompt = prompt % kwargs
 
334
        prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
 
335
        self.clear_term()
 
336
        self.stdout.flush()
 
337
        self.stderr.write(prompt)
 
338
 
 
339
    def report_transport_activity(self, transport, byte_count, direction):
 
340
        """Called by transports as they do IO.
 
341
 
 
342
        This may update a progress bar, spinner, or similar display.
 
343
        By default it does nothing.
 
344
        """
 
345
        self._progress_view.show_transport_activity(transport,
 
346
            direction, byte_count)
 
347
 
 
348
    def log_transport_activity(self, display=False):
 
349
        """See UIFactory.log_transport_activity()"""
 
350
        log = getattr(self._progress_view, 'log_transport_activity', None)
 
351
        if log is not None:
 
352
            log(display=display)
 
353
 
 
354
    def show_error(self, msg):
 
355
        self.clear_term()
 
356
        self.stderr.write("bzr: error: %s\n" % msg)
 
357
 
 
358
    def show_message(self, msg):
 
359
        self.note(msg)
 
360
 
 
361
    def show_warning(self, msg):
 
362
        self.clear_term()
 
363
        if isinstance(msg, unicode):
 
364
            te = osutils.get_terminal_encoding()
 
365
            msg = msg.encode(te, 'replace')
 
366
        self.stderr.write("bzr: warning: %s\n" % msg)
 
367
 
 
368
    def _progress_updated(self, task):
 
369
        """A task has been updated and wants to be displayed.
 
370
        """
 
371
        if not self._task_stack:
 
372
            warnings.warn("%r updated but no tasks are active" %
 
373
                (task,))
 
374
        elif task != self._task_stack[-1]:
 
375
            # We used to check it was the top task, but it's hard to always
 
376
            # get this right and it's not necessarily useful: any actual
 
377
            # problems will be evident in use
 
378
            #warnings.warn("%r is not the top progress task %r" %
 
379
            #     (task, self._task_stack[-1]))
 
380
            pass
 
381
        self._progress_view.show_progress(task)
 
382
 
 
383
    def _progress_all_finished(self):
 
384
        self._progress_view.clear()
 
385
 
 
386
    def show_user_warning(self, warning_id, **message_args):
 
387
        """Show a text message to the user.
 
388
 
 
389
        Explicitly not for warnings about bzr apis, deprecations or internals.
 
390
        """
 
391
        # eventually trace.warning should migrate here, to avoid logging and
 
392
        # be easier to test; that has a lot of test fallout so for now just
 
393
        # new code can call this
 
394
        if warning_id not in self.suppressed_warnings:
 
395
            self.stderr.write(self.format_user_warning(warning_id, message_args) +
 
396
                '\n')
 
397
 
 
398
 
 
399
class TextProgressView(object):
 
400
    """Display of progress bar and other information on a tty.
 
401
 
 
402
    This shows one line of text, including possibly a network indicator, spinner,
 
403
    progress bar, message, etc.
 
404
 
 
405
    One instance of this is created and held by the UI, and fed updates when a
 
406
    task wants to be painted.
 
407
 
 
408
    Transports feed data to this through the ui_factory object.
 
409
 
 
410
    The Progress views can comprise a tree with _parent_task pointers, but
 
411
    this only prints the stack from the nominated current task up to the root.
 
412
    """
 
413
 
 
414
    def __init__(self, term_file, encoding=None, errors="replace"):
 
415
        self._term_file = term_file
 
416
        if encoding is None:
 
417
            self._encoding = getattr(term_file, "encoding", None) or "ascii"
 
418
        else:
 
419
            self._encoding = encoding
 
420
        self._encoding_errors = errors
 
421
        # true when there's output on the screen we may need to clear
 
422
        self._have_output = False
 
423
        self._last_transport_msg = ''
 
424
        self._spin_pos = 0
 
425
        # time we last repainted the screen
 
426
        self._last_repaint = 0
 
427
        # time we last got information about transport activity
 
428
        self._transport_update_time = 0
 
429
        self._last_task = None
 
430
        self._total_byte_count = 0
 
431
        self._bytes_since_update = 0
 
432
        self._bytes_by_direction = {'unknown': 0, 'read': 0, 'write': 0}
 
433
        self._first_byte_time = None
 
434
        self._fraction = 0
 
435
        # force the progress bar to be off, as at the moment it doesn't 
 
436
        # correspond reliably to overall command progress
 
437
        self.enable_bar = False
 
438
 
 
439
    def _avail_width(self):
 
440
        # we need one extra space for terminals that wrap on last char
 
441
        w = osutils.terminal_width() 
 
442
        if w is None:
 
443
            return None
 
444
        else:
 
445
            return w - 1
 
446
 
 
447
    def _show_line(self, u):
 
448
        s = u.encode(self._encoding, self._encoding_errors)
 
449
        width = self._avail_width()
 
450
        if width is not None:
 
451
            # GZ 2012-03-28: Counting bytes is wrong for calculating width of
 
452
            #                text but better than counting codepoints.
 
453
            s = '%-*.*s' % (width, width, s)
 
454
        self._term_file.write('\r' + s + '\r')
 
455
 
 
456
    def clear(self):
 
457
        if self._have_output:
 
458
            self._show_line('')
 
459
        self._have_output = False
 
460
 
 
461
    def _render_bar(self):
 
462
        # return a string for the progress bar itself
 
463
        if self.enable_bar and (
 
464
            (self._last_task is None) or self._last_task.show_bar):
 
465
            # If there's no task object, we show space for the bar anyhow.
 
466
            # That's because most invocations of bzr will end showing progress
 
467
            # at some point, though perhaps only after doing some initial IO.
 
468
            # It looks better to draw the progress bar initially rather than
 
469
            # to have what looks like an incomplete progress bar.
 
470
            spin_str =  r'/-\|'[self._spin_pos % 4]
 
471
            self._spin_pos += 1
 
472
            cols = 20
 
473
            if self._last_task is None:
 
474
                completion_fraction = 0
 
475
                self._fraction = 0
 
476
            else:
 
477
                completion_fraction = \
 
478
                    self._last_task._overall_completion_fraction() or 0
 
479
            if (completion_fraction < self._fraction and 'progress' in
 
480
                debug.debug_flags):
 
481
                import pdb;pdb.set_trace()
 
482
            self._fraction = completion_fraction
 
483
            markers = int(round(float(cols) * completion_fraction)) - 1
 
484
            bar_str = '[' + ('#' * markers + spin_str).ljust(cols) + '] '
 
485
            return bar_str
 
486
        elif (self._last_task is None) or self._last_task.show_spinner:
 
487
            # The last task wanted just a spinner, no bar
 
488
            spin_str =  r'/-\|'[self._spin_pos % 4]
 
489
            self._spin_pos += 1
 
490
            return spin_str + ' '
 
491
        else:
 
492
            return ''
 
493
 
 
494
    def _format_task(self, task):
 
495
        """Format task-specific parts of progress bar.
 
496
 
 
497
        :returns: (text_part, counter_part) both unicode strings.
 
498
        """
 
499
        if not task.show_count:
 
500
            s = ''
 
501
        elif task.current_cnt is not None and task.total_cnt is not None:
 
502
            s = ' %d/%d' % (task.current_cnt, task.total_cnt)
 
503
        elif task.current_cnt is not None:
 
504
            s = ' %d' % (task.current_cnt)
 
505
        else:
 
506
            s = ''
 
507
        # compose all the parent messages
 
508
        t = task
 
509
        m = task.msg
 
510
        while t._parent_task:
 
511
            t = t._parent_task
 
512
            if t.msg:
 
513
                m = t.msg + ':' + m
 
514
        return m, s
 
515
 
 
516
    def _render_line(self):
 
517
        bar_string = self._render_bar()
 
518
        if self._last_task:
 
519
            task_part, counter_part = self._format_task(self._last_task)
 
520
        else:
 
521
            task_part = counter_part = ''
 
522
        if self._last_task and not self._last_task.show_transport_activity:
 
523
            trans = ''
 
524
        else:
 
525
            trans = self._last_transport_msg
 
526
        # the bar separates the transport activity from the message, so even
 
527
        # if there's no bar or spinner, we must show something if both those
 
528
        # fields are present
 
529
        if (task_part or trans) and not bar_string:
 
530
            bar_string = '| '
 
531
        # preferentially truncate the task message if we don't have enough
 
532
        # space
 
533
        avail_width = self._avail_width()
 
534
        if avail_width is not None:
 
535
            # if terminal avail_width is unknown, don't truncate
 
536
            current_len = len(bar_string) + len(trans) + len(task_part) + len(counter_part)
 
537
            gap = current_len - avail_width
 
538
            if gap > 0:
 
539
                task_part = task_part[:-gap-2] + '..'
 
540
        s = trans + bar_string + task_part + counter_part
 
541
        if avail_width is not None:
 
542
            if len(s) < avail_width:
 
543
                s = s.ljust(avail_width)
 
544
            elif len(s) > avail_width:
 
545
                s = s[:avail_width]
 
546
        return s
 
547
 
 
548
    def _repaint(self):
 
549
        s = self._render_line()
 
550
        self._show_line(s)
 
551
        self._have_output = True
 
552
 
 
553
    def show_progress(self, task):
 
554
        """Called by the task object when it has changed.
 
555
        
 
556
        :param task: The top task object; its parents are also included 
 
557
            by following links.
 
558
        """
 
559
        must_update = task is not self._last_task
 
560
        self._last_task = task
 
561
        now = time.time()
 
562
        if (not must_update) and (now < self._last_repaint + task.update_latency):
 
563
            return
 
564
        if now > self._transport_update_time + 10:
 
565
            # no recent activity; expire it
 
566
            self._last_transport_msg = ''
 
567
        self._last_repaint = now
 
568
        self._repaint()
 
569
 
 
570
    def show_transport_activity(self, transport, direction, byte_count):
 
571
        """Called by transports via the ui_factory, as they do IO.
 
572
 
 
573
        This may update a progress bar, spinner, or similar display.
 
574
        By default it does nothing.
 
575
        """
 
576
        # XXX: there should be a transport activity model, and that too should
 
577
        #      be seen by the progress view, rather than being poked in here.
 
578
        self._total_byte_count += byte_count
 
579
        self._bytes_since_update += byte_count
 
580
        if self._first_byte_time is None:
 
581
            # Note that this isn't great, as technically it should be the time
 
582
            # when the bytes started transferring, not when they completed.
 
583
            # However, we usually start with a small request anyway.
 
584
            self._first_byte_time = time.time()
 
585
        if direction in self._bytes_by_direction:
 
586
            self._bytes_by_direction[direction] += byte_count
 
587
        else:
 
588
            self._bytes_by_direction['unknown'] += byte_count
 
589
        if 'no_activity' in debug.debug_flags:
 
590
            # Can be used as a workaround if
 
591
            # <https://launchpad.net/bugs/321935> reappears and transport
 
592
            # activity is cluttering other output.  However, thanks to
 
593
            # TextUIOutputStream this shouldn't be a problem any more.
 
594
            return
 
595
        now = time.time()
 
596
        if self._total_byte_count < 2000:
 
597
            # a little resistance at first, so it doesn't stay stuck at 0
 
598
            # while connecting...
 
599
            return
 
600
        if self._transport_update_time is None:
 
601
            self._transport_update_time = now
 
602
        elif now >= (self._transport_update_time + 0.5):
 
603
            # guard against clock stepping backwards, and don't update too
 
604
            # often
 
605
            rate = (self._bytes_since_update
 
606
                    / (now - self._transport_update_time))
 
607
            # using base-10 units (see HACKING.txt).
 
608
            msg = ("%6dkB %5dkB/s " %
 
609
                    (self._total_byte_count / 1000, int(rate) / 1000,))
 
610
            self._transport_update_time = now
 
611
            self._last_repaint = now
 
612
            self._bytes_since_update = 0
 
613
            self._last_transport_msg = msg
 
614
            self._repaint()
 
615
 
 
616
    def _format_bytes_by_direction(self):
 
617
        if self._first_byte_time is None:
 
618
            bps = 0.0
 
619
        else:
 
620
            transfer_time = time.time() - self._first_byte_time
 
621
            if transfer_time < 0.001:
 
622
                transfer_time = 0.001
 
623
            bps = self._total_byte_count / transfer_time
 
624
 
 
625
        # using base-10 units (see HACKING.txt).
 
626
        msg = ('Transferred: %.0fkB'
 
627
               ' (%.1fkB/s r:%.0fkB w:%.0fkB'
 
628
               % (self._total_byte_count / 1000.,
 
629
                  bps / 1000.,
 
630
                  self._bytes_by_direction['read'] / 1000.,
 
631
                  self._bytes_by_direction['write'] / 1000.,
 
632
                 ))
 
633
        if self._bytes_by_direction['unknown'] > 0:
 
634
            msg += ' u:%.0fkB)' % (
 
635
                self._bytes_by_direction['unknown'] / 1000.
 
636
                )
 
637
        else:
 
638
            msg += ')'
 
639
        return msg
 
640
 
 
641
    def log_transport_activity(self, display=False):
 
642
        msg = self._format_bytes_by_direction()
 
643
        trace.mutter(msg)
 
644
        if display and self._total_byte_count > 0:
 
645
            self.clear()
 
646
            self._term_file.write(msg + '\n')
 
647
 
 
648
 
 
649
class TextUIOutputStream(object):
 
650
    """Decorates an output stream so that the terminal is cleared before writing.
 
651
 
 
652
    This is supposed to ensure that the progress bar does not conflict with bulk
 
653
    text output.
 
654
    """
 
655
    # XXX: this does not handle the case of writing part of a line, then doing
 
656
    # progress bar output: the progress bar will probably write over it.
 
657
    # one option is just to buffer that text until we have a full line;
 
658
    # another is to save and restore it
 
659
 
 
660
    # XXX: might need to wrap more methods
 
661
 
 
662
    def __init__(self, ui_factory, wrapped_stream):
 
663
        self.ui_factory = ui_factory
 
664
        self.wrapped_stream = wrapped_stream
 
665
        # this does no transcoding, but it must expose the underlying encoding
 
666
        # because some callers need to know what can be written - see for
 
667
        # example unescape_for_display.
 
668
        self.encoding = getattr(wrapped_stream, 'encoding', None)
 
669
 
 
670
    def flush(self):
 
671
        self.ui_factory.clear_term()
 
672
        self.wrapped_stream.flush()
 
673
 
 
674
    def write(self, to_write):
 
675
        self.ui_factory.clear_term()
 
676
        self.wrapped_stream.write(to_write)
 
677
 
 
678
    def writelines(self, lines):
 
679
        self.ui_factory.clear_term()
 
680
        self.wrapped_stream.writelines(lines)