~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/ui/text.py

  • Committer: Martin Pool
  • Date: 2009-07-27 06:28:35 UTC
  • mto: This revision was merged to the branch mainline in revision 4587.
  • Revision ID: mbp@sourcefrog.net-20090727062835-o66p8it658tq1sma
Add CountedLock.get_physical_lock_status

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
16
 
 
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
16
 
18
17
 
19
18
"""Text UI, write output to the console.
20
19
"""
21
20
 
 
21
import getpass
 
22
import os
22
23
import sys
23
24
import time
24
25
import warnings
25
26
 
26
27
from bzrlib.lazy_import import lazy_import
27
28
lazy_import(globals(), """
28
 
import getpass
29
 
 
30
29
from bzrlib import (
31
30
    progress,
32
31
    osutils,
35
34
 
36
35
""")
37
36
 
38
 
from bzrlib.ui import CLIUIFactory
39
 
 
40
 
 
41
 
class TextUIFactory(CLIUIFactory):
 
37
from bzrlib.ui import (
 
38
    UIFactory,
 
39
    NullProgressView,
 
40
    )
 
41
 
 
42
 
 
43
class TextUIFactory(UIFactory):
42
44
    """A UI factory for Text user interefaces."""
43
45
 
44
46
    def __init__(self,
45
 
                 bar_type=None,
46
47
                 stdin=None,
47
48
                 stdout=None,
48
49
                 stderr=None):
49
50
        """Create a TextUIFactory.
50
51
 
51
 
        :param bar_type: The type of progress bar to create. It defaults to 
 
52
        :param bar_type: The type of progress bar to create. It defaults to
52
53
                         letting the bzrlib.progress.ProgressBar factory auto
53
54
                         select.   Deprecated.
54
55
        """
55
 
        super(TextUIFactory, self).__init__(stdin=stdin,
56
 
                stdout=stdout, stderr=stderr)
57
 
        if bar_type:
58
 
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 11, 0))
59
 
                % "bar_type parameter")
 
56
        super(TextUIFactory, self).__init__()
 
57
        # TODO: there's no good reason not to pass all three streams, maybe we
 
58
        # should deprecate the default values...
 
59
        self.stdin = stdin
 
60
        self.stdout = stdout
 
61
        self.stderr = stderr
60
62
        # paints progress, network activity, etc
61
 
        self._progress_view = TextProgressView(self.stderr)
62
 
 
63
 
    def prompt(self, prompt):
64
 
        """Emit prompt on the CLI."""
65
 
        self.stdout.write(prompt)
 
63
        self._progress_view = self.make_progress_view()
66
64
        
67
65
    def clear_term(self):
68
66
        """Prepare the terminal for output.
72
70
        # XXX: If this is preparing to write to stdout, but that's for example
73
71
        # directed into a file rather than to the terminal, and the progress
74
72
        # bar _is_ going to the terminal, we shouldn't need
75
 
        # to clear it.  We might need to separately check for the case of 
 
73
        # to clear it.  We might need to separately check for the case of
76
74
        self._progress_view.clear()
77
75
 
 
76
    def get_boolean(self, prompt):
 
77
        while True:
 
78
            self.prompt(prompt + "? [y/n]: ")
 
79
            line = self.stdin.readline().lower()
 
80
            if line in ('y\n', 'yes\n'):
 
81
                return True
 
82
            elif line in ('n\n', 'no\n'):
 
83
                return False
 
84
            elif line in ('', None):
 
85
                # end-of-file; possibly should raise an error here instead
 
86
                return None
 
87
 
 
88
    def get_non_echoed_password(self):
 
89
        isatty = getattr(self.stdin, 'isatty', None)
 
90
        if isatty is not None and isatty():
 
91
            # getpass() ensure the password is not echoed and other
 
92
            # cross-platform niceties
 
93
            password = getpass.getpass('')
 
94
        else:
 
95
            # echo doesn't make sense without a terminal
 
96
            password = self.stdin.readline()
 
97
            if not password:
 
98
                password = None
 
99
            elif password[-1] == '\n':
 
100
                password = password[:-1]
 
101
        return password
 
102
 
 
103
    def get_password(self, prompt='', **kwargs):
 
104
        """Prompt the user for a password.
 
105
 
 
106
        :param prompt: The prompt to present the user
 
107
        :param kwargs: Arguments which will be expanded into the prompt.
 
108
                       This lets front ends display different things if
 
109
                       they so choose.
 
110
        :return: The password string, return None if the user
 
111
                 canceled the request.
 
112
        """
 
113
        prompt += ': '
 
114
        self.prompt(prompt, **kwargs)
 
115
        # There's currently no way to say 'i decline to enter a password'
 
116
        # as opposed to 'my password is empty' -- does it matter?
 
117
        return self.get_non_echoed_password()
 
118
 
 
119
    def get_username(self, prompt, **kwargs):
 
120
        """Prompt the user for a username.
 
121
 
 
122
        :param prompt: The prompt to present the user
 
123
        :param kwargs: Arguments which will be expanded into the prompt.
 
124
                       This lets front ends display different things if
 
125
                       they so choose.
 
126
        :return: The username string, return None if the user
 
127
                 canceled the request.
 
128
        """
 
129
        prompt += ': '
 
130
        self.prompt(prompt, **kwargs)
 
131
        username = self.stdin.readline()
 
132
        if not username:
 
133
            username = None
 
134
        elif username[-1] == '\n':
 
135
            username = username[:-1]
 
136
        return username
 
137
 
 
138
    def make_progress_view(self):
 
139
        """Construct and return a new ProgressView subclass for this UI.
 
140
        """
 
141
        # if the user specifically requests either text or no progress bars,
 
142
        # always do that.  otherwise, guess based on $TERM and tty presence.
 
143
        if os.environ.get('BZR_PROGRESS_BAR') == 'text':
 
144
            return TextProgressView(self.stderr)
 
145
        elif os.environ.get('BZR_PROGRESS_BAR') == 'none':
 
146
            return NullProgressView()
 
147
        elif progress._supports_progress(self.stderr):
 
148
            return TextProgressView(self.stderr)
 
149
        else:
 
150
            return NullProgressView()
 
151
 
78
152
    def note(self, msg):
79
153
        """Write an already-formatted message, clearing the progress bar if necessary."""
80
154
        self.clear_term()
81
155
        self.stdout.write(msg + '\n')
82
156
 
 
157
    def prompt(self, prompt, **kwargs):
 
158
        """Emit prompt on the CLI.
 
159
        
 
160
        :param kwargs: Dictionary of arguments to insert into the prompt,
 
161
            to allow UIs to reformat the prompt.
 
162
        """
 
163
        if kwargs:
 
164
            # See <https://launchpad.net/bugs/365891>
 
165
            prompt = prompt % kwargs
 
166
        prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
 
167
        self.clear_term()
 
168
        self.stderr.write(prompt)
 
169
 
83
170
    def report_transport_activity(self, transport, byte_count, direction):
84
171
        """Called by transports as they do IO.
85
 
        
 
172
 
86
173
        This may update a progress bar, spinner, or similar display.
87
174
        By default it does nothing.
88
175
        """
89
 
        self._progress_view.show_transport_activity(byte_count)
 
176
        self._progress_view.show_transport_activity(transport,
 
177
            direction, byte_count)
90
178
 
91
179
    def _progress_updated(self, task):
92
180
        """A task has been updated and wants to be displayed.
93
181
        """
94
 
        if task != self._task_stack[-1]:
 
182
        if not self._task_stack:
 
183
            warnings.warn("%r updated but no tasks are active" %
 
184
                (task,))
 
185
        elif task != self._task_stack[-1]:
95
186
            warnings.warn("%r is not the top progress task %r" %
96
187
                (task, self._task_stack[-1]))
97
188
        self._progress_view.show_progress(task)
102
193
 
103
194
class TextProgressView(object):
104
195
    """Display of progress bar and other information on a tty.
105
 
    
106
 
    This shows one line of text, including possibly a network indicator, spinner, 
 
196
 
 
197
    This shows one line of text, including possibly a network indicator, spinner,
107
198
    progress bar, message, etc.
108
199
 
109
200
    One instance of this is created and held by the UI, and fed updates when a
120
211
        # true when there's output on the screen we may need to clear
121
212
        self._have_output = False
122
213
        # XXX: We could listen for SIGWINCH and update the terminal width...
 
214
        # https://launchpad.net/bugs/316357
123
215
        self._width = osutils.terminal_width()
124
216
        self._last_transport_msg = ''
125
217
        self._spin_pos = 0
127
219
        self._last_repaint = 0
128
220
        # time we last got information about transport activity
129
221
        self._transport_update_time = 0
130
 
        self._task_fraction = None
131
222
        self._last_task = None
132
223
        self._total_byte_count = 0
133
224
        self._bytes_since_update = 0
143
234
 
144
235
    def _render_bar(self):
145
236
        # return a string for the progress bar itself
146
 
        if (self._last_task is not None) and self._last_task.show_bar:
 
237
        if (self._last_task is None) or self._last_task.show_bar:
 
238
            # If there's no task object, we show space for the bar anyhow.
 
239
            # That's because most invocations of bzr will end showing progress
 
240
            # at some point, though perhaps only after doing some initial IO.
 
241
            # It looks better to draw the progress bar initially rather than
 
242
            # to have what looks like an incomplete progress bar.
147
243
            spin_str =  r'/-\|'[self._spin_pos % 4]
148
244
            self._spin_pos += 1
149
 
            f = self._task_fraction or 0
150
245
            cols = 20
151
 
            # number of markers highlighted in bar
152
 
            markers = int(round(float(cols) * f)) - 1
 
246
            if self._last_task is None:
 
247
                completion_fraction = 0
 
248
            else:
 
249
                completion_fraction = \
 
250
                    self._last_task._overall_completion_fraction() or 0
 
251
            markers = int(round(float(cols) * completion_fraction)) - 1
153
252
            bar_str = '[' + ('#' * markers + spin_str).ljust(cols) + '] '
154
253
            return bar_str
155
 
        elif (self._last_task is None) or self._last_task.show_spinner:
 
254
        elif self._last_task.show_spinner:
 
255
            # The last task wanted just a spinner, no bar
156
256
            spin_str =  r'/-\|'[self._spin_pos % 4]
157
257
            self._spin_pos += 1
158
258
            return spin_str + ' '
162
262
    def _format_task(self, task):
163
263
        if not task.show_count:
164
264
            s = ''
165
 
        elif task.total_cnt is not None:
 
265
        elif task.current_cnt is not None and task.total_cnt is not None:
166
266
            s = ' %d/%d' % (task.current_cnt, task.total_cnt)
167
267
        elif task.current_cnt is not None:
168
268
            s = ' %d' % (task.current_cnt)
169
269
        else:
170
270
            s = ''
171
 
        self._task_fraction = task._overall_completion_fraction()
172
271
        # compose all the parent messages
173
272
        t = task
174
273
        m = task.msg
178
277
                m = t.msg + ':' + m
179
278
        return m + s
180
279
 
181
 
    def _repaint(self):
 
280
    def _render_line(self):
182
281
        bar_string = self._render_bar()
183
282
        if self._last_task:
184
283
            task_msg = self._format_task(self._last_task)
185
284
        else:
186
285
            task_msg = ''
187
286
        trans = self._last_transport_msg
188
 
        if trans and task_msg:
 
287
        if trans:
189
288
            trans += ' | '
190
 
        s = (bar_string
191
 
             + trans
192
 
             + task_msg
193
 
             )
 
289
        return (bar_string + trans + task_msg)
 
290
 
 
291
    def _repaint(self):
 
292
        s = self._render_line()
194
293
        self._show_line(s)
195
294
        self._have_output = True
196
295
 
197
296
    def show_progress(self, task):
 
297
        """Called by the task object when it has changed.
 
298
        
 
299
        :param task: The top task object; its parents are also included 
 
300
            by following links.
 
301
        """
 
302
        must_update = task is not self._last_task
198
303
        self._last_task = task
199
304
        now = time.time()
200
 
        if now < self._last_repaint + 0.1:
 
305
        if (not must_update) and (now < self._last_repaint + 0.1):
201
306
            return
202
 
        if now > self._transport_update_time + 5:
 
307
        if now > self._transport_update_time + 10:
203
308
            # no recent activity; expire it
204
309
            self._last_transport_msg = ''
205
310
        self._last_repaint = now
206
311
        self._repaint()
207
312
 
208
 
    def show_transport_activity(self, byte_count):
209
 
        """Called by transports as they do IO.
210
 
        
 
313
    def show_transport_activity(self, transport, direction, byte_count):
 
314
        """Called by transports via the ui_factory, as they do IO.
 
315
 
211
316
        This may update a progress bar, spinner, or similar display.
212
317
        By default it does nothing.
213
318
        """
214
319
        # XXX: Probably there should be a transport activity model, and that
215
320
        # too should be seen by the progress view, rather than being poked in
216
321
        # here.
 
322
        if not self._have_output:
 
323
            # As a workaround for <https://launchpad.net/bugs/321935> we only
 
324
            # show transport activity when there's already a progress bar
 
325
            # shown, which time the application code is expected to know to
 
326
            # clear off the progress bar when it's going to send some other
 
327
            # output.  Eventually it would be nice to have that automatically
 
328
            # synchronized.
 
329
            return
217
330
        self._total_byte_count += byte_count
218
331
        self._bytes_since_update += byte_count
219
332
        now = time.time()
220
333
        if self._transport_update_time is None:
221
334
            self._transport_update_time = now
222
 
        elif now >= (self._transport_update_time + 0.2):
 
335
        elif now >= (self._transport_update_time + 0.5):
223
336
            # guard against clock stepping backwards, and don't update too
224
337
            # often
225
338
            rate = self._bytes_since_update / (now - self._transport_update_time)
226
 
            msg = ("%6dkB @ %4dkB/s" %
227
 
                (self._total_byte_count>>10, int(rate)>>10,))
 
339
            msg = ("%6dKB %5dKB/s" %
 
340
                    (self._total_byte_count>>10, int(rate)>>10,))
228
341
            self._transport_update_time = now
229
342
            self._last_repaint = now
230
343
            self._bytes_since_update = 0
231
344
            self._last_transport_msg = msg
232
345
            self._repaint()
233
 
 
234