Debian Codegraph @

Lib/_pyrepl/console.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 from __future__ import annotations
21
22 import _colorize
23
24 from abc import ABC, abstractmethod
25 import ast
26 import code
27 import linecache
28 from dataclasses import dataclass, field
29 import os.path
30 import sys
31
32
33 TYPE_CHECKING = False
34
35 if TYPE_CHECKING:
36 from typing import IO
37 from typing import Callable
38
39
40 @dataclass
41 class Event:
42 evt: str
43 data: str
44 raw: bytes = b""
45
46
47 @dataclass
48 class Console(ABC):
49 posxy: tuple[int, int]
50 screen: list[str] = field(default_factory=list)
51 height: int = 25
52 width: int = 80
53
54 def __init__(
55 self,
56 f_in: IO[bytes] | int = 0,
57 f_out: IO[bytes] | int = 1,
58 term: str = "",
59 encoding: str = "",
60 ):
61 self.encoding = encoding or sys.getdefaultencoding()
62
63 if isinstance(f_in, int):
64 self.input_fd = f_in
65 else:
66 self.input_fd = f_in.fileno()
67
68 if isinstance(f_out, int):
69 self.output_fd = f_out
70 else:
71 self.output_fd = f_out.fileno()
72
73 @abstractmethod
74 def refresh(self, screen: list[str], xy: tuple[int, int]) -> None: ...
75
76 @abstractmethod
77 def prepare(self) -> None: ...
78
79 @abstractmethod
80 def restore(self) -> None: ...
81
82 @abstractmethod
83 def move_cursor(self, x: int, y: int) -> None: ...
84
85 @abstractmethod
86 def set_cursor_vis(self, visible: bool) -> None: ...
87
88 @abstractmethod
89 def getheightwidth(self) -> tuple[int, int]:
90 """Return (height, width) where height and width are the height
91 and width of the terminal window in characters."""
92 ...
93
94 @abstractmethod
95 def get_event(self, block: bool = True) -> Event | None:
96 """Return an Event instance. Returns None if |block| is false
97 and there is no event pending, otherwise waits for the
98 completion of an event."""
99 ...
100
101 @abstractmethod
102 def push_char(self, char: int | bytes) -> None:
103 """
104 Push a character to the console event queue.
105 """
106 ...
107
108 @abstractmethod
109 def beep(self) -> None: ...
110
111 @abstractmethod
112 def clear(self) -> None:
113 """Wipe the screen"""
114 ...
115
116 @abstractmethod
117 def finish(self) -> None:
118 """Move the cursor to the end of the display and otherwise get
119 ready for end. XXX could be merged with restore? Hmm."""
120 ...
121
122 @abstractmethod
123 def flushoutput(self) -> None:
124 """Flush all output to the screen (assuming there's some
125 buffering going on somewhere)."""
126 ...
127
128 @abstractmethod
129 def forgetinput(self) -> None:
130 """Forget all pending, but not yet processed input."""
131 ...
132
133 @abstractmethod
134 def getpending(self) -> Event:
135 """Return the characters that have been typed but not yet
136 processed."""
137 ...
138
139 @abstractmethod
140 def wait(self, timeout: float | None) -> bool:
141 """Wait for an event. The return value is True if an event is
142 available, False if the timeout has been reached. If timeout is
143 None, wait forever. The timeout is in milliseconds."""
144 ...
145
146 @property
147 def input_hook(self) -> Callable[[], int] | None:
148 """Returns the current input hook."""
149 ...
150
151 @abstractmethod
152 def repaint(self) -> None: ...
153
154
155 class InteractiveColoredConsole(code.InteractiveConsole):
156 STATEMENT_FAILED = object()
157
158 def __init__(
159 self,
160 locals: dict[str, object] | None = None,
161 filename: str = "<console>",
162 *,
163 local_exit: bool = False,
164 ) -> None:
165 super().__init__(locals=locals, filename=filename, local_exit=local_exit)
166 self.can_colorize = _colorize.can_colorize()
167
168 def showsyntaxerror(self, filename=None, **kwargs):
169 super().showsyntaxerror(filename=filename, **kwargs)
170
171 def _excepthook(self, typ, value, tb):
172 import traceback
173 lines = traceback.format_exception(
174 typ, value, tb,
175 colorize=self.can_colorize,
176 limit=traceback.BUILTIN_EXCEPTION_LIMIT)
177 self.write(''.join(lines))
178
179 def runcode(self, code):
180 try:
181 exec(code, self.locals)
182 except SystemExit:
183 raise
184 except BaseException:
185 self.showtraceback()
186 return self.STATEMENT_FAILED
187 return None
188
189 def runsource(self, source, filename="<input>", symbol="single"):
190 try:
191 tree = self.compile.compiler(
192 source,
193 filename,
194 "exec",
195 ast.PyCF_ONLY_AST,
196 incomplete_input=False,
197 )
198 except (SyntaxError, OverflowError, ValueError):
199 self.showsyntaxerror(filename, source=source)
200 return False
201 if tree.body:
202 *_, last_stmt = tree.body
203 for stmt in tree.body:
204 wrapper = ast.Interactive if stmt is last_stmt else ast.Module
205 the_symbol = symbol if stmt is last_stmt else "exec"
206 item = wrapper([stmt])
207 try:
208 code = self.compile.compiler(item, filename, the_symbol)
209 linecache._register_code(code, source, filename)
210 except SyntaxError as e:
211 if e.args[0] == "'await' outside function":
212 python = os.path.basename(sys.executable)
213 e.add_note(
214 f"Try the asyncio REPL ({python} -m asyncio) to use"
215 f" top-level 'await' and run background asyncio tasks."
216 )
217 self.showsyntaxerror(filename, source=source)
218 return False
219 except (OverflowError, ValueError):
220 self.showsyntaxerror(filename, source=source)
221 return False
222
223 if code is None:
224 return True
225
226 result = self.runcode(code)
227 if result is self.STATEMENT_FAILED:
228 break
229 return False