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