/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5752.3.8 by John Arbash Meinel
Merge bzr.dev 5764 to resolve release-notes (aka NEWS) conflicts
1
# Copyright (C) 2005-2011 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1185.49.21 by John Arbash Meinel
Refactored bzrlib/ui.py into a module with the possibility for multiple ui forms.
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1185.49.21 by John Arbash Meinel
Refactored bzrlib/ui.py into a module with the possibility for multiple ui forms.
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1185.49.21 by John Arbash Meinel
Refactored bzrlib/ui.py into a module with the possibility for multiple ui forms.
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1185.49.21 by John Arbash Meinel
Refactored bzrlib/ui.py into a module with the possibility for multiple ui forms.
16
17
18
"""Text UI, write output to the console.
19
"""
20
6379.6.1 by Jelmer Vernooij
Import absolute_import in a few places.
21
from __future__ import absolute_import
22
4449.2.1 by Martin Pool
TextUIFactory now respects BZR_PROGRESS_BAR again
23
import os
1996.3.27 by John Arbash Meinel
lazy import getpass in bzrlib.ui.text
24
import sys
3882.7.5 by Martin Pool
Further mockup of transport-based activity indicator.
25
import time
1996.3.27 by John Arbash Meinel
lazy import getpass in bzrlib.ui.text
26
27
from bzrlib.lazy_import import lazy_import
28
lazy_import(globals(), """
5753.2.2 by Jelmer Vernooij
Remove some unnecessary imports, clean up lazy imports.
29
import codecs
30
import getpass
31
import warnings
32
1996.3.27 by John Arbash Meinel
lazy import getpass in bzrlib.ui.text
33
from bzrlib import (
6561.2.1 by Vincent Ladeuil
Add a ``progress_bar`` config option.
34
    config,
4332.3.18 by Robert Collins
Add -Dprogress to assist in debugging progress bar jumping.
35
    debug,
1996.3.27 by John Arbash Meinel
lazy import getpass in bzrlib.ui.text
36
    progress,
2294.4.1 by Vincent Ladeuil
Add a UIFactory.get_login method, fix tests.
37
    osutils,
4906.1.1 by John Arbash Meinel
Basic implementation of logging bytes transferred when bzr exits.
38
    trace,
1996.3.27 by John Arbash Meinel
lazy import getpass in bzrlib.ui.text
39
    )
3882.8.8 by Martin Pool
Progress and UI test cleanups
40
1996.3.27 by John Arbash Meinel
lazy import getpass in bzrlib.ui.text
41
""")
42
4449.3.15 by Martin Pool
Move NullProgressView and make_progress_view up to UIFactory base class
43
from bzrlib.ui import (
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
44
    UIFactory,
4449.3.15 by Martin Pool
Move NullProgressView and make_progress_view up to UIFactory base class
45
    NullProgressView,
46
    )
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
47
48
6182.2.28 by Benoît Pierre
Cleanup helper class for TextUIFactory.choose.
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
6561.2.1 by Vincent Ladeuil
Add a ``progress_bar`` config option.
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
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
165
class TextUIFactory(UIFactory):
6561.2.1 by Vincent Ladeuil
Add a ``progress_bar`` config option.
166
    """A UI factory for Text user interfaces."""
1681.1.2 by Robert Collins
* bzrlib.ui.text.TextUIFactory now accepts a bar_type parameter which
167
1692.3.3 by Robert Collins
Get run_bzr in tests to always assign a new, clean ui factory.
168
    def __init__(self,
3882.8.11 by Martin Pool
Choose the UIFactory class depending on the terminal capabilities
169
                 stdin=None,
1692.3.3 by Robert Collins
Get run_bzr in tests to always assign a new, clean ui factory.
170
                 stdout=None,
171
                 stderr=None):
1681.1.2 by Robert Collins
* bzrlib.ui.text.TextUIFactory now accepts a bar_type parameter which
172
        """Create a TextUIFactory.
173
        """
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
174
        super(TextUIFactory, self).__init__()
4449.3.28 by Martin Pool
todo
175
        # TODO: there's no good reason not to pass all three streams, maybe we
176
        # should deprecate the default values...
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
177
        self.stdin = stdin
178
        self.stdout = stdout
179
        self.stderr = stderr
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
180
        # paints progress, network activity, etc
4449.3.15 by Martin Pool
Move NullProgressView and make_progress_view up to UIFactory base class
181
        self._progress_view = self.make_progress_view()
4797.20.2 by
Register SIGWINCH only when creating a TextUIFactory
182
6182.2.13 by Benoît Pierre
Rename ui.confirm to ui.choose.
183
    def choose(self, msg, choices, default=None):
6182.2.11 by Benoît Pierre
Small tweak to TextUIFactory.confirm documentation.
184
        """Prompt the user for a list of alternatives.
6182.2.2 by Benoît Pierre
Implement TextUIFactory.confirm.
185
6182.2.14 by Benoît Pierre
Rework TextUIFactory.choose again to make the code simpler to follow.
186
        Support both line-based and char-based editing.
6182.2.2 by Benoît Pierre
Implement TextUIFactory.confirm.
187
188
        In line-based mode, both the shortcut and full choice name are valid
6182.2.13 by Benoît Pierre
Rename ui.confirm to ui.choose.
189
        answers, e.g. for choose('prompt', '&yes\n&no'): 'y', ' Y ', ' yes',
6182.2.2 by Benoît Pierre
Implement TextUIFactory.confirm.
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
        """
6182.2.14 by Benoît Pierre
Rework TextUIFactory.choose again to make the code simpler to follow.
200
6182.2.28 by Benoît Pierre
Cleanup helper class for TextUIFactory.choose.
201
        choose_ui = _ChooseUI(self, msg, choices, default)
6182.2.14 by Benoît Pierre
Rework TextUIFactory.choose again to make the code simpler to follow.
202
        return choose_ui.interact()
6182.2.2 by Benoît Pierre
Implement TextUIFactory.confirm.
203
4961.1.2 by Martin Pool
quietness-state is now tracked on UIFactory
204
    def be_quiet(self, state):
205
        if state and not self._quiet:
206
            self.clear_term()
207
        UIFactory.be_quiet(self, state)
4961.1.3 by Martin Pool
trace quietness now controls whether the progress bar appears
208
        self._progress_view = self.make_progress_view()
4961.1.2 by Martin Pool
quietness-state is now tracked on UIFactory
209
1558.8.1 by Aaron Bentley
Fix overall progress bar's interaction with 'note' and 'warning'
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."""
3882.7.6 by Martin Pool
Preliminary support for drawing network io into the progress bar
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
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
218
        # to clear it.  We might need to separately check for the case of
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
219
        self._progress_view.clear()
3882.7.5 by Martin Pool
Further mockup of transport-based activity indicator.
220
4597.3.37 by Vincent Ladeuil
Allows ui factories to query users for an integer.
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
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
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
6559.2.1 by Vincent Ladeuil
Makes AuthenticationConfig always return unicode user names and passwords.
241
            else:
242
                password = password.decode(self.stdin.encoding)
243
244
                if password[-1] == '\n':
245
                    password = password[:-1]
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
246
        return password
247
5863.6.1 by Jelmer Vernooij
Require a unicode prompt to be passed into all methods that prompt.
248
    def get_password(self, prompt=u'', **kwargs):
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
249
        """Prompt the user for a password.
250
251
        :param prompt: The prompt to present the user
252
        :param kwargs: Arguments which will be expanded into the prompt.
253
                       This lets front ends display different things if
254
                       they so choose.
255
        :return: The password string, return None if the user
256
                 canceled the request.
257
        """
258
        prompt += ': '
259
        self.prompt(prompt, **kwargs)
260
        # There's currently no way to say 'i decline to enter a password'
261
        # as opposed to 'my password is empty' -- does it matter?
262
        return self.get_non_echoed_password()
263
264
    def get_username(self, prompt, **kwargs):
265
        """Prompt the user for a username.
266
267
        :param prompt: The prompt to present the user
268
        :param kwargs: Arguments which will be expanded into the prompt.
269
                       This lets front ends display different things if
270
                       they so choose.
271
        :return: The username string, return None if the user
272
                 canceled the request.
273
        """
274
        prompt += ': '
275
        self.prompt(prompt, **kwargs)
276
        username = self.stdin.readline()
277
        if not username:
278
            username = None
6559.2.1 by Vincent Ladeuil
Makes AuthenticationConfig always return unicode user names and passwords.
279
        else:
280
            username = username.decode(self.stdin.encoding)
281
            if username[-1] == '\n':
282
                username = username[:-1]
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
283
        return username
284
4449.3.15 by Martin Pool
Move NullProgressView and make_progress_view up to UIFactory base class
285
    def make_progress_view(self):
286
        """Construct and return a new ProgressView subclass for this UI.
287
        """
4961.1.2 by Martin Pool
quietness-state is now tracked on UIFactory
288
        # with --quiet, never any progress view
5243.1.2 by Martin
Point launchpad links in comments at production server rather than edge
289
        # <https://bugs.launchpad.net/bzr/+bug/320035>.  Otherwise if the
4961.1.2 by Martin Pool
quietness-state is now tracked on UIFactory
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()
6561.2.1 by Vincent Ladeuil
Add a ``progress_bar`` config option.
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()
4449.2.1 by Martin Pool
TextUIFactory now respects BZR_PROGRESS_BAR again
302
4792.8.5 by Martin Pool
Support encoding_type=exact for make_output_stream
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)
314
        else:
315
            encoded_stdout = codecs.getwriter(encoding)(self.stdout,
316
                errors=encoding_type)
4792.8.10 by Martin Pool
Put tweaks to codecs.getwriter encoding into the place it's created
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
4792.8.5 by Martin Pool
Support encoding_type=exact for make_output_stream
321
            return TextUIOutputStream(self, encoded_stdout)
4792.8.2 by Martin Pool
New method ui_factory.make_output_stream
322
3882.8.4 by Martin Pool
All UI factories should support note()
323
    def note(self, msg):
324
        """Write an already-formatted message, clearing the progress bar if necessary."""
325
        self.clear_term()
326
        self.stdout.write(msg + '\n')
327
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
328
    def prompt(self, prompt, **kwargs):
329
        """Emit prompt on the CLI.
330
        
331
        :param kwargs: Dictionary of arguments to insert into the prompt,
332
            to allow UIs to reformat the prompt.
333
        """
5863.6.1 by Jelmer Vernooij
Require a unicode prompt to be passed into all methods that prompt.
334
        if type(prompt) != unicode:
335
            raise ValueError("prompt %r not a unicode string" % prompt)
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
336
        if kwargs:
337
            # See <https://launchpad.net/bugs/365891>
338
            prompt = prompt % kwargs
339
        prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
340
        self.clear_term()
6182.2.10 by Benoît Pierre
Flush stdout before prompting in TextUIFactory.
341
        self.stdout.flush()
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
342
        self.stderr.write(prompt)
343
3882.7.5 by Martin Pool
Further mockup of transport-based activity indicator.
344
    def report_transport_activity(self, transport, byte_count, direction):
345
        """Called by transports as they do IO.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
346
3882.7.5 by Martin Pool
Further mockup of transport-based activity indicator.
347
        This may update a progress bar, spinner, or similar display.
348
        By default it does nothing.
349
        """
4449.2.1 by Martin Pool
TextUIFactory now respects BZR_PROGRESS_BAR again
350
        self._progress_view.show_transport_activity(transport,
4110.2.19 by Martin Pool
Transport activity now shows scheme and direction
351
            direction, byte_count)
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
352
4906.1.1 by John Arbash Meinel
Basic implementation of logging bytes transferred when bzr exits.
353
    def log_transport_activity(self, display=False):
354
        """See UIFactory.log_transport_activity()"""
355
        log = getattr(self._progress_view, 'log_transport_activity', None)
356
        if log is not None:
357
            log(display=display)
358
4711.1.7 by Martin Pool
Add UIFactory.show_error, show_warning, show_message
359
    def show_error(self, msg):
360
        self.clear_term()
361
        self.stderr.write("bzr: error: %s\n" % msg)
362
4711.1.8 by Martin Pool
Add show_warning and show_message tests and implementations
363
    def show_message(self, msg):
364
        self.note(msg)
365
366
    def show_warning(self, msg):
367
        self.clear_term()
5167.1.1 by Parth Malwankar
commit command can now accept message (-m) same as a unicode filename
368
        if isinstance(msg, unicode):
369
            te = osutils.get_terminal_encoding()
5167.1.4 by Parth Malwankar
show_warning now uses 'replace' option for encoding the message.
370
            msg = msg.encode(te, 'replace')
4711.1.8 by Martin Pool
Add show_warning and show_message tests and implementations
371
        self.stderr.write("bzr: warning: %s\n" % msg)
372
3948.2.3 by Martin Pool
Make the interface from ProgressTask to ui more private
373
    def _progress_updated(self, task):
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
374
        """A task has been updated and wants to be displayed.
375
        """
4070.1.1 by Martin Pool
Be more robust about pb updates when none are active
376
        if not self._task_stack:
377
            warnings.warn("%r updated but no tasks are active" %
378
                (task,))
379
        elif task != self._task_stack[-1]:
4961.2.19 by Martin Pool
Suppress un-helpful warning about progress task ordering
380
            # We used to check it was the top task, but it's hard to always
381
            # get this right and it's not necessarily useful: any actual
382
            # problems will be evident in use
383
            #warnings.warn("%r is not the top progress task %r" %
384
            #     (task, self._task_stack[-1]))
385
            pass
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
386
        self._progress_view.show_progress(task)
387
3948.2.5 by Martin Pool
rename to _progress_all_finished
388
    def _progress_all_finished(self):
3948.2.3 by Martin Pool
Make the interface from ProgressTask to ui more private
389
        self._progress_view.clear()
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
390
4634.144.8 by Martin Pool
Generalize to ui_factory.show_user_warning
391
    def show_user_warning(self, warning_id, **message_args):
4634.144.5 by Martin Pool
Cleaner presentation and tests for warn_cross_format_fetch
392
        """Show a text message to the user.
393
394
        Explicitly not for warnings about bzr apis, deprecations or internals.
395
        """
396
        # eventually trace.warning should migrate here, to avoid logging and
397
        # be easier to test; that has a lot of test fallout so for now just
398
        # new code can call this
4634.144.11 by Martin Pool
Rename squelched to suppressed
399
        if warning_id not in self.suppressed_warnings:
4634.144.9 by Martin Pool
Suppress user warnings about cross-format fetch during upgrade
400
            self.stderr.write(self.format_user_warning(warning_id, message_args) +
401
                '\n')
4634.144.5 by Martin Pool
Cleaner presentation and tests for warn_cross_format_fetch
402
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
403
404
class TextProgressView(object):
405
    """Display of progress bar and other information on a tty.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
406
407
    This shows one line of text, including possibly a network indicator, spinner,
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
408
    progress bar, message, etc.
409
410
    One instance of this is created and held by the UI, and fed updates when a
411
    task wants to be painted.
412
413
    Transports feed data to this through the ui_factory object.
3948.2.2 by Martin Pool
Corrections to finishing progress bars
414
415
    The Progress views can comprise a tree with _parent_task pointers, but
416
    this only prints the stack from the nominated current task up to the root.
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
417
    """
418
6437.57.3 by Martin Packman
Make TextProgressView somewhat aware of encodings
419
    def __init__(self, term_file, encoding=None, errors="replace"):
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
420
        self._term_file = term_file
6437.57.3 by Martin Packman
Make TextProgressView somewhat aware of encodings
421
        if encoding is None:
6437.57.7 by Martin Packman
Correct and test fallback to ascii logic when a stream has no encoding
422
            self._encoding = getattr(term_file, "encoding", None) or "ascii"
6437.57.3 by Martin Packman
Make TextProgressView somewhat aware of encodings
423
        else:
424
            self._encoding = encoding
425
        self._encoding_errors = errors
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
426
        # true when there's output on the screen we may need to clear
427
        self._have_output = False
428
        self._last_transport_msg = ''
429
        self._spin_pos = 0
430
        # time we last repainted the screen
431
        self._last_repaint = 0
432
        # time we last got information about transport activity
433
        self._transport_update_time = 0
434
        self._last_task = None
435
        self._total_byte_count = 0
436
        self._bytes_since_update = 0
4906.1.4 by John Arbash Meinel
Play around with the ui display a bit more.
437
        self._bytes_by_direction = {'unknown': 0, 'read': 0, 'write': 0}
4906.1.5 by John Arbash Meinel
Include the KiB/s for the transfer.
438
        self._first_byte_time = None
4332.3.18 by Robert Collins
Add -Dprogress to assist in debugging progress bar jumping.
439
        self._fraction = 0
4880.2.1 by Martin Pool
Text progress view is now only a spinner not a bar.
440
        # force the progress bar to be off, as at the moment it doesn't 
441
        # correspond reliably to overall command progress
442
        self.enable_bar = False
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
443
5339.2.1 by Martin Pool
Progress bars should truncate text rather than counters so as not to give a misleading result
444
    def _avail_width(self):
445
        # we need one extra space for terminals that wrap on last char
446
        w = osutils.terminal_width() 
447
        if w is None:
5050.16.1 by Martin Pool
Clear off progress bars by painting spaces.
448
            return None
5339.2.1 by Martin Pool
Progress bars should truncate text rather than counters so as not to give a misleading result
449
        else:
450
            return w - 1
451
6437.57.3 by Martin Packman
Make TextProgressView somewhat aware of encodings
452
    def _show_line(self, u):
453
        s = u.encode(self._encoding, self._encoding_errors)
5050.16.1 by Martin Pool
Clear off progress bars by painting spaces.
454
        width = self._avail_width()
455
        if width is not None:
6437.57.3 by Martin Packman
Make TextProgressView somewhat aware of encodings
456
            # GZ 2012-03-28: Counting bytes is wrong for calculating width of
457
            #                text but better than counting codepoints.
5050.16.1 by Martin Pool
Clear off progress bars by painting spaces.
458
            s = '%-*.*s' % (width, width, s)
4747.3.6 by Vincent Ladeuil
terminal_width can now returns None.
459
        self._term_file.write('\r' + s + '\r')
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
460
461
    def clear(self):
462
        if self._have_output:
463
            self._show_line('')
464
        self._have_output = False
465
466
    def _render_bar(self):
467
        # return a string for the progress bar itself
4880.2.1 by Martin Pool
Text progress view is now only a spinner not a bar.
468
        if self.enable_bar and (
469
            (self._last_task is None) or self._last_task.show_bar):
4103.3.3 by Martin Pool
Show the progress bar part when showing activity by default
470
            # If there's no task object, we show space for the bar anyhow.
471
            # That's because most invocations of bzr will end showing progress
472
            # at some point, though perhaps only after doing some initial IO.
473
            # It looks better to draw the progress bar initially rather than
474
            # to have what looks like an incomplete progress bar.
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
475
            spin_str =  r'/-\|'[self._spin_pos % 4]
476
            self._spin_pos += 1
477
            cols = 20
4110.2.19 by Martin Pool
Transport activity now shows scheme and direction
478
            if self._last_task is None:
479
                completion_fraction = 0
4332.3.18 by Robert Collins
Add -Dprogress to assist in debugging progress bar jumping.
480
                self._fraction = 0
4110.2.19 by Martin Pool
Transport activity now shows scheme and direction
481
            else:
482
                completion_fraction = \
483
                    self._last_task._overall_completion_fraction() or 0
4332.3.18 by Robert Collins
Add -Dprogress to assist in debugging progress bar jumping.
484
            if (completion_fraction < self._fraction and 'progress' in
485
                debug.debug_flags):
486
                import pdb;pdb.set_trace()
487
            self._fraction = completion_fraction
4110.2.15 by Martin Pool
Fix bug in showing task progress and add a test
488
            markers = int(round(float(cols) * completion_fraction)) - 1
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
489
            bar_str = '[' + ('#' * markers + spin_str).ljust(cols) + '] '
490
            return bar_str
4912.1.1 by Martin Pool
Transport activity indicator is now shown even if there's no pb
491
        elif (self._last_task is None) or self._last_task.show_spinner:
4103.3.3 by Martin Pool
Show the progress bar part when showing activity by default
492
            # The last task wanted just a spinner, no bar
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
493
            spin_str =  r'/-\|'[self._spin_pos % 4]
494
            self._spin_pos += 1
495
            return spin_str + ' '
496
        else:
497
            return ''
498
499
    def _format_task(self, task):
5339.2.1 by Martin Pool
Progress bars should truncate text rather than counters so as not to give a misleading result
500
        """Format task-specific parts of progress bar.
501
502
        :returns: (text_part, counter_part) both unicode strings.
503
        """
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
504
        if not task.show_count:
505
            s = ''
4017.1.1 by John Arbash Meinel
Get a pb.tick() to work after calling pb.update()
506
        elif task.current_cnt is not None and task.total_cnt is not None:
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
507
            s = ' %d/%d' % (task.current_cnt, task.total_cnt)
508
        elif task.current_cnt is not None:
509
            s = ' %d' % (task.current_cnt)
510
        else:
511
            s = ''
512
        # compose all the parent messages
513
        t = task
514
        m = task.msg
515
        while t._parent_task:
516
            t = t._parent_task
517
            if t.msg:
518
                m = t.msg + ':' + m
5339.2.1 by Martin Pool
Progress bars should truncate text rather than counters so as not to give a misleading result
519
        return m, s
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
520
4110.2.16 by Martin Pool
Refactor TextProgressView a bit and add another test
521
    def _render_line(self):
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
522
        bar_string = self._render_bar()
523
        if self._last_task:
5339.2.1 by Martin Pool
Progress bars should truncate text rather than counters so as not to give a misleading result
524
            task_part, counter_part = self._format_task(self._last_task)
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
525
        else:
5339.2.1 by Martin Pool
Progress bars should truncate text rather than counters so as not to give a misleading result
526
            task_part = counter_part = ''
4580.3.5 by Martin Pool
selftest sets ProgressTask.show_transport_activity off
527
        if self._last_task and not self._last_task.show_transport_activity:
528
            trans = ''
529
        else:
530
            trans = self._last_transport_msg
5339.2.3 by Martin Pool
Show the progress spinner between the transport rate and the message.
531
        # the bar separates the transport activity from the message, so even
532
        # if there's no bar or spinner, we must show something if both those
533
        # fields are present
534
        if (task_part or trans) and not bar_string:
535
            bar_string = '| '
5339.2.1 by Martin Pool
Progress bars should truncate text rather than counters so as not to give a misleading result
536
        # preferentially truncate the task message if we don't have enough
537
        # space
5339.2.3 by Martin Pool
Show the progress spinner between the transport rate and the message.
538
        avail_width = self._avail_width()
539
        if avail_width is not None:
540
            # if terminal avail_width is unknown, don't truncate
5339.2.1 by Martin Pool
Progress bars should truncate text rather than counters so as not to give a misleading result
541
            current_len = len(bar_string) + len(trans) + len(task_part) + len(counter_part)
5339.2.3 by Martin Pool
Show the progress spinner between the transport rate and the message.
542
            gap = current_len - avail_width
5339.2.1 by Martin Pool
Progress bars should truncate text rather than counters so as not to give a misleading result
543
            if gap > 0:
544
                task_part = task_part[:-gap-2] + '..'
5339.2.3 by Martin Pool
Show the progress spinner between the transport rate and the message.
545
        s = trans + bar_string + task_part + counter_part
546
        if avail_width is not None:
547
            if len(s) < avail_width:
548
                s = s.ljust(avail_width)
549
            elif len(s) > avail_width:
550
                s = s[:avail_width]
551
        return s
4110.2.16 by Martin Pool
Refactor TextProgressView a bit and add another test
552
553
    def _repaint(self):
554
        s = self._render_line()
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
555
        self._show_line(s)
556
        self._have_output = True
557
558
    def show_progress(self, task):
4110.2.15 by Martin Pool
Fix bug in showing task progress and add a test
559
        """Called by the task object when it has changed.
560
        
561
        :param task: The top task object; its parents are also included 
562
            by following links.
563
        """
4110.2.18 by Martin Pool
Progress bars always repaint when task structure is changed
564
        must_update = task is not self._last_task
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
565
        self._last_task = task
566
        now = time.time()
4580.3.1 by Martin Pool
ProgressTasks can specify an update latency
567
        if (not must_update) and (now < self._last_repaint + task.update_latency):
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
568
            return
4110.2.15 by Martin Pool
Fix bug in showing task progress and add a test
569
        if now > self._transport_update_time + 10:
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
570
            # no recent activity; expire it
571
            self._last_transport_msg = ''
572
        self._last_repaint = now
573
        self._repaint()
574
4449.2.1 by Martin Pool
TextUIFactory now respects BZR_PROGRESS_BAR again
575
    def show_transport_activity(self, transport, direction, byte_count):
4110.2.19 by Martin Pool
Transport activity now shows scheme and direction
576
        """Called by transports via the ui_factory, as they do IO.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
577
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
578
        This may update a progress bar, spinner, or similar display.
579
        By default it does nothing.
580
        """
4906.1.8 by John Arbash Meinel
Merge bzr.dev, resolve conflicts.
581
        # XXX: there should be a transport activity model, and that too should
582
        #      be seen by the progress view, rather than being poked in here.
4906.1.2 by John Arbash Meinel
Get the basic interface tested.
583
        self._total_byte_count += byte_count
584
        self._bytes_since_update += byte_count
4906.1.5 by John Arbash Meinel
Include the KiB/s for the transfer.
585
        if self._first_byte_time is None:
586
            # Note that this isn't great, as technically it should be the time
587
            # when the bytes started transferring, not when they completed.
588
            # However, we usually start with a small request anyway.
589
            self._first_byte_time = time.time()
4906.1.4 by John Arbash Meinel
Play around with the ui display a bit more.
590
        if direction in self._bytes_by_direction:
591
            self._bytes_by_direction[direction] += byte_count
592
        else:
593
            self._bytes_by_direction['unknown'] += byte_count
4912.1.4 by Martin Pool
Rename to -Dno_activity; incidentally fixes ReST syntax error
594
        if 'no_activity' in debug.debug_flags:
4912.1.1 by Martin Pool
Transport activity indicator is now shown even if there's no pb
595
            # Can be used as a workaround if
596
            # <https://launchpad.net/bugs/321935> reappears and transport
597
            # activity is cluttering other output.  However, thanks to
598
            # TextUIOutputStream this shouldn't be a problem any more.
4480.1.1 by Martin Pool
(mbp) only show transport activity when progress is already visible
599
            return
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
600
        now = time.time()
4912.1.3 by Martin Pool
Revert: don't show transport activity til some data has been sent.
601
        if self._total_byte_count < 2000:
602
            # a little resistance at first, so it doesn't stay stuck at 0
603
            # while connecting...
604
            return
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
605
        if self._transport_update_time is None:
606
            self._transport_update_time = now
4043.1.1 by John Arbash Meinel
Increase the debounce time for 'transport activity' to 0.5s
607
        elif now >= (self._transport_update_time + 0.5):
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
608
            # guard against clock stepping backwards, and don't update too
609
            # often
4989.1.6 by Vincent Ladeuil
Add comments and update HACKING.txt about which units should be used.
610
            rate = (self._bytes_since_update
611
                    / (now - self._transport_update_time))
612
            # using base-10 units (see HACKING.txt).
5339.2.3 by Martin Pool
Show the progress spinner between the transport rate and the message.
613
            msg = ("%6dkB %5dkB/s " %
4989.1.1 by Gordon Tyler
Changed show_transport_activity and log_transport_activity to use base-10 SI units.
614
                    (self._total_byte_count / 1000, int(rate) / 1000,))
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
615
            self._transport_update_time = now
616
            self._last_repaint = now
617
            self._bytes_since_update = 0
618
            self._last_transport_msg = msg
619
            self._repaint()
4792.8.1 by Martin Pool
Add TextUIOutputStream coordinated with progress view
620
4906.1.4 by John Arbash Meinel
Play around with the ui display a bit more.
621
    def _format_bytes_by_direction(self):
4906.1.5 by John Arbash Meinel
Include the KiB/s for the transfer.
622
        if self._first_byte_time is None:
623
            bps = 0.0
624
        else:
625
            transfer_time = time.time() - self._first_byte_time
626
            if transfer_time < 0.001:
627
                transfer_time = 0.001
628
            bps = self._total_byte_count / transfer_time
629
4989.1.6 by Vincent Ladeuil
Add comments and update HACKING.txt about which units should be used.
630
        # using base-10 units (see HACKING.txt).
4989.1.1 by Gordon Tyler
Changed show_transport_activity and log_transport_activity to use base-10 SI units.
631
        msg = ('Transferred: %.0fkB'
632
               ' (%.1fkB/s r:%.0fkB w:%.0fkB'
633
               % (self._total_byte_count / 1000.,
634
                  bps / 1000.,
635
                  self._bytes_by_direction['read'] / 1000.,
636
                  self._bytes_by_direction['write'] / 1000.,
4906.1.4 by John Arbash Meinel
Play around with the ui display a bit more.
637
                 ))
638
        if self._bytes_by_direction['unknown'] > 0:
4989.1.1 by Gordon Tyler
Changed show_transport_activity and log_transport_activity to use base-10 SI units.
639
            msg += ' u:%.0fkB)' % (
640
                self._bytes_by_direction['unknown'] / 1000.
4906.1.4 by John Arbash Meinel
Play around with the ui display a bit more.
641
                )
642
        else:
643
            msg += ')'
644
        return msg
645
4906.1.1 by John Arbash Meinel
Basic implementation of logging bytes transferred when bzr exits.
646
    def log_transport_activity(self, display=False):
4906.1.4 by John Arbash Meinel
Play around with the ui display a bit more.
647
        msg = self._format_bytes_by_direction()
648
        trace.mutter(msg)
4906.1.7 by John Arbash Meinel
Switch to KiB/K for each value. Don't display if there are no bytes.
649
        if display and self._total_byte_count > 0:
4906.1.3 by John Arbash Meinel
Use clear() so that we clear a progress bar, but don't introduce a newline.
650
            self.clear()
4906.1.4 by John Arbash Meinel
Play around with the ui display a bit more.
651
            self._term_file.write(msg + '\n')
4906.1.1 by John Arbash Meinel
Basic implementation of logging bytes transferred when bzr exits.
652
4792.8.1 by Martin Pool
Add TextUIOutputStream coordinated with progress view
653
654
class TextUIOutputStream(object):
655
    """Decorates an output stream so that the terminal is cleared before writing.
656
657
    This is supposed to ensure that the progress bar does not conflict with bulk
658
    text output.
659
    """
660
    # XXX: this does not handle the case of writing part of a line, then doing
661
    # progress bar output: the progress bar will probably write over it.
662
    # one option is just to buffer that text until we have a full line;
663
    # another is to save and restore it
664
665
    # XXX: might need to wrap more methods
666
667
    def __init__(self, ui_factory, wrapped_stream):
668
        self.ui_factory = ui_factory
669
        self.wrapped_stream = wrapped_stream
4792.8.13 by Martin Pool
TextUIOutputStream must have an .encoding
670
        # this does no transcoding, but it must expose the underlying encoding
671
        # because some callers need to know what can be written - see for
672
        # example unescape_for_display.
4792.8.15 by Martin Pool
TextUIOutputStream can cope if the wrapped stream doesn't have a .encoding
673
        self.encoding = getattr(wrapped_stream, 'encoding', None)
4792.8.1 by Martin Pool
Add TextUIOutputStream coordinated with progress view
674
4792.8.7 by Martin Pool
Add TextUIOutputStream.flush
675
    def flush(self):
676
        self.ui_factory.clear_term()
677
        self.wrapped_stream.flush()
678
4792.8.1 by Martin Pool
Add TextUIOutputStream coordinated with progress view
679
    def write(self, to_write):
680
        self.ui_factory.clear_term()
681
        self.wrapped_stream.write(to_write)
4792.8.3 by Martin Pool
Add TextUIOutputStream.writelines
682
683
    def writelines(self, lines):
684
        self.ui_factory.clear_term()
685
        self.wrapped_stream.writelines(lines)