/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/ui/text.py

  • Committer: Martin Pool
  • Date: 2009-12-09 07:58:06 UTC
  • mto: This revision was merged to the branch mainline in revision 4890.
  • Revision ID: mbp@sourcefrog.net-20091209075806-a3nnd8dcnpdfrppn
Text progress view is now only a spinner not a bar.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2008, 2009 Canonical Ltd
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
 
 
18
"""Text UI, write output to the console.
 
19
"""
 
20
 
 
21
import codecs
 
22
import getpass
 
23
import os
 
24
import sys
 
25
import time
 
26
import warnings
 
27
 
 
28
from bzrlib.lazy_import import lazy_import
 
29
lazy_import(globals(), """
 
30
from bzrlib import (
 
31
    debug,
 
32
    progress,
 
33
    osutils,
 
34
    symbol_versioning,
 
35
    )
 
36
 
 
37
""")
 
38
 
 
39
from bzrlib.ui import (
 
40
    UIFactory,
 
41
    NullProgressView,
 
42
    )
 
43
 
 
44
 
 
45
class TextUIFactory(UIFactory):
 
46
    """A UI factory for Text user interefaces."""
 
47
 
 
48
    def __init__(self,
 
49
                 stdin=None,
 
50
                 stdout=None,
 
51
                 stderr=None):
 
52
        """Create a TextUIFactory.
 
53
        """
 
54
        super(TextUIFactory, self).__init__()
 
55
        # TODO: there's no good reason not to pass all three streams, maybe we
 
56
        # should deprecate the default values...
 
57
        self.stdin = stdin
 
58
        self.stdout = stdout
 
59
        self.stderr = stderr
 
60
        # paints progress, network activity, etc
 
61
        self._progress_view = self.make_progress_view()
 
62
        
 
63
    def clear_term(self):
 
64
        """Prepare the terminal for output.
 
65
 
 
66
        This will, clear any progress bars, and leave the cursor at the
 
67
        leftmost position."""
 
68
        # XXX: If this is preparing to write to stdout, but that's for example
 
69
        # directed into a file rather than to the terminal, and the progress
 
70
        # bar _is_ going to the terminal, we shouldn't need
 
71
        # to clear it.  We might need to separately check for the case of
 
72
        self._progress_view.clear()
 
73
 
 
74
    def get_boolean(self, prompt):
 
75
        while True:
 
76
            self.prompt(prompt + "? [y/n]: ")
 
77
            line = self.stdin.readline().lower()
 
78
            if line in ('y\n', 'yes\n'):
 
79
                return True
 
80
            elif line in ('n\n', 'no\n'):
 
81
                return False
 
82
            elif line in ('', None):
 
83
                # end-of-file; possibly should raise an error here instead
 
84
                return None
 
85
 
 
86
    def get_non_echoed_password(self):
 
87
        isatty = getattr(self.stdin, 'isatty', None)
 
88
        if isatty is not None and isatty():
 
89
            # getpass() ensure the password is not echoed and other
 
90
            # cross-platform niceties
 
91
            password = getpass.getpass('')
 
92
        else:
 
93
            # echo doesn't make sense without a terminal
 
94
            password = self.stdin.readline()
 
95
            if not password:
 
96
                password = None
 
97
            elif password[-1] == '\n':
 
98
                password = password[:-1]
 
99
        return password
 
100
 
 
101
    def get_password(self, prompt='', **kwargs):
 
102
        """Prompt the user for a password.
 
103
 
 
104
        :param prompt: The prompt to present the user
 
105
        :param kwargs: Arguments which will be expanded into the prompt.
 
106
                       This lets front ends display different things if
 
107
                       they so choose.
 
108
        :return: The password string, return None if the user
 
109
                 canceled the request.
 
110
        """
 
111
        prompt += ': '
 
112
        self.prompt(prompt, **kwargs)
 
113
        # There's currently no way to say 'i decline to enter a password'
 
114
        # as opposed to 'my password is empty' -- does it matter?
 
115
        return self.get_non_echoed_password()
 
116
 
 
117
    def get_username(self, prompt, **kwargs):
 
118
        """Prompt the user for a username.
 
119
 
 
120
        :param prompt: The prompt to present the user
 
121
        :param kwargs: Arguments which will be expanded into the prompt.
 
122
                       This lets front ends display different things if
 
123
                       they so choose.
 
124
        :return: The username string, return None if the user
 
125
                 canceled the request.
 
126
        """
 
127
        prompt += ': '
 
128
        self.prompt(prompt, **kwargs)
 
129
        username = self.stdin.readline()
 
130
        if not username:
 
131
            username = None
 
132
        elif username[-1] == '\n':
 
133
            username = username[:-1]
 
134
        return username
 
135
 
 
136
    def make_progress_view(self):
 
137
        """Construct and return a new ProgressView subclass for this UI.
 
138
        """
 
139
        # if the user specifically requests either text or no progress bars,
 
140
        # always do that.  otherwise, guess based on $TERM and tty presence.
 
141
        if os.environ.get('BZR_PROGRESS_BAR') == 'text':
 
142
            return TextProgressView(self.stderr)
 
143
        elif os.environ.get('BZR_PROGRESS_BAR') == 'none':
 
144
            return NullProgressView()
 
145
        elif progress._supports_progress(self.stderr):
 
146
            return TextProgressView(self.stderr)
 
147
        else:
 
148
            return NullProgressView()
 
149
 
 
150
    def _make_output_stream_explicit(self, encoding, encoding_type):
 
151
        if encoding_type == 'exact':
 
152
            # force sys.stdout to be binary stream on win32; 
 
153
            # NB: this leaves the file set in that mode; may cause problems if
 
154
            # one process tries to do binary and then text output
 
155
            if sys.platform == 'win32':
 
156
                fileno = getattr(self.stdout, 'fileno', None)
 
157
                if fileno:
 
158
                    import msvcrt
 
159
                    msvcrt.setmode(fileno(), os.O_BINARY)
 
160
            return TextUIOutputStream(self, self.stdout)
 
161
        else:
 
162
            encoded_stdout = codecs.getwriter(encoding)(self.stdout,
 
163
                errors=encoding_type)
 
164
            # For whatever reason codecs.getwriter() does not advertise its encoding
 
165
            # it just returns the encoding of the wrapped file, which is completely
 
166
            # bogus. So set the attribute, so we can find the correct encoding later.
 
167
            encoded_stdout.encoding = encoding
 
168
            return TextUIOutputStream(self, encoded_stdout)
 
169
 
 
170
    def note(self, msg):
 
171
        """Write an already-formatted message, clearing the progress bar if necessary."""
 
172
        self.clear_term()
 
173
        self.stdout.write(msg + '\n')
 
174
 
 
175
    def prompt(self, prompt, **kwargs):
 
176
        """Emit prompt on the CLI.
 
177
        
 
178
        :param kwargs: Dictionary of arguments to insert into the prompt,
 
179
            to allow UIs to reformat the prompt.
 
180
        """
 
181
        if kwargs:
 
182
            # See <https://launchpad.net/bugs/365891>
 
183
            prompt = prompt % kwargs
 
184
        prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
 
185
        self.clear_term()
 
186
        self.stderr.write(prompt)
 
187
 
 
188
    def report_transport_activity(self, transport, byte_count, direction):
 
189
        """Called by transports as they do IO.
 
190
 
 
191
        This may update a progress bar, spinner, or similar display.
 
192
        By default it does nothing.
 
193
        """
 
194
        self._progress_view.show_transport_activity(transport,
 
195
            direction, byte_count)
 
196
 
 
197
    def show_error(self, msg):
 
198
        self.clear_term()
 
199
        self.stderr.write("bzr: error: %s\n" % msg)
 
200
 
 
201
    def show_message(self, msg):
 
202
        self.note(msg)
 
203
 
 
204
    def show_warning(self, msg):
 
205
        self.clear_term()
 
206
        self.stderr.write("bzr: warning: %s\n" % msg)
 
207
 
 
208
    def _progress_updated(self, task):
 
209
        """A task has been updated and wants to be displayed.
 
210
        """
 
211
        if not self._task_stack:
 
212
            warnings.warn("%r updated but no tasks are active" %
 
213
                (task,))
 
214
        elif task != self._task_stack[-1]:
 
215
            warnings.warn("%r is not the top progress task %r" %
 
216
                (task, self._task_stack[-1]))
 
217
        self._progress_view.show_progress(task)
 
218
 
 
219
    def _progress_all_finished(self):
 
220
        self._progress_view.clear()
 
221
 
 
222
 
 
223
class TextProgressView(object):
 
224
    """Display of progress bar and other information on a tty.
 
225
 
 
226
    This shows one line of text, including possibly a network indicator, spinner,
 
227
    progress bar, message, etc.
 
228
 
 
229
    One instance of this is created and held by the UI, and fed updates when a
 
230
    task wants to be painted.
 
231
 
 
232
    Transports feed data to this through the ui_factory object.
 
233
 
 
234
    The Progress views can comprise a tree with _parent_task pointers, but
 
235
    this only prints the stack from the nominated current task up to the root.
 
236
    """
 
237
 
 
238
    def __init__(self, term_file):
 
239
        self._term_file = term_file
 
240
        # true when there's output on the screen we may need to clear
 
241
        self._have_output = False
 
242
        # XXX: We could listen for SIGWINCH and update the terminal width...
 
243
        # https://launchpad.net/bugs/316357
 
244
        self._width = osutils.terminal_width()
 
245
        self._last_transport_msg = ''
 
246
        self._spin_pos = 0
 
247
        # time we last repainted the screen
 
248
        self._last_repaint = 0
 
249
        # time we last got information about transport activity
 
250
        self._transport_update_time = 0
 
251
        self._last_task = None
 
252
        self._total_byte_count = 0
 
253
        self._bytes_since_update = 0
 
254
        self._fraction = 0
 
255
        # force the progress bar to be off, as at the moment it doesn't 
 
256
        # correspond reliably to overall command progress
 
257
        self.enable_bar = False
 
258
 
 
259
    def _show_line(self, s):
 
260
        # sys.stderr.write("progress %r\n" % s)
 
261
        if self._width is not None:
 
262
            n = self._width - 1
 
263
            s = '%-*.*s' % (n, n, s)
 
264
        self._term_file.write('\r' + s + '\r')
 
265
 
 
266
    def clear(self):
 
267
        if self._have_output:
 
268
            self._show_line('')
 
269
        self._have_output = False
 
270
 
 
271
    def _render_bar(self):
 
272
        # return a string for the progress bar itself
 
273
        if self.enable_bar and (
 
274
            (self._last_task is None) or self._last_task.show_bar):
 
275
            # If there's no task object, we show space for the bar anyhow.
 
276
            # That's because most invocations of bzr will end showing progress
 
277
            # at some point, though perhaps only after doing some initial IO.
 
278
            # It looks better to draw the progress bar initially rather than
 
279
            # to have what looks like an incomplete progress bar.
 
280
            spin_str =  r'/-\|'[self._spin_pos % 4]
 
281
            self._spin_pos += 1
 
282
            cols = 20
 
283
            if self._last_task is None:
 
284
                completion_fraction = 0
 
285
                self._fraction = 0
 
286
            else:
 
287
                completion_fraction = \
 
288
                    self._last_task._overall_completion_fraction() or 0
 
289
            if (completion_fraction < self._fraction and 'progress' in
 
290
                debug.debug_flags):
 
291
                import pdb;pdb.set_trace()
 
292
            self._fraction = completion_fraction
 
293
            markers = int(round(float(cols) * completion_fraction)) - 1
 
294
            bar_str = '[' + ('#' * markers + spin_str).ljust(cols) + '] '
 
295
            return bar_str
 
296
        elif self._last_task.show_spinner:
 
297
            # The last task wanted just a spinner, no bar
 
298
            spin_str =  r'/-\|'[self._spin_pos % 4]
 
299
            self._spin_pos += 1
 
300
            return spin_str + ' '
 
301
        else:
 
302
            return ''
 
303
 
 
304
    def _format_task(self, task):
 
305
        if not task.show_count:
 
306
            s = ''
 
307
        elif task.current_cnt is not None and task.total_cnt is not None:
 
308
            s = ' %d/%d' % (task.current_cnt, task.total_cnt)
 
309
        elif task.current_cnt is not None:
 
310
            s = ' %d' % (task.current_cnt)
 
311
        else:
 
312
            s = ''
 
313
        # compose all the parent messages
 
314
        t = task
 
315
        m = task.msg
 
316
        while t._parent_task:
 
317
            t = t._parent_task
 
318
            if t.msg:
 
319
                m = t.msg + ':' + m
 
320
        return m + s
 
321
 
 
322
    def _render_line(self):
 
323
        bar_string = self._render_bar()
 
324
        if self._last_task:
 
325
            task_msg = self._format_task(self._last_task)
 
326
        else:
 
327
            task_msg = ''
 
328
        if self._last_task and not self._last_task.show_transport_activity:
 
329
            trans = ''
 
330
        else:
 
331
            trans = self._last_transport_msg
 
332
            if trans:
 
333
                trans += ' | '
 
334
        return (bar_string + trans + task_msg)
 
335
 
 
336
    def _repaint(self):
 
337
        s = self._render_line()
 
338
        self._show_line(s)
 
339
        self._have_output = True
 
340
 
 
341
    def show_progress(self, task):
 
342
        """Called by the task object when it has changed.
 
343
        
 
344
        :param task: The top task object; its parents are also included 
 
345
            by following links.
 
346
        """
 
347
        must_update = task is not self._last_task
 
348
        self._last_task = task
 
349
        now = time.time()
 
350
        if (not must_update) and (now < self._last_repaint + task.update_latency):
 
351
            return
 
352
        if now > self._transport_update_time + 10:
 
353
            # no recent activity; expire it
 
354
            self._last_transport_msg = ''
 
355
        self._last_repaint = now
 
356
        self._repaint()
 
357
 
 
358
    def show_transport_activity(self, transport, direction, byte_count):
 
359
        """Called by transports via the ui_factory, as they do IO.
 
360
 
 
361
        This may update a progress bar, spinner, or similar display.
 
362
        By default it does nothing.
 
363
        """
 
364
        # XXX: Probably there should be a transport activity model, and that
 
365
        # too should be seen by the progress view, rather than being poked in
 
366
        # here.
 
367
        if not self._have_output:
 
368
            # As a workaround for <https://launchpad.net/bugs/321935> we only
 
369
            # show transport activity when there's already a progress bar
 
370
            # shown, which time the application code is expected to know to
 
371
            # clear off the progress bar when it's going to send some other
 
372
            # output.  Eventually it would be nice to have that automatically
 
373
            # synchronized.
 
374
            return
 
375
        self._total_byte_count += byte_count
 
376
        self._bytes_since_update += byte_count
 
377
        now = time.time()
 
378
        if self._total_byte_count < 2000:
 
379
            # a little resistance at first, so it doesn't stay stuck at 0
 
380
            # while connecting...
 
381
            return
 
382
        if self._transport_update_time is None:
 
383
            self._transport_update_time = now
 
384
        elif now >= (self._transport_update_time + 0.5):
 
385
            # guard against clock stepping backwards, and don't update too
 
386
            # often
 
387
            rate = self._bytes_since_update / (now - self._transport_update_time)
 
388
            msg = ("%6dKB %5dKB/s" %
 
389
                    (self._total_byte_count>>10, int(rate)>>10,))
 
390
            self._transport_update_time = now
 
391
            self._last_repaint = now
 
392
            self._bytes_since_update = 0
 
393
            self._last_transport_msg = msg
 
394
            self._repaint()
 
395
 
 
396
 
 
397
class TextUIOutputStream(object):
 
398
    """Decorates an output stream so that the terminal is cleared before writing.
 
399
 
 
400
    This is supposed to ensure that the progress bar does not conflict with bulk
 
401
    text output.
 
402
    """
 
403
    # XXX: this does not handle the case of writing part of a line, then doing
 
404
    # progress bar output: the progress bar will probably write over it.
 
405
    # one option is just to buffer that text until we have a full line;
 
406
    # another is to save and restore it
 
407
 
 
408
    # XXX: might need to wrap more methods
 
409
 
 
410
    def __init__(self, ui_factory, wrapped_stream):
 
411
        self.ui_factory = ui_factory
 
412
        self.wrapped_stream = wrapped_stream
 
413
        # this does no transcoding, but it must expose the underlying encoding
 
414
        # because some callers need to know what can be written - see for
 
415
        # example unescape_for_display.
 
416
        self.encoding = getattr(wrapped_stream, 'encoding', None)
 
417
 
 
418
    def flush(self):
 
419
        self.ui_factory.clear_term()
 
420
        self.wrapped_stream.flush()
 
421
 
 
422
    def write(self, to_write):
 
423
        self.ui_factory.clear_term()
 
424
        self.wrapped_stream.write(to_write)
 
425
 
 
426
    def writelines(self, lines):
 
427
        self.ui_factory.clear_term()
 
428
        self.wrapped_stream.writelines(lines)