/brz/remove-bazaar

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