Debian Codegraph @

lib_pypy/pyrepl/unix_console.py

raw symbols SCIP
1 # Copyright 2000-2010 Michael Hudson-Doyle <[email protected]>
2 # Antonio Cuni
3 # Armin Rigo
4 #
5 # All Rights Reserved
6 #
7 #
8 # Permission to use, copy, modify, and distribute this software and
9 # its documentation for any purpose is hereby granted without fee,
10 # provided that the above copyright notice appear in all copies and
11 # that both that copyright notice and this permission notice appear in
12 # supporting documentation.
13 #
14 # THE AUTHOR MICHAEL HUDSON DISCLAIMS ALL WARRANTIES WITH REGARD TO
15 # THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
16 # AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
17 # INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
18 # RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
19 # CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
20 # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21
22 from __future__ import annotations
23
24 import errno
25 import os
26 import re
27 import select
28 import signal
29 import struct
30 import termios
31 import time
32 import platform
33 from fcntl import ioctl
34
35 from . import curses
36 from .console import Console, Event
37 from .fancy_termios import tcgetattr, tcsetattr
38 from .trace import trace
39 from .unix_eventqueue import EventQueue
40 from .utils import wlen
41
42
43 TYPE_CHECKING = False
44
45 # types
46 if TYPE_CHECKING:
47 from typing import IO, Literal, overload
48 else:
49 overload = lambda func: None
50
51
52 class InvalidTerminal(RuntimeError):
53 pass
54
55
56 _error = (termios.error, curses.error, InvalidTerminal)
57
58 SIGWINCH_EVENT = "repaint"
59
60 FIONREAD = getattr(termios, "FIONREAD", None)
61 TIOCGWINSZ = getattr(termios, "TIOCGWINSZ", None)
62
63 # ------------ start of baudrate definitions ------------
64
65 # Add (possibly) missing baudrates (check termios man page) to termios
66
67
68 def add_baudrate_if_supported(dictionary: dict[int, int], rate: int) -> None:
69 baudrate_name = "B%d" % rate
70 if hasattr(termios, baudrate_name):
71 dictionary[getattr(termios, baudrate_name)] = rate
72
73
74 # Check the termios man page (Line speed) to know where these
75 # values come from.
76 potential_baudrates = [
77 0,
78 110,
79 115200,
80 1200,
81 134,
82 150,
83 1800,
84 19200,
85 200,
86 230400,
87 2400,
88 300,
89 38400,
90 460800,
91 4800,
92 50,
93 57600,
94 600,
95 75,
96 9600,
97 ]
98
99 ratedict: dict[int, int] = {}
100 for rate in potential_baudrates:
101 add_baudrate_if_supported(ratedict, rate)
102
103 # Clean up variables to avoid unintended usage
104 del rate, add_baudrate_if_supported
105
106 # ------------ end of baudrate definitions ------------
107
108 delayprog = re.compile(b"\\$<([0-9]+)((?:/|\\*){0,2})>")
109
110 try:
111 poll: type[select.poll] = select.poll
112 except AttributeError:
113 # this is exactly the minimum necessary to support what we
114 # do with poll objects
115 class MinimalPoll:
116 def __init__(self):
117 pass
118
119 def register(self, fd, flag):
120 self.fd = fd
121 # note: The 'timeout' argument is received as *milliseconds*
122 def poll(self, timeout: float | None = None) -> list[int]:
123 if timeout is None:
124 r, w, e = select.select([self.fd], [], [])
125 else:
126 r, w, e = select.select([self.fd], [], [], timeout/1000)
127 return r
128
129 poll = MinimalPoll # type: ignore[assignment]
130
131
132 class UnixConsole(Console):
133 def __init__(
134 self,
135 f_in: IO[bytes] | int = 0,
136 f_out: IO[bytes] | int = 1,
137 term: str = "",
138 encoding: str = "",
139 ):
140 """
141 Initialize the UnixConsole.
142
143 Parameters:
144 - f_in (int or file-like object): Input file descriptor or object.
145 - f_out (int or file-like object): Output file descriptor or object.
146 - term (str): Terminal name.
147 - encoding (str): Encoding to use for I/O operations.
148 """
149 super().__init__(f_in, f_out, term, encoding)
150
151 self.pollob = poll()
152 self.pollob.register(self.input_fd, select.POLLIN)
153 self.input_buffer = b""
154 self.input_buffer_pos = 0
155 curses.setupterm(term or None, self.output_fd)
156 self.term = term
157
158 @overload
159 def _my_getstr(cap: str, optional: Literal[False] = False) -> bytes: ...
160
161 @overload
162 def _my_getstr(cap: str, optional: bool) -> bytes | None: ...
163
164 def _my_getstr(cap: str, optional: bool = False) -> bytes | None:
165 r = curses.tigetstr(cap)
166 if not optional and r is None:
167 raise InvalidTerminal(
168 f"terminal doesn't have the required {cap} capability"
169 )
170 return r
171
172 self._bel = _my_getstr("bel")
173 self._civis = _my_getstr("civis", optional=True)
174 self._clear = _my_getstr("clear")
175 self._cnorm = _my_getstr("cnorm", optional=True)
176 self._cub = _my_getstr("cub", optional=True)
177 self._cub1 = _my_getstr("cub1", optional=True)
178 self._cud = _my_getstr("cud", optional=True)
179 self._cud1 = _my_getstr("cud1", optional=True)
180 self._cuf = _my_getstr("cuf", optional=True)
181 self._cuf1 = _my_getstr("cuf1", optional=True)
182 self._cup = _my_getstr("cup")
183 self._cuu = _my_getstr("cuu", optional=True)
184 self._cuu1 = _my_getstr("cuu1", optional=True)
185 self._dch1 = _my_getstr("dch1", optional=True)
186 self._dch = _my_getstr("dch", optional=True)
187 self._el = _my_getstr("el")
188 self._hpa = _my_getstr("hpa", optional=True)
189 self._ich = _my_getstr("ich", optional=True)
190 self._ich1 = _my_getstr("ich1", optional=True)
191 self._ind = _my_getstr("ind", optional=True)
192 self._pad = _my_getstr("pad", optional=True)
193 self._ri = _my_getstr("ri", optional=True)
194 self._rmkx = _my_getstr("rmkx", optional=True)
195 self._smkx = _my_getstr("smkx", optional=True)
196
197 self.__setup_movement()
198
199 self.event_queue = EventQueue(self.input_fd, self.encoding)
200 self.cursor_visible = 1
201
202 def __read(self, n: int) -> bytes:
203 if not self.input_buffer or self.input_buffer_pos >= len(self.input_buffer):
204 self.input_buffer = os.read(self.input_fd, 10000)
205
206 ret = self.input_buffer[self.input_buffer_pos : self.input_buffer_pos + n]
207 self.input_buffer_pos += len(ret)
208 if self.input_buffer_pos >= len(self.input_buffer):
209 self.input_buffer = b""
210 self.input_buffer_pos = 0
211 return ret
212
213
214 def change_encoding(self, encoding: str) -> None:
215 """
216 Change the encoding used for I/O operations.
217
218 Parameters:
219 - encoding (str): New encoding to use.
220 """
221 self.encoding = encoding
222
223 def refresh(self, screen, c_xy):
224 """
225 Refresh the console screen.
226
227 Parameters:
228 - screen (list): List of strings representing the screen contents.
229 - c_xy (tuple): Cursor position (x, y) on the screen.
230 """
231 cx, cy = c_xy
232 if not self.__gone_tall:
233 while len(self.screen) < min(len(screen), self.height):
234 self.__hide_cursor()
235 self.__move(0, len(self.screen) - 1)
236 self.__write("\n")
237 self.__posxy = 0, len(self.screen)
238 self.screen.append("")
239 else:
240 while len(self.screen) < len(screen):
241 self.screen.append("")
242
243 if len(screen) > self.height:
244 self.__gone_tall = 1
245 self.__move = self.__move_tall
246
247 px, py = self.__posxy
248 old_offset = offset = self.__offset
249 height = self.height
250
251 # we make sure the cursor is on the screen, and that we're
252 # using all of the screen if we can
253 if cy < offset:
254 offset = cy
255 elif cy >= offset + height:
256 offset = cy - height + 1
257 elif offset > 0 and len(screen) < offset + height:
258 offset = max(len(screen) - height, 0)
259 screen.append("")
260
261 oldscr = self.screen[old_offset : old_offset + height]
262 newscr = screen[offset : offset + height]
263
264 # use hardware scrolling if we have it.
265 if old_offset > offset and self._ri:
266 self.__hide_cursor()
267 self.__write_code(self._cup, 0, 0)
268 self.__posxy = 0, old_offset
269 for i in range(old_offset - offset):
270 self.__write_code(self._ri)
271 oldscr.pop(-1)
272 oldscr.insert(0, "")
273 elif old_offset < offset and self._ind:
274 self.__hide_cursor()
275 self.__write_code(self._cup, self.height - 1, 0)
276 self.__posxy = 0, old_offset + self.height - 1
277 for i in range(offset - old_offset):
278 self.__write_code(self._ind)
279 oldscr.pop(0)
280 oldscr.append("")
281
282 self.__offset = offset
283
284 for (
285 y,
286 oldline,
287 newline,
288 ) in zip(range(offset, offset + height), oldscr, newscr):
289 if oldline != newline:
290 self.__write_changed_line(y, oldline, newline, px)
291
292 y = len(newscr)
293 while y < len(oldscr):
294 self.__hide_cursor()
295 self.__move(0, y)
296 self.__posxy = 0, y
297 self.__write_code(self._el)
298 y += 1
299
300 self.__show_cursor()
301
302 self.screen = screen.copy()
303 self.move_cursor(cx, cy)
304 self.flushoutput()
305
306 def move_cursor(self, x, y):
307 """
308 Move the cursor to the specified position on the screen.
309
310 Parameters:
311 - x (int): X coordinate.
312 - y (int): Y coordinate.
313 """
314 if y < self.__offset or y >= self.__offset + self.height:
315 self.event_queue.insert(Event("scroll", None))
316 else:
317 self.__move(x, y)
318 self.__posxy = x, y
319 self.flushoutput()
320
321 def prepare(self):
322 """
323 Prepare the console for input/output operations.
324 """
325 self.__svtermstate = tcgetattr(self.input_fd)
326 raw = self.__svtermstate.copy()
327 raw.iflag &= ~(termios.INPCK | termios.ISTRIP | termios.IXON)
328 raw.oflag &= ~(termios.OPOST)
329 raw.cflag &= ~(termios.CSIZE | termios.PARENB)
330 raw.cflag |= termios.CS8
331 raw.iflag |= termios.BRKINT
332 raw.lflag &= ~(termios.ICANON | termios.ECHO | termios.IEXTEN)
333 raw.lflag |= termios.ISIG
334 raw.cc[termios.VMIN] = 1
335 raw.cc[termios.VTIME] = 0
336 tcsetattr(self.input_fd, termios.TCSADRAIN, raw)
337 self.__rawstate = raw
338
339 # In macOS terminal we need to deactivate line wrap via ANSI escape code
340 if platform.system() == "Darwin" and os.getenv("TERM_PROGRAM") == "Apple_Terminal":
341 os.write(self.output_fd, b"\033[?7l")
342
343 self.screen = []
344 self.height, self.width = self.getheightwidth()
345
346 self.__buffer = []
347
348 self.__posxy = 0, 0
349 self.__gone_tall = 0
350 self.__move = self.__move_short
351 self.__offset = 0
352
353 self.__maybe_write_code(self._smkx)
354
355 try:
356 self.old_sigwinch = signal.signal(signal.SIGWINCH, self.__sigwinch)
357 except ValueError:
358 pass
359
360 self.__enable_bracketed_paste()
361
362 def restore(self):
363 """
364 Restore the console to the default state
365 """
366 self.__disable_bracketed_paste()
367 self.__maybe_write_code(self._rmkx)
368 self.flushoutput()
369 tcsetattr(self.input_fd, termios.TCSADRAIN, self.__svtermstate)
370
371 if platform.system() == "Darwin" and os.getenv("TERM_PROGRAM") == "Apple_Terminal":
372 os.write(self.output_fd, b"\033[?7h")
373
374 if hasattr(self, "old_sigwinch"):
375 signal.signal(signal.SIGWINCH, self.old_sigwinch)
376 del self.old_sigwinch
377
378 def restore_output(self) -> None:
379 """Temporarily re-enable terminal output processing (OPOST/ONLCR) so
380 that user-supplied callbacks can use print() with normal \\r\\n output.
381 Input stays in raw mode so pyrepl keeps control of the keyboard."""
382 self.flushoutput()
383 with_opost = self.__rawstate.copy()
384 with_opost.oflag = self.__svtermstate.oflag # restore original output flags
385 tcsetattr(self.input_fd, termios.TCSANOW, with_opost)
386
387 def prepare_output(self) -> None:
388 """Re-enter raw output mode after restore_output()."""
389 self.flushoutput()
390 tcsetattr(self.input_fd, termios.TCSANOW, self.__rawstate)
391
392 def push_char(self, char: int | bytes) -> None:
393 """
394 Push a character to the console event queue.
395 """
396 trace("push char {char!r}", char=char)
397 self.event_queue.push(char)
398
399 def get_event(self, block: bool = True) -> Event | None:
400 """
401 Get an event from the console event queue.
402
403 Parameters:
404 - block (bool): Whether to block until an event is available.
405
406 Returns:
407 - Event: Event object from the event queue.
408 """
409 if not block and not self.wait(timeout=0):
410 return None
411 while self.event_queue.empty():
412 while True:
413 try:
414 self.push_char(self.__read(1))
415 except OSError as err:
416 if err.errno == errno.EINTR:
417 if not self.event_queue.empty():
418 return self.event_queue.get()
419 else:
420 continue
421 else:
422 raise
423 else:
424 break
425 return self.event_queue.get()
426
427 def wait(self, timeout: float | None = None) -> bool:
428 """
429 Wait for events on the console.
430 """
431 return bool(self.pollob.poll(timeout))
432
433 def set_cursor_vis(self, visible):
434 """
435 Set the visibility of the cursor.
436
437 Parameters:
438 - visible (bool): Visibility flag.
439 """
440 if visible:
441 self.__show_cursor()
442 else:
443 self.__hide_cursor()
444
445 if TIOCGWINSZ:
446
447 def getheightwidth(self):
448 """
449 Get the height and width of the console.
450
451 Returns:
452 - tuple: Height and width of the console.
453 """
454 try:
455 return int(os.environ["LINES"]), int(os.environ["COLUMNS"])
456 except KeyError:
457 height, width = struct.unpack(
458 "hhhh", ioctl(self.input_fd, TIOCGWINSZ, b"\000" * 8)
459 )[0:2]
460 if not height:
461 return 25, 80
462 return height, width
463
464 else:
465
466 def getheightwidth(self):
467 """
468 Get the height and width of the console.
469
470 Returns:
471 - tuple: Height and width of the console.
472 """
473 try:
474 return int(os.environ["LINES"]), int(os.environ["COLUMNS"])
475 except KeyError:
476 return 25, 80
477
478 def forgetinput(self):
479 """
480 Discard any pending input on the console.
481 """
482 termios.tcflush(self.input_fd, termios.TCIFLUSH)
483
484 def flushoutput(self):
485 """
486 Flush the output buffer.
487 """
488 for text, iscode in self.__buffer:
489 if iscode:
490 self.__tputs(text)
491 else:
492 os.write(self.output_fd, text.encode(self.encoding, "replace"))
493 del self.__buffer[:]
494
495 def finish(self):
496 """
497 Finish console operations and flush the output buffer.
498 """
499 y = len(self.screen) - 1
500 while y >= 0 and not self.screen[y]:
501 y -= 1
502 self.__move(0, min(y, self.height + self.__offset - 1))
503 self.__write("\n\r")
504 self.flushoutput()
505
506 def beep(self):
507 """
508 Emit a beep sound.
509 """
510 self.__maybe_write_code(self._bel)
511 self.flushoutput()
512
513 if FIONREAD:
514
515 def getpending(self):
516 """
517 Get pending events from the console event queue.
518
519 Returns:
520 - Event: Pending event from the event queue.
521 """
522 e = Event("key", "", b"")
523
524 while not self.event_queue.empty():
525 e2 = self.event_queue.get()
526 e.data += e2.data
527 e.raw += e.raw
528
529 amount = struct.unpack("i", ioctl(self.input_fd, FIONREAD, b"\0\0\0\0"))[0]
530 raw = self.__read(amount)
531 data = str(raw, self.encoding, "replace")
532 e.data += data
533 e.raw += raw
534 return e
535
536 else:
537
538 def getpending(self):
539 """
540 Get pending events from the console event queue.
541
542 Returns:
543 - Event: Pending event from the event queue.
544 """
545 e = Event("key", "", b"")
546
547 while not self.event_queue.empty():
548 e2 = self.event_queue.get()
549 e.data += e2.data
550 e.raw += e.raw
551
552 amount = 10000
553 raw = self.__read(amount)
554 data = str(raw, self.encoding, "replace")
555 e.data += data
556 e.raw += raw
557 return e
558
559 def clear(self):
560 """
561 Clear the console screen.
562 """
563 self.__write_code(self._clear)
564 self.__gone_tall = 1
565 self.__move = self.__move_tall
566 self.__posxy = 0, 0
567 self.screen = []
568
569 @property
570 def input_hook(self):
571 return None # not supported on pypy
572 try:
573 import posix
574 except ImportError:
575 return None
576 if posix._is_inputhook_installed():
577 return posix._inputhook
578
579 def __enable_bracketed_paste(self) -> None:
580 os.write(self.output_fd, b"\x1b[?2004h")
581
582 def __disable_bracketed_paste(self) -> None:
583 os.write(self.output_fd, b"\x1b[?2004l")
584
585 def __setup_movement(self):
586 """
587 Set up the movement functions based on the terminal capabilities.
588 """
589 if 0 and self._hpa: # hpa don't work in windows telnet :-(
590 self.__move_x = self.__move_x_hpa
591 elif self._cub and self._cuf:
592 self.__move_x = self.__move_x_cub_cuf
593 elif self._cub1 and self._cuf1:
594 self.__move_x = self.__move_x_cub1_cuf1
595 else:
596 raise RuntimeError("insufficient terminal (horizontal)")
597
598 if self._cuu and self._cud:
599 self.__move_y = self.__move_y_cuu_cud
600 elif self._cuu1 and self._cud1:
601 self.__move_y = self.__move_y_cuu1_cud1
602 else:
603 raise RuntimeError("insufficient terminal (vertical)")
604
605 if self._dch1:
606 self.dch1 = self._dch1
607 elif self._dch:
608 self.dch1 = curses.tparm(self._dch, 1)
609 else:
610 self.dch1 = None
611
612 if self._ich1:
613 self.ich1 = self._ich1
614 elif self._ich:
615 self.ich1 = curses.tparm(self._ich, 1)
616 else:
617 self.ich1 = None
618
619 self.__move = self.__move_short
620
621 def __write_changed_line(self, y, oldline, newline, px_coord):
622 # this is frustrating; there's no reason to test (say)
623 # self.dch1 inside the loop -- but alternative ways of
624 # structuring this function are equally painful (I'm trying to
625 # avoid writing code generators these days...)
626 minlen = min(wlen(oldline), wlen(newline))
627 x_pos = 0
628 x_coord = 0
629
630 px_pos = 0
631 j = 0
632 for c in oldline:
633 if j >= px_coord:
634 break
635 j += wlen(c)
636 px_pos += 1
637
638 # reuse the oldline as much as possible, but stop as soon as we
639 # encounter an ESCAPE, because it might be the start of an escape
640 # sequence
641 while (
642 x_coord < minlen
643 and oldline[x_pos] == newline[x_pos]
644 and newline[x_pos] != "\x1b"
645 ):
646 x_coord += wlen(newline[x_pos])
647 x_pos += 1
648
649 # if we need to insert a single character right after the first detected change
650 if oldline[x_pos:] == newline[x_pos + 1 :] and self.ich1:
651 if (
652 y == self.__posxy[1]
653 and x_coord > self.__posxy[0]
654 and oldline[px_pos:x_pos] == newline[px_pos + 1 : x_pos + 1]
655 ):
656 x_pos = px_pos
657 x_coord = px_coord
658 character_width = wlen(newline[x_pos])
659 self.__move(x_coord, y)
660 self.__write_code(self.ich1)
661 self.__write(newline[x_pos])
662 self.__posxy = x_coord + character_width, y
663
664 # if it's a single character change in the middle of the line
665 elif (
666 x_coord < minlen
667 and oldline[x_pos + 1 :] == newline[x_pos + 1 :]
668 and wlen(oldline[x_pos]) == wlen(newline[x_pos])
669 ):
670 character_width = wlen(newline[x_pos])
671 self.__move(x_coord, y)
672 self.__write(newline[x_pos])
673 self.__posxy = x_coord + character_width, y
674
675 # if this is the last character to fit in the line and we edit in the middle of the line
676 elif (
677 self.dch1
678 and self.ich1
679 and wlen(newline) == self.width
680 and x_coord < wlen(newline) - 2
681 and newline[x_pos + 1 : -1] == oldline[x_pos:-2]
682 ):
683 self.__hide_cursor()
684 self.__move(self.width - 2, y)
685 self.__posxy = self.width - 2, y
686 self.__write_code(self.dch1)
687
688 character_width = wlen(newline[x_pos])
689 self.__move(x_coord, y)
690 self.__write_code(self.ich1)
691 self.__write(newline[x_pos])
692 self.__posxy = character_width + 1, y
693
694 else:
695 self.__hide_cursor()
696 self.__move(x_coord, y)
697 if wlen(oldline) > wlen(newline):
698 self.__write_code(self._el)
699 self.__write(newline[x_pos:])
700 self.__posxy = wlen(newline), y
701
702 if "\x1b" in newline:
703 # ANSI escape characters are present, so we can't assume
704 # anything about the position of the cursor. Moving the cursor
705 # to the left margin should work to get to a known position.
706 self.move_cursor(0, y)
707
708 def __write(self, text):
709 self.__buffer.append((text, 0))
710
711 def __write_code(self, fmt, *args):
712 self.__buffer.append((curses.tparm(fmt, *args), 1))
713
714 def __maybe_write_code(self, fmt, *args):
715 if fmt:
716 self.__write_code(fmt, *args)
717
718 def __move_y_cuu1_cud1(self, y):
719 dy = y - self.__posxy[1]
720 if dy > 0:
721 self.__write_code(dy * self._cud1)
722 elif dy < 0:
723 self.__write_code((-dy) * self._cuu1)
724
725 def __move_y_cuu_cud(self, y):
726 dy = y - self.__posxy[1]
727 if dy > 0:
728 self.__write_code(self._cud, dy)
729 elif dy < 0:
730 self.__write_code(self._cuu, -dy)
731
732 def __move_x_hpa(self, x: int) -> None:
733 if x != self.__posxy[0]:
734 self.__write_code(self._hpa, x)
735
736 def __move_x_cub1_cuf1(self, x: int) -> None:
737 dx = x - self.__posxy[0]
738 if dx > 0:
739 self.__write_code(self._cuf1 * dx)
740 elif dx < 0:
741 self.__write_code(self._cub1 * (-dx))
742
743 def __move_x_cub_cuf(self, x: int) -> None:
744 dx = x - self.__posxy[0]
745 if dx > 0:
746 self.__write_code(self._cuf, dx)
747 elif dx < 0:
748 self.__write_code(self._cub, -dx)
749
750 def __move_short(self, x, y):
751 self.__move_x(x)
752 self.__move_y(y)
753
754 def __move_tall(self, x, y):
755 assert 0 <= y - self.__offset < self.height, y - self.__offset
756 self.__write_code(self._cup, y - self.__offset, x)
757
758 def __sigwinch(self, signum, frame):
759 self.height, self.width = self.getheightwidth()
760 self.event_queue.insert(Event("resize", None))
761
762 def __hide_cursor(self):
763 if self.cursor_visible:
764 self.__maybe_write_code(self._civis)
765 self.cursor_visible = 0
766
767 def __show_cursor(self):
768 if not self.cursor_visible:
769 self.__maybe_write_code(self._cnorm)
770 self.cursor_visible = 1
771
772 def repaint(self):
773 if not self.__gone_tall:
774 self.__posxy = 0, self.__posxy[1]
775 self.__write("\r")
776 ns = len(self.screen) * ["\000" * self.width]
777 self.screen = ns
778 else:
779 self.__posxy = 0, self.__offset
780 self.__move(0, self.__offset)
781 ns = self.height * ["\000" * self.width]
782 self.screen = ns
783
784 def __tputs(self, fmt, prog=delayprog):
785 """A Python implementation of the curses tputs function; the
786 curses one can't really be wrapped in a sane manner.
787
788 I have the strong suspicion that this is complexity that
789 will never do anyone any good."""
790 # using .get() means that things will blow up
791 # only if the bps is actually needed (which I'm
792 # betting is pretty unlkely)
793 bps = ratedict.get(self.__svtermstate.ospeed)
794 while 1:
795 m = prog.search(fmt)
796 if not m:
797 os.write(self.output_fd, fmt)
798 break
799 x, y = m.span()
800 os.write(self.output_fd, fmt[:x])
801 fmt = fmt[y:]
802 delay = int(m.group(1))
803 if b"*" in m.group(2):
804 delay *= self.height
805 if self._pad and bps is not None:
806 nchars = (bps * delay) / 1000
807 os.write(self.output_fd, self._pad * nchars)
808 else:
809 time.sleep(float(delay) / 1000.0)