~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/ui/text.py

  • Committer: Martin Pool
  • Date: 2009-08-04 11:40:59 UTC
  • mfrom: (4584 +trunk)
  • mto: This revision was merged to the branch mainline in revision 4586.
  • Revision ID: mbp@sourcefrog.net-20090804114059-xptutagbs5jev3ry
merge trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
 
18
 
 
19
18
"""Text UI, write output to the console.
20
19
"""
21
20
 
 
21
import getpass
22
22
import os
23
23
import sys
24
24
import time
34
34
 
35
35
""")
36
36
 
37
 
from bzrlib.ui import CLIUIFactory
38
 
 
39
 
 
40
 
class TextUIFactory(CLIUIFactory):
 
37
from bzrlib.ui import (
 
38
    UIFactory,
 
39
    NullProgressView,
 
40
    )
 
41
 
 
42
 
 
43
class TextUIFactory(UIFactory):
41
44
    """A UI factory for Text user interefaces."""
42
45
 
43
46
    def __init__(self,
44
 
                 bar_type=None,
45
47
                 stdin=None,
46
48
                 stdout=None,
47
49
                 stderr=None):
50
52
        :param bar_type: The type of progress bar to create.  Deprecated
51
53
            and ignored; a TextProgressView is always used.
52
54
        """
53
 
        super(TextUIFactory, self).__init__(stdin=stdin,
54
 
                stdout=stdout, stderr=stderr)
55
 
        if bar_type:
56
 
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 11, 0))
57
 
                % "bar_type parameter")
 
55
        super(TextUIFactory, self).__init__()
 
56
        # TODO: there's no good reason not to pass all three streams, maybe we
 
57
        # should deprecate the default values...
 
58
        self.stdin = stdin
 
59
        self.stdout = stdout
 
60
        self.stderr = stderr
58
61
        # paints progress, network activity, etc
59
 
        self._progress_view = self._make_progress_view()
 
62
        self._progress_view = self.make_progress_view()
60
63
        
61
64
    def clear_term(self):
62
65
        """Prepare the terminal for output.
69
72
        # to clear it.  We might need to separately check for the case of
70
73
        self._progress_view.clear()
71
74
 
72
 
    def _make_progress_view(self):
73
 
        if os.environ.get('BZR_PROGRESS_BAR') in ('text', None, ''):
 
75
    def get_boolean(self, prompt):
 
76
        while True:
 
77
            self.prompt(prompt + "? [y/n]: ")
 
78
            line = self.stdin.readline().lower()
 
79
            if line in ('y\n', 'yes\n'):
 
80
                return True
 
81
            elif line in ('n\n', 'no\n'):
 
82
                return False
 
83
            elif line in ('', None):
 
84
                # end-of-file; possibly should raise an error here instead
 
85
                return None
 
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
 
 
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):
74
147
            return TextProgressView(self.stderr)
75
148
        else:
76
149
            return NullProgressView()
80
153
        self.clear_term()
81
154
        self.stdout.write(msg + '\n')
82
155
 
 
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
 
83
169
    def report_transport_activity(self, transport, byte_count, direction):
84
170
        """Called by transports as they do IO.
85
171
 
104
190
        self._progress_view.clear()
105
191
 
106
192
 
107
 
class NullProgressView(object):
108
 
    """Soak up and ignore progress information."""
109
 
 
110
 
    def clear(self):
111
 
        pass
112
 
 
113
 
    def show_progress(self, task):
114
 
        pass
115
 
 
116
 
    def show_transport_activity(self, transport, direction, byte_count):
117
 
        pass
118
 
    
119
 
 
120
193
class TextProgressView(object):
121
194
    """Display of progress bar and other information on a tty.
122
195
 
137
210
        # true when there's output on the screen we may need to clear
138
211
        self._have_output = False
139
212
        # XXX: We could listen for SIGWINCH and update the terminal width...
 
213
        # https://launchpad.net/bugs/316357
140
214
        self._width = osutils.terminal_width()
141
215
        self._last_transport_msg = ''
142
216
        self._spin_pos = 0
149
223
        self._bytes_since_update = 0
150
224
 
151
225
    def _show_line(self, s):
 
226
        # sys.stderr.write("progress %r\n" % s)
152
227
        n = self._width - 1
153
228
        self._term_file.write('\r%-*.*s\r' % (n, n, s))
154
229
 
208
283
            task_msg = self._format_task(self._last_task)
209
284
        else:
210
285
            task_msg = ''
211
 
        trans = self._last_transport_msg
212
 
        if trans:
213
 
            trans += ' | '
 
286
        if self._last_task and not self._last_task.show_transport_activity:
 
287
            trans = ''
 
288
        else:
 
289
            trans = self._last_transport_msg
 
290
            if trans:
 
291
                trans += ' | '
214
292
        return (bar_string + trans + task_msg)
215
293
 
216
294
    def _repaint(self):
227
305
        must_update = task is not self._last_task
228
306
        self._last_task = task
229
307
        now = time.time()
230
 
        if (not must_update) and (now < self._last_repaint + 0.1):
 
308
        if (not must_update) and (now < self._last_repaint + task.update_latency):
231
309
            return
232
310
        if now > self._transport_update_time + 10:
233
311
            # no recent activity; expire it
244
322
        # XXX: Probably there should be a transport activity model, and that
245
323
        # too should be seen by the progress view, rather than being poked in
246
324
        # here.
 
325
        if not self._have_output:
 
326
            # As a workaround for <https://launchpad.net/bugs/321935> we only
 
327
            # show transport activity when there's already a progress bar
 
328
            # shown, which time the application code is expected to know to
 
329
            # clear off the progress bar when it's going to send some other
 
330
            # output.  Eventually it would be nice to have that automatically
 
331
            # synchronized.
 
332
            return
247
333
        self._total_byte_count += byte_count
248
334
        self._bytes_since_update += byte_count
249
335
        now = time.time()
 
336
        if self._total_byte_count < 2000:
 
337
            # a little resistance at first, so it doesn't stay stuck at 0
 
338
            # while connecting...
 
339
            return
250
340
        if self._transport_update_time is None:
251
341
            self._transport_update_time = now
252
342
        elif now >= (self._transport_update_time + 0.5):
253
343
            # guard against clock stepping backwards, and don't update too
254
344
            # often
255
345
            rate = self._bytes_since_update / (now - self._transport_update_time)
256
 
            scheme = getattr(transport, '_scheme', None) or repr(transport)
257
 
            if direction == 'read':
258
 
                dir_char = '>'
259
 
            elif direction == 'write':
260
 
                dir_char = '<'
261
 
            else:
262
 
                dir_char = ' '
263
 
            msg = ("%.7s %s %6dKB %5dKB/s" %
264
 
                    (scheme, dir_char, self._total_byte_count>>10, int(rate)>>10,))
 
346
            msg = ("%6dKB %5dKB/s" %
 
347
                    (self._total_byte_count>>10, int(rate)>>10,))
265
348
            self._transport_update_time = now
266
349
            self._last_repaint = now
267
350
            self._bytes_since_update = 0
268
351
            self._last_transport_msg = msg
269
352
            self._repaint()
270
 
 
271