Debian Codegraph @

Lib/_pyrepl/fancy_termios.py

raw
1 # Copyright 2000-2004 Michael Hudson-Doyle <[email protected]>
2 #
3 # All Rights Reserved
4 #
5 #
6 # Permission to use, copy, modify, and distribute this software and
7 # its documentation for any purpose is hereby granted without fee,
8 # provided that the above copyright notice appear in all copies and
9 # that both that copyright notice and this permission notice appear in
10 # supporting documentation.
11 #
12 # THE AUTHOR MICHAEL HUDSON DISCLAIMS ALL WARRANTIES WITH REGARD TO
13 # THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
14 # AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
15 # INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
16 # RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
17 # CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
18 # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19
20 import termios
21
22
23 TYPE_CHECKING = False
24
25 if TYPE_CHECKING:
26 from typing import cast
27 else:
28 cast = lambda typ, val: val
29
30
31 class TermState:
32 def __init__(self, attrs: list[int | list[bytes]]) -> None:
33 self.iflag = cast(int, attrs[0])
34 self.oflag = cast(int, attrs[1])
35 self.cflag = cast(int, attrs[2])
36 self.lflag = cast(int, attrs[3])
37 self.ispeed = cast(int, attrs[4])
38 self.ospeed = cast(int, attrs[5])
39 self.cc = cast(list[bytes], attrs[6])
40
41 def as_list(self) -> list[int | list[bytes]]:
42 return [
43 self.iflag,
44 self.oflag,
45 self.cflag,
46 self.lflag,
47 self.ispeed,
48 self.ospeed,
49 # Always return a copy of the control characters list to ensure
50 # there are not any additional references to self.cc
51 self.cc[:],
52 ]
53
54 def copy(self) -> "TermState":
55 return self.__class__(self.as_list())
56
57
58 def tcgetattr(fd: int) -> TermState:
59 return TermState(termios.tcgetattr(fd))
60
61
62 def tcsetattr(fd: int, when: int, attrs: TermState) -> None:
63 termios.tcsetattr(fd, when, attrs.as_list())
64
65
66 class Term(TermState):
67 TS__init__ = TermState.__init__
68
69 def __init__(self, fd: int = 0) -> None:
70 self.TS__init__(termios.tcgetattr(fd))
71 self.fd = fd
72 self.stack: list[list[int | list[bytes]]] = []
73
74 def save(self) -> None:
75 self.stack.append(self.as_list())
76
77 def set(self, when: int = termios.TCSANOW) -> None:
78 termios.tcsetattr(self.fd, when, self.as_list())
79
80 def restore(self) -> None:
81 self.TS__init__(self.stack.pop())
82 self.set()