~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/ui/text.py

  • Committer: Vincent Ladeuil
  • Date: 2009-06-22 12:52:39 UTC
  • mto: (4471.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 4472.
  • Revision ID: v.ladeuil+lp@free.fr-20090622125239-kabo9smxt9c3vnir
Use a consistent scheme for naming pyrex source files.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 Canonical Ltd
 
1
# Copyright (C) 2005, 2008, 2009 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
 
18
18
 
19
19
"""Text UI, write output to the console.
20
20
"""
21
21
 
 
22
import os
22
23
import sys
 
24
import time
 
25
import warnings
23
26
 
24
27
from bzrlib.lazy_import import lazy_import
25
28
lazy_import(globals(), """
26
 
import getpass
27
 
 
28
29
from bzrlib import (
29
30
    progress,
30
31
    osutils,
 
32
    symbol_versioning,
31
33
    )
 
34
 
32
35
""")
33
36
 
34
37
from bzrlib.ui import CLIUIFactory
39
42
 
40
43
    def __init__(self,
41
44
                 bar_type=None,
 
45
                 stdin=None,
42
46
                 stdout=None,
43
47
                 stderr=None):
44
48
        """Create a TextUIFactory.
45
49
 
46
 
        :param bar_type: The type of progress bar to create. It defaults to 
 
50
        :param bar_type: The type of progress bar to create. It defaults to
47
51
                         letting the bzrlib.progress.ProgressBar factory auto
48
 
                         select.
49
 
        """
50
 
        super(TextUIFactory, self).__init__()
51
 
        self._bar_type = bar_type
52
 
        if stdout is None:
53
 
            self.stdout = sys.stdout
54
 
        else:
55
 
            self.stdout = stdout
56
 
        if stderr is None:
57
 
            self.stderr = sys.stderr
58
 
        else:
59
 
            self.stderr = stderr
60
 
 
61
 
    def prompt(self, prompt):
62
 
        """Emit prompt on the CLI."""
63
 
        self.stdout.write(prompt)
64
 
        
65
 
    def nested_progress_bar(self):
66
 
        """Return a nested progress bar.
67
 
        
68
 
        The actual bar type returned depends on the progress module which
69
 
        may return a tty or dots bar depending on the terminal.
70
 
        """
71
 
        if self._progress_bar_stack is None:
72
 
            self._progress_bar_stack = progress.ProgressBarStack(
73
 
                klass=self._bar_type)
74
 
        return self._progress_bar_stack.get_nested()
75
 
 
 
52
                         select.   Deprecated.
 
53
        """
 
54
        super(TextUIFactory, self).__init__(stdin=stdin,
 
55
                stdout=stdout, stderr=stderr)
 
56
        if bar_type:
 
57
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 11, 0))
 
58
                % "bar_type parameter")
 
59
        # paints progress, network activity, etc
 
60
        self._progress_view = self._make_progress_view()
 
61
        
76
62
    def clear_term(self):
77
63
        """Prepare the terminal for output.
78
64
 
79
65
        This will, clear any progress bars, and leave the cursor at the
80
66
        leftmost position."""
81
 
        if self._progress_bar_stack is None:
 
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
 
70
        # to clear it.  We might need to separately check for the case of
 
71
        self._progress_view.clear()
 
72
 
 
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
 
 
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
 
 
84
    def report_transport_activity(self, transport, byte_count, direction):
 
85
        """Called by transports as they do IO.
 
86
 
 
87
        This may update a progress bar, spinner, or similar display.
 
88
        By default it does nothing.
 
89
        """
 
90
        self._progress_view.show_transport_activity(transport,
 
91
            direction, byte_count)
 
92
 
 
93
    def _progress_updated(self, task):
 
94
        """A task has been updated and wants to be displayed.
 
95
        """
 
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]:
 
100
            warnings.warn("%r is not the top progress task %r" %
 
101
                (task, self._task_stack[-1]))
 
102
        self._progress_view.show_progress(task)
 
103
 
 
104
    def _progress_all_finished(self):
 
105
        self._progress_view.clear()
 
106
 
 
107
 
 
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
 
 
121
class TextProgressView(object):
 
122
    """Display of progress bar and other information on a tty.
 
123
 
 
124
    This shows one line of text, including possibly a network indicator, spinner,
 
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.
 
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.
 
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...
 
141
        self._width = osutils.terminal_width()
 
142
        self._last_transport_msg = ''
 
143
        self._spin_pos = 0
 
144
        # time we last repainted the screen
 
145
        self._last_repaint = 0
 
146
        # time we last got information about transport activity
 
147
        self._transport_update_time = 0
 
148
        self._last_task = None
 
149
        self._total_byte_count = 0
 
150
        self._bytes_since_update = 0
 
151
 
 
152
    def _show_line(self, s):
 
153
        n = self._width - 1
 
154
        self._term_file.write('\r%-*.*s\r' % (n, n, s))
 
155
 
 
156
    def clear(self):
 
157
        if self._have_output:
 
158
            self._show_line('')
 
159
        self._have_output = False
 
160
 
 
161
    def _render_bar(self):
 
162
        # return a string for the progress bar itself
 
163
        if (self._last_task is None) or self._last_task.show_bar:
 
164
            # If there's no task object, we show space for the bar anyhow.
 
165
            # That's because most invocations of bzr will end showing progress
 
166
            # at some point, though perhaps only after doing some initial IO.
 
167
            # It looks better to draw the progress bar initially rather than
 
168
            # to have what looks like an incomplete progress bar.
 
169
            spin_str =  r'/-\|'[self._spin_pos % 4]
 
170
            self._spin_pos += 1
 
171
            cols = 20
 
172
            if self._last_task is None:
 
173
                completion_fraction = 0
 
174
            else:
 
175
                completion_fraction = \
 
176
                    self._last_task._overall_completion_fraction() or 0
 
177
            markers = int(round(float(cols) * completion_fraction)) - 1
 
178
            bar_str = '[' + ('#' * markers + spin_str).ljust(cols) + '] '
 
179
            return bar_str
 
180
        elif self._last_task.show_spinner:
 
181
            # The last task wanted just a spinner, no bar
 
182
            spin_str =  r'/-\|'[self._spin_pos % 4]
 
183
            self._spin_pos += 1
 
184
            return spin_str + ' '
 
185
        else:
 
186
            return ''
 
187
 
 
188
    def _format_task(self, task):
 
189
        if not task.show_count:
 
190
            s = ''
 
191
        elif task.current_cnt is not None and task.total_cnt is not None:
 
192
            s = ' %d/%d' % (task.current_cnt, task.total_cnt)
 
193
        elif task.current_cnt is not None:
 
194
            s = ' %d' % (task.current_cnt)
 
195
        else:
 
196
            s = ''
 
197
        # compose all the parent messages
 
198
        t = task
 
199
        m = task.msg
 
200
        while t._parent_task:
 
201
            t = t._parent_task
 
202
            if t.msg:
 
203
                m = t.msg + ':' + m
 
204
        return m + s
 
205
 
 
206
    def _render_line(self):
 
207
        bar_string = self._render_bar()
 
208
        if self._last_task:
 
209
            task_msg = self._format_task(self._last_task)
 
210
        else:
 
211
            task_msg = ''
 
212
        trans = self._last_transport_msg
 
213
        if trans:
 
214
            trans += ' | '
 
215
        return (bar_string + trans + task_msg)
 
216
 
 
217
    def _repaint(self):
 
218
        s = self._render_line()
 
219
        self._show_line(s)
 
220
        self._have_output = True
 
221
 
 
222
    def show_progress(self, task):
 
223
        """Called by the task object when it has changed.
 
224
        
 
225
        :param task: The top task object; its parents are also included 
 
226
            by following links.
 
227
        """
 
228
        must_update = task is not self._last_task
 
229
        self._last_task = task
 
230
        now = time.time()
 
231
        if (not must_update) and (now < self._last_repaint + 0.1):
82
232
            return
83
 
        overall_pb = self._progress_bar_stack.bottom()
84
 
        if overall_pb is not None:
85
 
            overall_pb.clear()
 
233
        if now > self._transport_update_time + 10:
 
234
            # no recent activity; expire it
 
235
            self._last_transport_msg = ''
 
236
        self._last_repaint = now
 
237
        self._repaint()
 
238
 
 
239
    def show_transport_activity(self, transport, direction, byte_count):
 
240
        """Called by transports via the ui_factory, as they do IO.
 
241
 
 
242
        This may update a progress bar, spinner, or similar display.
 
243
        By default it does nothing.
 
244
        """
 
245
        # XXX: Probably there should be a transport activity model, and that
 
246
        # too should be seen by the progress view, rather than being poked in
 
247
        # here.
 
248
        self._total_byte_count += byte_count
 
249
        self._bytes_since_update += byte_count
 
250
        now = time.time()
 
251
        if self._transport_update_time is None:
 
252
            self._transport_update_time = now
 
253
        elif now >= (self._transport_update_time + 0.5):
 
254
            # guard against clock stepping backwards, and don't update too
 
255
            # often
 
256
            rate = self._bytes_since_update / (now - self._transport_update_time)
 
257
            scheme = getattr(transport, '_scheme', None) or repr(transport)
 
258
            if direction == 'read':
 
259
                dir_char = '>'
 
260
            elif direction == 'write':
 
261
                dir_char = '<'
 
262
            else:
 
263
                dir_char = ' '
 
264
            msg = ("%.7s %s %6dKB %5dKB/s" %
 
265
                    (scheme, dir_char, self._total_byte_count>>10, int(rate)>>10,))
 
266
            self._transport_update_time = now
 
267
            self._last_repaint = now
 
268
            self._bytes_since_update = 0
 
269
            self._last_transport_msg = msg
 
270
            self._repaint()
 
271
 
 
272