~bzr-pqm/bzr/bzr.dev

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