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