~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
19
"""Text UI, write output to the console.
20
"""
21
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 (
30
    progress,
2294.4.1 by Vincent Ladeuil
Add a UIFactory.get_login method, fix tests.
31
    osutils,
3882.8.8 by Martin Pool
Progress and UI test cleanups
32
    symbol_versioning,
1996.3.27 by John Arbash Meinel
lazy import getpass in bzrlib.ui.text
33
    )
3882.8.8 by Martin Pool
Progress and UI test cleanups
34
1996.3.27 by John Arbash Meinel
lazy import getpass in bzrlib.ui.text
35
""")
36
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
37
from bzrlib.ui import CLIUIFactory
38
39
40
class TextUIFactory(CLIUIFactory):
1681.1.2 by Robert Collins
* bzrlib.ui.text.TextUIFactory now accepts a bar_type parameter which
41
    """A UI factory for Text user interefaces."""
42
1692.3.3 by Robert Collins
Get run_bzr in tests to always assign a new, clean ui factory.
43
    def __init__(self,
44
                 bar_type=None,
3882.8.11 by Martin Pool
Choose the UIFactory class depending on the terminal capabilities
45
                 stdin=None,
1692.3.3 by Robert Collins
Get run_bzr in tests to always assign a new, clean ui factory.
46
                 stdout=None,
47
                 stderr=None):
1681.1.2 by Robert Collins
* bzrlib.ui.text.TextUIFactory now accepts a bar_type parameter which
48
        """Create a TextUIFactory.
49
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
50
        :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
51
                         letting the bzrlib.progress.ProgressBar factory auto
3882.8.3 by Martin Pool
Move display of transport throughput into TextProgressView
52
                         select.   Deprecated.
1681.1.2 by Robert Collins
* bzrlib.ui.text.TextUIFactory now accepts a bar_type parameter which
53
        """
3882.8.11 by Martin Pool
Choose the UIFactory class depending on the terminal capabilities
54
        super(TextUIFactory, self).__init__(stdin=stdin,
55
                stdout=stdout, stderr=stderr)
3882.8.6 by Martin Pool
TextUIFactory ignores and deprecates the bar_type parameter
56
        if bar_type:
57
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 11, 0))
58
                % "bar_type parameter")
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
59
        # paints progress, network activity, etc
4449.2.1 by Martin Pool
TextUIFactory now respects BZR_PROGRESS_BAR again
60
        self._progress_view = self._make_progress_view()
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.2.1 by Martin Pool
TextUIFactory now respects BZR_PROGRESS_BAR again
73
    def _make_progress_view(self):
74
        if os.environ.get('BZR_PROGRESS_BAR') in ('text', None, ''):
75
            return TextProgressView(self.stderr)
76
        else:
77
            return NullProgressView()
78
3882.8.4 by Martin Pool
All UI factories should support note()
79
    def note(self, msg):
80
        """Write an already-formatted message, clearing the progress bar if necessary."""
81
        self.clear_term()
82
        self.stdout.write(msg + '\n')
83
3882.7.5 by Martin Pool
Further mockup of transport-based activity indicator.
84
    def report_transport_activity(self, transport, byte_count, direction):
85
        """Called by transports as they do IO.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
86
3882.7.5 by Martin Pool
Further mockup of transport-based activity indicator.
87
        This may update a progress bar, spinner, or similar display.
88
        By default it does nothing.
89
        """
4449.2.1 by Martin Pool
TextUIFactory now respects BZR_PROGRESS_BAR again
90
        self._progress_view.show_transport_activity(transport,
4110.2.19 by Martin Pool
Transport activity now shows scheme and direction
91
            direction, byte_count)
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
92
3948.2.3 by Martin Pool
Make the interface from ProgressTask to ui more private
93
    def _progress_updated(self, task):
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
94
        """A task has been updated and wants to be displayed.
95
        """
4070.1.1 by Martin Pool
Be more robust about pb updates when none are active
96
        if not self._task_stack:
97
            warnings.warn("%r updated but no tasks are active" %
98
                (task,))
99
        elif task != self._task_stack[-1]:
3948.2.2 by Martin Pool
Corrections to finishing progress bars
100
            warnings.warn("%r is not the top progress task %r" %
101
                (task, self._task_stack[-1]))
3882.7.7 by Martin Pool
Change progress bars to a more MVC style
102
        self._progress_view.show_progress(task)
103
3948.2.5 by Martin Pool
rename to _progress_all_finished
104
    def _progress_all_finished(self):
3948.2.3 by Martin Pool
Make the interface from ProgressTask to ui more private
105
        self._progress_view.clear()
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
106
107
4449.2.1 by Martin Pool
TextUIFactory now respects BZR_PROGRESS_BAR again
108
class NullProgressView(object):
109
    """Soak up and ignore progress information."""
110
111
    def clear(self):
112
        pass
113
114
    def show_progress(self, task):
115
        pass
116
117
    def show_transport_activity(self, transport, direction, byte_count):
118
        pass
119
    
120
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
121
class TextProgressView(object):
122
    """Display of progress bar and other information on a tty.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
123
124
    This shows one line of text, including possibly a network indicator, spinner,
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
125
    progress bar, message, etc.
126
127
    One instance of this is created and held by the UI, and fed updates when a
128
    task wants to be painted.
129
130
    Transports feed data to this through the ui_factory object.
3948.2.2 by Martin Pool
Corrections to finishing progress bars
131
132
    The Progress views can comprise a tree with _parent_task pointers, but
133
    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
134
    """
135
136
    def __init__(self, term_file):
137
        self._term_file = term_file
138
        # true when there's output on the screen we may need to clear
139
        self._have_output = False
140
        # 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
141
        # https://launchpad.net/bugs/316357
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
142
        self._width = osutils.terminal_width()
143
        self._last_transport_msg = ''
144
        self._spin_pos = 0
145
        # time we last repainted the screen
146
        self._last_repaint = 0
147
        # time we last got information about transport activity
148
        self._transport_update_time = 0
149
        self._last_task = None
150
        self._total_byte_count = 0
151
        self._bytes_since_update = 0
152
153
    def _show_line(self, s):
154
        n = self._width - 1
155
        self._term_file.write('\r%-*.*s\r' % (n, n, s))
156
157
    def clear(self):
158
        if self._have_output:
159
            self._show_line('')
160
        self._have_output = False
161
162
    def _render_bar(self):
163
        # return a string for the progress bar itself
4103.3.3 by Martin Pool
Show the progress bar part when showing activity by default
164
        if (self._last_task is None) or self._last_task.show_bar:
165
            # If there's no task object, we show space for the bar anyhow.
166
            # That's because most invocations of bzr will end showing progress
167
            # at some point, though perhaps only after doing some initial IO.
168
            # It looks better to draw the progress bar initially rather than
169
            # to have what looks like an incomplete progress bar.
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
170
            spin_str =  r'/-\|'[self._spin_pos % 4]
171
            self._spin_pos += 1
172
            cols = 20
4110.2.19 by Martin Pool
Transport activity now shows scheme and direction
173
            if self._last_task is None:
174
                completion_fraction = 0
175
            else:
176
                completion_fraction = \
177
                    self._last_task._overall_completion_fraction() or 0
4110.2.15 by Martin Pool
Fix bug in showing task progress and add a test
178
            markers = int(round(float(cols) * completion_fraction)) - 1
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
179
            bar_str = '[' + ('#' * markers + spin_str).ljust(cols) + '] '
180
            return bar_str
4103.3.3 by Martin Pool
Show the progress bar part when showing activity by default
181
        elif self._last_task.show_spinner:
182
            # The last task wanted just a spinner, no bar
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
183
            spin_str =  r'/-\|'[self._spin_pos % 4]
184
            self._spin_pos += 1
185
            return spin_str + ' '
186
        else:
187
            return ''
188
189
    def _format_task(self, task):
190
        if not task.show_count:
191
            s = ''
4017.1.1 by John Arbash Meinel
Get a pb.tick() to work after calling pb.update()
192
        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
193
            s = ' %d/%d' % (task.current_cnt, task.total_cnt)
194
        elif task.current_cnt is not None:
195
            s = ' %d' % (task.current_cnt)
196
        else:
197
            s = ''
198
        # compose all the parent messages
199
        t = task
200
        m = task.msg
201
        while t._parent_task:
202
            t = t._parent_task
203
            if t.msg:
204
                m = t.msg + ':' + m
205
        return m + s
206
4110.2.16 by Martin Pool
Refactor TextProgressView a bit and add another test
207
    def _render_line(self):
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
208
        bar_string = self._render_bar()
209
        if self._last_task:
210
            task_msg = self._format_task(self._last_task)
211
        else:
212
            task_msg = ''
213
        trans = self._last_transport_msg
4110.2.16 by Martin Pool
Refactor TextProgressView a bit and add another test
214
        if trans:
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
215
            trans += ' | '
4110.2.16 by Martin Pool
Refactor TextProgressView a bit and add another test
216
        return (bar_string + trans + task_msg)
217
218
    def _repaint(self):
219
        s = self._render_line()
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
220
        self._show_line(s)
221
        self._have_output = True
222
223
    def show_progress(self, task):
4110.2.15 by Martin Pool
Fix bug in showing task progress and add a test
224
        """Called by the task object when it has changed.
225
        
226
        :param task: The top task object; its parents are also included 
227
            by following links.
228
        """
4110.2.18 by Martin Pool
Progress bars always repaint when task structure is changed
229
        must_update = task is not self._last_task
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
230
        self._last_task = task
231
        now = time.time()
4110.2.18 by Martin Pool
Progress bars always repaint when task structure is changed
232
        if (not must_update) and (now < self._last_repaint + 0.1):
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
233
            return
4110.2.15 by Martin Pool
Fix bug in showing task progress and add a test
234
        if now > self._transport_update_time + 10:
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
235
            # no recent activity; expire it
236
            self._last_transport_msg = ''
237
        self._last_repaint = now
238
        self._repaint()
239
4449.2.1 by Martin Pool
TextUIFactory now respects BZR_PROGRESS_BAR again
240
    def show_transport_activity(self, transport, direction, byte_count):
4110.2.19 by Martin Pool
Transport activity now shows scheme and direction
241
        """Called by transports via the ui_factory, as they do IO.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
242
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
243
        This may update a progress bar, spinner, or similar display.
244
        By default it does nothing.
245
        """
246
        # XXX: Probably there should be a transport activity model, and that
247
        # too should be seen by the progress view, rather than being poked in
248
        # here.
4480.1.1 by Martin Pool
(mbp) only show transport activity when progress is already visible
249
        if not self._have_output:
250
            # As a workaround for <https://launchpad.net/bugs/321935> we only
251
            # show transport activity when there's already a progress bar
252
            # shown, which time the application code is expected to know to
253
            # clear off the progress bar when it's going to send some other
254
            # output.  Eventually it would be nice to have that automatically
255
            # synchronized.
256
            return
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
257
        self._total_byte_count += byte_count
258
        self._bytes_since_update += byte_count
259
        now = time.time()
260
        if self._transport_update_time is None:
261
            self._transport_update_time = now
4043.1.1 by John Arbash Meinel
Increase the debounce time for 'transport activity' to 0.5s
262
        elif now >= (self._transport_update_time + 0.5):
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
263
            # guard against clock stepping backwards, and don't update too
264
            # often
265
            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
266
            msg = ("%6dKB %5dKB/s" %
267
                    (self._total_byte_count>>10, int(rate)>>10,))
3882.8.9 by Martin Pool
Move TextProgressView to ui.text
268
            self._transport_update_time = now
269
            self._last_repaint = now
270
            self._bytes_since_update = 0
271
            self._last_transport_msg = msg
272
            self._repaint()