~bzr-pqm/bzr/bzr.dev

3948.2.2 by Martin Pool
Corrections to finishing progress bars
1
# Copyright (C) 2005, 2008, 2009 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
4566.1.1 by John Arbash Meinel
Fix a fairly critical bug where TextUIFactory.get_non_echoed_password was failing.
21
import getpass
4449.2.1 by Martin Pool
TextUIFactory now respects BZR_PROGRESS_BAR again
22
import os
1996.3.27 by John Arbash Meinel
lazy import getpass in bzrlib.ui.text
23
import sys
3882.7.5 by Martin Pool
Further mockup of transport-based activity indicator.
24
import time
3948.2.2 by Martin Pool
Corrections to finishing progress bars
25
import warnings
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(), """
29
from bzrlib import (
4332.3.18 by Robert Collins
Add -Dprogress to assist in debugging progress bar jumping.
30
    debug,
1996.3.27 by John Arbash Meinel
lazy import getpass in bzrlib.ui.text
31
    progress,
2294.4.1 by Vincent Ladeuil
Add a UIFactory.get_login method, fix tests.
32
    osutils,
3882.8.8 by Martin Pool
Progress and UI test cleanups
33
    symbol_versioning,
1996.3.27 by John Arbash Meinel
lazy import getpass in bzrlib.ui.text
34
    )
3882.8.8 by Martin Pool
Progress and UI test cleanups
35
1996.3.27 by John Arbash Meinel
lazy import getpass in bzrlib.ui.text
36
""")
37
4449.3.15 by Martin Pool
Move NullProgressView and make_progress_view up to UIFactory base class
38
from bzrlib.ui import (
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
39
    UIFactory,
4449.3.15 by Martin Pool
Move NullProgressView and make_progress_view up to UIFactory base class
40
    NullProgressView,
41
    )
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
42
43
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
44
class TextUIFactory(UIFactory):
1681.1.2 by Robert Collins
* bzrlib.ui.text.TextUIFactory now accepts a bar_type parameter which
45
    """A UI factory for Text user interefaces."""
46
1692.3.3 by Robert Collins
Get run_bzr in tests to always assign a new, clean ui factory.
47
    def __init__(self,
3882.8.11 by Martin Pool
Choose the UIFactory class depending on the terminal capabilities
48
                 stdin=None,
1692.3.3 by Robert Collins
Get run_bzr in tests to always assign a new, clean ui factory.
49
                 stdout=None,
50
                 stderr=None):
1681.1.2 by Robert Collins
* bzrlib.ui.text.TextUIFactory now accepts a bar_type parameter which
51
        """Create a TextUIFactory.
52
        """
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
53
        super(TextUIFactory, self).__init__()
4449.3.28 by Martin Pool
todo
54
        # TODO: there's no good reason not to pass all three streams, maybe we
55
        # should deprecate the default values...
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
56
        self.stdin = stdin
57
        self.stdout = stdout
58
        self.stderr = stderr
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
59
        # paints progress, network activity, etc
4449.3.15 by Martin Pool
Move NullProgressView and make_progress_view up to UIFactory base class
60
        self._progress_view = self.make_progress_view()
4449.2.1 by Martin Pool
TextUIFactory now respects BZR_PROGRESS_BAR again
61
        
1558.8.1 by Aaron Bentley
Fix overall progress bar's interaction with 'note' and 'warning'
62
    def clear_term(self):
63
        """Prepare the terminal for output.
64
65
        This will, clear any progress bars, and leave the cursor at the
66
        leftmost position."""
3882.7.6 by Martin Pool
Preliminary support for drawing network io into the progress bar
67
        # XXX: If this is preparing to write to stdout, but that's for example
68
        # directed into a file rather than to the terminal, and the progress
69
        # bar _is_ going to the terminal, we shouldn't need
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
70
        # 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
71
        self._progress_view.clear()
3882.7.5 by Martin Pool
Further mockup of transport-based activity indicator.
72
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
73
    def get_boolean(self, prompt):
74
        while True:
75
            self.prompt(prompt + "? [y/n]: ")
4449.3.37 by Martin Pool
TextUIFactory should cope with EOF when in get_boolean
76
            line = self.stdin.readline().lower()
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
77
            if line in ('y\n', 'yes\n'):
78
                return True
4449.3.37 by Martin Pool
TextUIFactory should cope with EOF when in get_boolean
79
            elif line in ('n\n', 'no\n'):
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
80
                return False
4449.3.37 by Martin Pool
TextUIFactory should cope with EOF when in get_boolean
81
            elif line in ('', None):
82
                # end-of-file; possibly should raise an error here instead
83
                return None
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
84
85
    def get_non_echoed_password(self):
86
        isatty = getattr(self.stdin, 'isatty', None)
87
        if isatty is not None and isatty():
88
            # getpass() ensure the password is not echoed and other
89
            # cross-platform niceties
90
            password = getpass.getpass('')
91
        else:
92
            # echo doesn't make sense without a terminal
93
            password = self.stdin.readline()
94
            if not password:
95
                password = None
96
            elif password[-1] == '\n':
97
                password = password[:-1]
98
        return password
99
100
    def get_password(self, prompt='', **kwargs):
101
        """Prompt the user for a password.
102
103
        :param prompt: The prompt to present the user
104
        :param kwargs: Arguments which will be expanded into the prompt.
105
                       This lets front ends display different things if
106
                       they so choose.
107
        :return: The password string, return None if the user
108
                 canceled the request.
109
        """
110
        prompt += ': '
111
        self.prompt(prompt, **kwargs)
112
        # There's currently no way to say 'i decline to enter a password'
113
        # as opposed to 'my password is empty' -- does it matter?
114
        return self.get_non_echoed_password()
115
116
    def get_username(self, prompt, **kwargs):
117
        """Prompt the user for a username.
118
119
        :param prompt: The prompt to present the user
120
        :param kwargs: Arguments which will be expanded into the prompt.
121
                       This lets front ends display different things if
122
                       they so choose.
123
        :return: The username string, return None if the user
124
                 canceled the request.
125
        """
126
        prompt += ': '
127
        self.prompt(prompt, **kwargs)
128
        username = self.stdin.readline()
129
        if not username:
130
            username = None
131
        elif username[-1] == '\n':
132
            username = username[:-1]
133
        return username
134
4449.3.15 by Martin Pool
Move NullProgressView and make_progress_view up to UIFactory base class
135
    def make_progress_view(self):
136
        """Construct and return a new ProgressView subclass for this UI.
137
        """
138
        # if the user specifically requests either text or no progress bars,
139
        # always do that.  otherwise, guess based on $TERM and tty presence.
140
        if os.environ.get('BZR_PROGRESS_BAR') == 'text':
141
            return TextProgressView(self.stderr)
142
        elif os.environ.get('BZR_PROGRESS_BAR') == 'none':
143
            return NullProgressView()
144
        elif progress._supports_progress(self.stderr):
4449.2.1 by Martin Pool
TextUIFactory now respects BZR_PROGRESS_BAR again
145
            return TextProgressView(self.stderr)
146
        else:
147
            return NullProgressView()
148
3882.8.4 by Martin Pool
All UI factories should support note()
149
    def note(self, msg):
150
        """Write an already-formatted message, clearing the progress bar if necessary."""
151
        self.clear_term()
152
        self.stdout.write(msg + '\n')
153
4449.3.18 by Martin Pool
Fuse CLIUIFactory and TextUIFactory and deprecate the old name
154
    def prompt(self, prompt, **kwargs):
155
        """Emit prompt on the CLI.
156
        
157
        :param kwargs: Dictionary of arguments to insert into the prompt,
158
            to allow UIs to reformat the prompt.
159
        """
160
        if kwargs:
161
            # See <https://launchpad.net/bugs/365891>
162
            prompt = prompt % kwargs
163
        prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
164
        self.clear_term()
165
        self.stderr.write(prompt)
166
3882.7.5 by Martin Pool
Further mockup of transport-based activity indicator.
167
    def report_transport_activity(self, transport, byte_count, direction):
168
        """Called by transports as they do IO.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
169
3882.7.5 by Martin Pool
Further mockup of transport-based activity indicator.
170
        This may update a progress bar, spinner, or similar display.
171
        By default it does nothing.
172
        """
4449.2.1 by Martin Pool
TextUIFactory now respects BZR_PROGRESS_BAR again
173
        self._progress_view.show_transport_activity(transport,
4110.2.19 by Martin Pool
Transport activity now shows scheme and direction
174
            direction, byte_count)
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
175
4711.1.7 by Martin Pool
Add UIFactory.show_error, show_warning, show_message
176
    def show_error(self, msg):
177
        self.clear_term()
178
        self.stderr.write("bzr: error: %s\n" % msg)
179
4711.1.8 by Martin Pool
Add show_warning and show_message tests and implementations
180
    def show_message(self, msg):
181
        self.note(msg)
182
183
    def show_warning(self, msg):
184
        self.clear_term()
185
        self.stderr.write("bzr: warning: %s\n" % msg)
186
3948.2.3 by Martin Pool
Make the interface from ProgressTask to ui more private
187
    def _progress_updated(self, task):
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
188
        """A task has been updated and wants to be displayed.
189
        """
4070.1.1 by Martin Pool
Be more robust about pb updates when none are active
190
        if not self._task_stack:
191
            warnings.warn("%r updated but no tasks are active" %
192
                (task,))
193
        elif task != self._task_stack[-1]:
3948.2.2 by Martin Pool
Corrections to finishing progress bars
194
            warnings.warn("%r is not the top progress task %r" %
195
                (task, self._task_stack[-1]))
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
196
        self._progress_view.show_progress(task)
197
3948.2.5 by Martin Pool
rename to _progress_all_finished
198
    def _progress_all_finished(self):
3948.2.3 by Martin Pool
Make the interface from ProgressTask to ui more private
199
        self._progress_view.clear()
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
200
201
202
class TextProgressView(object):
203
    """Display of progress bar and other information on a tty.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
204
205
    This shows one line of text, including possibly a network indicator, spinner,
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
206
    progress bar, message, etc.
207
208
    One instance of this is created and held by the UI, and fed updates when a
209
    task wants to be painted.
210
211
    Transports feed data to this through the ui_factory object.
3948.2.2 by Martin Pool
Corrections to finishing progress bars
212
213
    The Progress views can comprise a tree with _parent_task pointers, but
214
    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
215
    """
216
217
    def __init__(self, term_file):
218
        self._term_file = term_file
219
        # true when there's output on the screen we may need to clear
220
        self._have_output = False
221
        # XXX: We could listen for SIGWINCH and update the terminal width...
4470.3.1 by Martin Pool
Progress bars no longer show transport scheme or direction
222
        # https://launchpad.net/bugs/316357
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
223
        self._width = osutils.terminal_width()
224
        self._last_transport_msg = ''
225
        self._spin_pos = 0
226
        # time we last repainted the screen
227
        self._last_repaint = 0
228
        # time we last got information about transport activity
229
        self._transport_update_time = 0
230
        self._last_task = None
231
        self._total_byte_count = 0
232
        self._bytes_since_update = 0
4332.3.18 by Robert Collins
Add -Dprogress to assist in debugging progress bar jumping.
233
        self._fraction = 0
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
234
235
    def _show_line(self, s):
4580.3.1 by Martin Pool
ProgressTasks can specify an update latency
236
        # sys.stderr.write("progress %r\n" % s)
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
237
        n = self._width - 1
238
        self._term_file.write('\r%-*.*s\r' % (n, n, s))
239
240
    def clear(self):
241
        if self._have_output:
242
            self._show_line('')
243
        self._have_output = False
244
245
    def _render_bar(self):
246
        # return a string for the progress bar itself
4103.3.3 by Martin Pool
Show the progress bar part when showing activity by default
247
        if (self._last_task is None) or self._last_task.show_bar:
248
            # If there's no task object, we show space for the bar anyhow.
249
            # That's because most invocations of bzr will end showing progress
250
            # at some point, though perhaps only after doing some initial IO.
251
            # It looks better to draw the progress bar initially rather than
252
            # to have what looks like an incomplete progress bar.
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
253
            spin_str =  r'/-\|'[self._spin_pos % 4]
254
            self._spin_pos += 1
255
            cols = 20
4110.2.19 by Martin Pool
Transport activity now shows scheme and direction
256
            if self._last_task is None:
257
                completion_fraction = 0
4332.3.18 by Robert Collins
Add -Dprogress to assist in debugging progress bar jumping.
258
                self._fraction = 0
4110.2.19 by Martin Pool
Transport activity now shows scheme and direction
259
            else:
260
                completion_fraction = \
261
                    self._last_task._overall_completion_fraction() or 0
4332.3.18 by Robert Collins
Add -Dprogress to assist in debugging progress bar jumping.
262
            if (completion_fraction < self._fraction and 'progress' in
263
                debug.debug_flags):
264
                import pdb;pdb.set_trace()
265
            self._fraction = completion_fraction
4110.2.15 by Martin Pool
Fix bug in showing task progress and add a test
266
            markers = int(round(float(cols) * completion_fraction)) - 1
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
267
            bar_str = '[' + ('#' * markers + spin_str).ljust(cols) + '] '
268
            return bar_str
4103.3.3 by Martin Pool
Show the progress bar part when showing activity by default
269
        elif self._last_task.show_spinner:
270
            # The last task wanted just a spinner, no bar
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
271
            spin_str =  r'/-\|'[self._spin_pos % 4]
272
            self._spin_pos += 1
273
            return spin_str + ' '
274
        else:
275
            return ''
276
277
    def _format_task(self, task):
278
        if not task.show_count:
279
            s = ''
4017.1.1 by John Arbash Meinel
Get a pb.tick() to work after calling pb.update()
280
        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
281
            s = ' %d/%d' % (task.current_cnt, task.total_cnt)
282
        elif task.current_cnt is not None:
283
            s = ' %d' % (task.current_cnt)
284
        else:
285
            s = ''
286
        # compose all the parent messages
287
        t = task
288
        m = task.msg
289
        while t._parent_task:
290
            t = t._parent_task
291
            if t.msg:
292
                m = t.msg + ':' + m
293
        return m + s
294
4110.2.16 by Martin Pool
Refactor TextProgressView a bit and add another test
295
    def _render_line(self):
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
296
        bar_string = self._render_bar()
297
        if self._last_task:
298
            task_msg = self._format_task(self._last_task)
299
        else:
300
            task_msg = ''
4580.3.5 by Martin Pool
selftest sets ProgressTask.show_transport_activity off
301
        if self._last_task and not self._last_task.show_transport_activity:
302
            trans = ''
303
        else:
304
            trans = self._last_transport_msg
305
            if trans:
306
                trans += ' | '
4110.2.16 by Martin Pool
Refactor TextProgressView a bit and add another test
307
        return (bar_string + trans + task_msg)
308
309
    def _repaint(self):
310
        s = self._render_line()
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
311
        self._show_line(s)
312
        self._have_output = True
313
314
    def show_progress(self, task):
4110.2.15 by Martin Pool
Fix bug in showing task progress and add a test
315
        """Called by the task object when it has changed.
316
        
317
        :param task: The top task object; its parents are also included 
318
            by following links.
319
        """
4110.2.18 by Martin Pool
Progress bars always repaint when task structure is changed
320
        must_update = task is not self._last_task
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
321
        self._last_task = task
322
        now = time.time()
4580.3.1 by Martin Pool
ProgressTasks can specify an update latency
323
        if (not must_update) and (now < self._last_repaint + task.update_latency):
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
324
            return
4110.2.15 by Martin Pool
Fix bug in showing task progress and add a test
325
        if now > self._transport_update_time + 10:
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
326
            # no recent activity; expire it
327
            self._last_transport_msg = ''
328
        self._last_repaint = now
329
        self._repaint()
330
4449.2.1 by Martin Pool
TextUIFactory now respects BZR_PROGRESS_BAR again
331
    def show_transport_activity(self, transport, direction, byte_count):
4110.2.19 by Martin Pool
Transport activity now shows scheme and direction
332
        """Called by transports via the ui_factory, as they do IO.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
333
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
334
        This may update a progress bar, spinner, or similar display.
335
        By default it does nothing.
336
        """
337
        # XXX: Probably there should be a transport activity model, and that
338
        # too should be seen by the progress view, rather than being poked in
339
        # here.
4480.1.1 by Martin Pool
(mbp) only show transport activity when progress is already visible
340
        if not self._have_output:
341
            # As a workaround for <https://launchpad.net/bugs/321935> we only
342
            # show transport activity when there's already a progress bar
343
            # shown, which time the application code is expected to know to
344
            # clear off the progress bar when it's going to send some other
345
            # output.  Eventually it would be nice to have that automatically
346
            # synchronized.
347
            return
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
348
        self._total_byte_count += byte_count
349
        self._bytes_since_update += byte_count
350
        now = time.time()
4580.3.4 by Martin Pool
Don't show transport activity until 2kB has gone past
351
        if self._total_byte_count < 2000:
352
            # a little resistance at first, so it doesn't stay stuck at 0
353
            # while connecting...
354
            return
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
355
        if self._transport_update_time is None:
356
            self._transport_update_time = now
4043.1.1 by John Arbash Meinel
Increase the debounce time for 'transport activity' to 0.5s
357
        elif now >= (self._transport_update_time + 0.5):
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
358
            # guard against clock stepping backwards, and don't update too
359
            # often
360
            rate = self._bytes_since_update / (now - self._transport_update_time)
4470.3.1 by Martin Pool
Progress bars no longer show transport scheme or direction
361
            msg = ("%6dKB %5dKB/s" %
362
                    (self._total_byte_count>>10, int(rate)>>10,))
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
363
            self._transport_update_time = now
364
            self._last_repaint = now
365
            self._bytes_since_update = 0
366
            self._last_transport_msg = msg
367
            self._repaint()