~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/ui/text.py

  • Committer: Vincent Ladeuil
  • Date: 2012-03-13 16:42:20 UTC
  • mto: This revision was merged to the branch mainline in revision 6512.
  • Revision ID: v.ladeuil+lp@free.fr-20120313164220-atkou2zprhlspmwg
Mention that a given config option cannot be safely handled via both APIs at the same time.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2005-2011 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
18
18
"""Text UI, write output to the console.
19
19
"""
20
20
 
21
 
import codecs
22
 
import getpass
 
21
from __future__ import absolute_import
 
22
 
23
23
import os
24
24
import sys
25
25
import time
26
 
import warnings
27
26
 
28
27
from bzrlib.lazy_import import lazy_import
29
28
lazy_import(globals(), """
 
29
import codecs
 
30
import getpass
 
31
import warnings
 
32
 
30
33
from bzrlib import (
31
34
    debug,
32
35
    progress,
33
36
    osutils,
34
 
    symbol_versioning,
35
37
    trace,
36
38
    )
37
39
 
43
45
    )
44
46
 
45
47
 
 
48
class _ChooseUI(object):
 
49
 
 
50
    """ Helper class for choose implementation.
 
51
    """
 
52
 
 
53
    def __init__(self, ui, msg, choices, default):
 
54
        self.ui = ui
 
55
        self._setup_mode()
 
56
        self._build_alternatives(msg, choices, default)
 
57
 
 
58
    def _setup_mode(self):
 
59
        """Setup input mode (line-based, char-based) and echo-back.
 
60
 
 
61
        Line-based input is used if the BZR_TEXTUI_INPUT environment
 
62
        variable is set to 'line-based', or if there is no controlling
 
63
        terminal.
 
64
        """
 
65
        if os.environ.get('BZR_TEXTUI_INPUT') != 'line-based' and \
 
66
           self.ui.stdin == sys.stdin and self.ui.stdin.isatty():
 
67
            self.line_based = False
 
68
            self.echo_back = True
 
69
        else:
 
70
            self.line_based = True
 
71
            self.echo_back = not self.ui.stdin.isatty()
 
72
 
 
73
    def _build_alternatives(self, msg, choices, default):
 
74
        """Parse choices string.
 
75
 
 
76
        Setup final prompt and the lists of choices and associated
 
77
        shortcuts.
 
78
        """
 
79
        index = 0
 
80
        help_list = []
 
81
        self.alternatives = {}
 
82
        choices = choices.split('\n')
 
83
        if default is not None and default not in range(0, len(choices)):
 
84
            raise ValueError("invalid default index")
 
85
        for c in choices:
 
86
            name = c.replace('&', '').lower()
 
87
            choice = (name, index)
 
88
            if name in self.alternatives:
 
89
                raise ValueError("duplicated choice: %s" % name)
 
90
            self.alternatives[name] = choice
 
91
            shortcut = c.find('&')
 
92
            if -1 != shortcut and (shortcut + 1) < len(c):
 
93
                help = c[:shortcut]
 
94
                help += '[' + c[shortcut + 1] + ']'
 
95
                help += c[(shortcut + 2):]
 
96
                shortcut = c[shortcut + 1]
 
97
            else:
 
98
                c = c.replace('&', '')
 
99
                shortcut = c[0]
 
100
                help = '[%s]%s' % (shortcut, c[1:])
 
101
            shortcut = shortcut.lower()
 
102
            if shortcut in self.alternatives:
 
103
                raise ValueError("duplicated shortcut: %s" % shortcut)
 
104
            self.alternatives[shortcut] = choice
 
105
            # Add redirections for default.
 
106
            if index == default:
 
107
                self.alternatives[''] = choice
 
108
                self.alternatives['\r'] = choice
 
109
            help_list.append(help)
 
110
            index += 1
 
111
 
 
112
        self.prompt = u'%s (%s): ' % (msg, ', '.join(help_list))
 
113
 
 
114
    def _getline(self):
 
115
        line = self.ui.stdin.readline()
 
116
        if '' == line:
 
117
            raise EOFError
 
118
        return line.strip()
 
119
 
 
120
    def _getchar(self):
 
121
        char = osutils.getchar()
 
122
        if char == chr(3): # INTR
 
123
            raise KeyboardInterrupt
 
124
        if char == chr(4): # EOF (^d, C-d)
 
125
            raise EOFError
 
126
        return char
 
127
 
 
128
    def interact(self):
 
129
        """Keep asking the user until a valid choice is made.
 
130
        """
 
131
        if self.line_based:
 
132
            getchoice = self._getline
 
133
        else:
 
134
            getchoice = self._getchar
 
135
        iter = 0
 
136
        while True:
 
137
            iter += 1
 
138
            if 1 == iter or self.line_based:
 
139
                self.ui.prompt(self.prompt)
 
140
            try:
 
141
                choice = getchoice()
 
142
            except EOFError:
 
143
                self.ui.stderr.write('\n')
 
144
                return None
 
145
            except KeyboardInterrupt:
 
146
                self.ui.stderr.write('\n')
 
147
                raise KeyboardInterrupt
 
148
            choice = choice.lower()
 
149
            if choice not in self.alternatives:
 
150
                # Not a valid choice, keep on asking.
 
151
                continue
 
152
            name, index = self.alternatives[choice]
 
153
            if self.echo_back:
 
154
                self.ui.stderr.write(name + '\n')
 
155
            return index
 
156
 
 
157
 
46
158
class TextUIFactory(UIFactory):
47
159
    """A UI factory for Text user interefaces."""
48
160
 
60
172
        self.stderr = stderr
61
173
        # paints progress, network activity, etc
62
174
        self._progress_view = self.make_progress_view()
63
 
        
 
175
 
 
176
    def choose(self, msg, choices, default=None):
 
177
        """Prompt the user for a list of alternatives.
 
178
 
 
179
        Support both line-based and char-based editing.
 
180
 
 
181
        In line-based mode, both the shortcut and full choice name are valid
 
182
        answers, e.g. for choose('prompt', '&yes\n&no'): 'y', ' Y ', ' yes',
 
183
        'YES ' are all valid input lines for choosing 'yes'.
 
184
 
 
185
        An empty line, when in line-based mode, or pressing enter in char-based
 
186
        mode will select the default choice (if any).
 
187
 
 
188
        Choice is echoed back if:
 
189
        - input is char-based; which means a controlling terminal is available,
 
190
          and osutils.getchar is used
 
191
        - input is line-based, and no controlling terminal is available
 
192
        """
 
193
 
 
194
        choose_ui = _ChooseUI(self, msg, choices, default)
 
195
        return choose_ui.interact()
 
196
 
 
197
    def be_quiet(self, state):
 
198
        if state and not self._quiet:
 
199
            self.clear_term()
 
200
        UIFactory.be_quiet(self, state)
 
201
        self._progress_view = self.make_progress_view()
 
202
 
64
203
    def clear_term(self):
65
204
        """Prepare the terminal for output.
66
205
 
72
211
        # to clear it.  We might need to separately check for the case of
73
212
        self._progress_view.clear()
74
213
 
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
214
    def get_integer(self, prompt):
88
215
        while True:
89
216
            self.prompt(prompt)
108
235
                password = password[:-1]
109
236
        return password
110
237
 
111
 
    def get_password(self, prompt='', **kwargs):
 
238
    def get_password(self, prompt=u'', **kwargs):
112
239
        """Prompt the user for a password.
113
240
 
114
241
        :param prompt: The prompt to present the user
146
273
    def make_progress_view(self):
147
274
        """Construct and return a new ProgressView subclass for this UI.
148
275
        """
149
 
        # if the user specifically requests either text or no progress bars,
150
 
        # always do that.  otherwise, guess based on $TERM and tty presence.
151
 
        if os.environ.get('BZR_PROGRESS_BAR') == 'text':
 
276
        # with --quiet, never any progress view
 
277
        # <https://bugs.launchpad.net/bzr/+bug/320035>.  Otherwise if the
 
278
        # user specifically requests either text or no progress bars, always
 
279
        # do that.  otherwise, guess based on $TERM and tty presence.
 
280
        if self.is_quiet():
 
281
            return NullProgressView()
 
282
        elif os.environ.get('BZR_PROGRESS_BAR') == 'text':
152
283
            return TextProgressView(self.stderr)
153
284
        elif os.environ.get('BZR_PROGRESS_BAR') == 'none':
154
285
            return NullProgressView()
188
319
        :param kwargs: Dictionary of arguments to insert into the prompt,
189
320
            to allow UIs to reformat the prompt.
190
321
        """
 
322
        if type(prompt) != unicode:
 
323
            raise ValueError("prompt %r not a unicode string" % prompt)
191
324
        if kwargs:
192
325
            # See <https://launchpad.net/bugs/365891>
193
326
            prompt = prompt % kwargs
194
327
        prompt = prompt.encode(osutils.get_terminal_encoding(), 'replace')
195
328
        self.clear_term()
 
329
        self.stdout.flush()
196
330
        self.stderr.write(prompt)
197
331
 
198
332
    def report_transport_activity(self, transport, byte_count, direction):
219
353
 
220
354
    def show_warning(self, msg):
221
355
        self.clear_term()
 
356
        if isinstance(msg, unicode):
 
357
            te = osutils.get_terminal_encoding()
 
358
            msg = msg.encode(te, 'replace')
222
359
        self.stderr.write("bzr: warning: %s\n" % msg)
223
360
 
224
361
    def _progress_updated(self, task):
228
365
            warnings.warn("%r updated but no tasks are active" %
229
366
                (task,))
230
367
        elif task != self._task_stack[-1]:
231
 
            warnings.warn("%r is not the top progress task %r" %
232
 
                (task, self._task_stack[-1]))
 
368
            # We used to check it was the top task, but it's hard to always
 
369
            # get this right and it's not necessarily useful: any actual
 
370
            # problems will be evident in use
 
371
            #warnings.warn("%r is not the top progress task %r" %
 
372
            #     (task, self._task_stack[-1]))
 
373
            pass
233
374
        self._progress_view.show_progress(task)
234
375
 
235
376
    def _progress_all_finished(self):
236
377
        self._progress_view.clear()
237
378
 
 
379
    def show_user_warning(self, warning_id, **message_args):
 
380
        """Show a text message to the user.
 
381
 
 
382
        Explicitly not for warnings about bzr apis, deprecations or internals.
 
383
        """
 
384
        # eventually trace.warning should migrate here, to avoid logging and
 
385
        # be easier to test; that has a lot of test fallout so for now just
 
386
        # new code can call this
 
387
        if warning_id not in self.suppressed_warnings:
 
388
            self.stderr.write(self.format_user_warning(warning_id, message_args) +
 
389
                '\n')
 
390
 
238
391
 
239
392
class TextProgressView(object):
240
393
    """Display of progress bar and other information on a tty.
271
424
        # correspond reliably to overall command progress
272
425
        self.enable_bar = False
273
426
 
 
427
    def _avail_width(self):
 
428
        # we need one extra space for terminals that wrap on last char
 
429
        w = osutils.terminal_width() 
 
430
        if w is None:
 
431
            return None
 
432
        else:
 
433
            return w - 1
 
434
 
274
435
    def _show_line(self, s):
275
436
        # sys.stderr.write("progress %r\n" % s)
276
 
        width = osutils.terminal_width()
 
437
        width = self._avail_width()
277
438
        if width is not None:
278
 
            # we need one extra space for terminals that wrap on last char
279
 
            width = width - 1
280
439
            s = '%-*.*s' % (width, width, s)
281
440
        self._term_file.write('\r' + s + '\r')
282
441
 
319
478
            return ''
320
479
 
321
480
    def _format_task(self, task):
 
481
        """Format task-specific parts of progress bar.
 
482
 
 
483
        :returns: (text_part, counter_part) both unicode strings.
 
484
        """
322
485
        if not task.show_count:
323
486
            s = ''
324
487
        elif task.current_cnt is not None and task.total_cnt is not None:
334
497
            t = t._parent_task
335
498
            if t.msg:
336
499
                m = t.msg + ':' + m
337
 
        return m + s
 
500
        return m, s
338
501
 
339
502
    def _render_line(self):
340
503
        bar_string = self._render_bar()
341
504
        if self._last_task:
342
 
            task_msg = self._format_task(self._last_task)
 
505
            task_part, counter_part = self._format_task(self._last_task)
343
506
        else:
344
 
            task_msg = ''
 
507
            task_part = counter_part = ''
345
508
        if self._last_task and not self._last_task.show_transport_activity:
346
509
            trans = ''
347
510
        else:
348
511
            trans = self._last_transport_msg
349
 
            if trans:
350
 
                trans += ' | '
351
 
        return (bar_string + trans + task_msg)
 
512
        # the bar separates the transport activity from the message, so even
 
513
        # if there's no bar or spinner, we must show something if both those
 
514
        # fields are present
 
515
        if (task_part or trans) and not bar_string:
 
516
            bar_string = '| '
 
517
        # preferentially truncate the task message if we don't have enough
 
518
        # space
 
519
        avail_width = self._avail_width()
 
520
        if avail_width is not None:
 
521
            # if terminal avail_width is unknown, don't truncate
 
522
            current_len = len(bar_string) + len(trans) + len(task_part) + len(counter_part)
 
523
            gap = current_len - avail_width
 
524
            if gap > 0:
 
525
                task_part = task_part[:-gap-2] + '..'
 
526
        s = trans + bar_string + task_part + counter_part
 
527
        if avail_width is not None:
 
528
            if len(s) < avail_width:
 
529
                s = s.ljust(avail_width)
 
530
            elif len(s) > avail_width:
 
531
                s = s[:avail_width]
 
532
        return s
352
533
 
353
534
    def _repaint(self):
354
535
        s = self._render_line()
407
588
        elif now >= (self._transport_update_time + 0.5):
408
589
            # guard against clock stepping backwards, and don't update too
409
590
            # often
410
 
            rate = self._bytes_since_update / (now - self._transport_update_time)
411
 
            msg = ("%6dKB %5dKB/s" %
412
 
                    (self._total_byte_count>>10, int(rate)>>10,))
 
591
            rate = (self._bytes_since_update
 
592
                    / (now - self._transport_update_time))
 
593
            # using base-10 units (see HACKING.txt).
 
594
            msg = ("%6dkB %5dkB/s " %
 
595
                    (self._total_byte_count / 1000, int(rate) / 1000,))
413
596
            self._transport_update_time = now
414
597
            self._last_repaint = now
415
598
            self._bytes_since_update = 0
425
608
                transfer_time = 0.001
426
609
            bps = self._total_byte_count / transfer_time
427
610
 
428
 
        msg = ('Transferred: %.0fKiB'
429
 
               ' (%.1fK/s r:%.0fK w:%.0fK'
430
 
               % (self._total_byte_count / 1024.,
431
 
                  bps / 1024.,
432
 
                  self._bytes_by_direction['read'] / 1024.,
433
 
                  self._bytes_by_direction['write'] / 1024.,
 
611
        # using base-10 units (see HACKING.txt).
 
612
        msg = ('Transferred: %.0fkB'
 
613
               ' (%.1fkB/s r:%.0fkB w:%.0fkB'
 
614
               % (self._total_byte_count / 1000.,
 
615
                  bps / 1000.,
 
616
                  self._bytes_by_direction['read'] / 1000.,
 
617
                  self._bytes_by_direction['write'] / 1000.,
434
618
                 ))
435
619
        if self._bytes_by_direction['unknown'] > 0:
436
 
            msg += ' u:%.0fK)' % (
437
 
                self._bytes_by_direction['unknown'] / 1024.
 
620
            msg += ' u:%.0fkB)' % (
 
621
                self._bytes_by_direction['unknown'] / 1000.
438
622
                )
439
623
        else:
440
624
            msg += ')'