Debian Codegraph @

Lib/_pyrepl/unix_console.py

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