Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement screen clear for Windows #42

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Lib/_pyrepl/pager.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def get_pager() -> Pager:
if os.environ.get('TERM') in ('dumb', 'emacs'):
return plain_pager
if sys.platform == 'win32':
return lambda text, title='': tempfilepager(plain(text), 'more <')
return lambda text, title='': tempfile_pager(plain(text), 'more <')
if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
return lambda text, title='': pipe_pager(text, 'less', title)

Expand Down
16 changes: 7 additions & 9 deletions Lib/_pyrepl/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -407,14 +407,13 @@ def get_arg(self, default: int = 1) -> int:
"""
if self.arg is None:
return default
else:
return self.arg
return self.arg

def get_prompt(self, lineno: int, cursor_on_line: bool) -> str:
"""Return what should be in the left-hand margin for line
`lineno'."""
if self.arg is not None and cursor_on_line:
prompt = "(arg: %s) " % self.arg
prompt = f"(arg: {self.arg}) "
elif self.paste_mode:
prompt = "(paste) "
elif "\n" in self.buffer:
Expand Down Expand Up @@ -480,12 +479,12 @@ def pos2xy(self) -> tuple[int, int]:
offset = l - 1 if in_wrapped_line else l # need to remove backslash
if offset >= pos:
break

if p + sum(l2) >= self.console.width:
pos -= l - 1 # -1 cause backslash is not in buffer
else:
if p + sum(l2) >= self.console.width:
pos -= l - 1 # -1 cause backslash is not in buffer
else:
pos -= l + 1 # +1 cause newline is in buffer
y += 1
pos -= l + 1 # +1 cause newline is in buffer
y += 1
return p + sum(l2[:pos]), y

def insert(self, text: str | list[str]) -> None:
Expand Down Expand Up @@ -543,7 +542,6 @@ def suspend(self) -> SimpleContextManager:
for arg in ("msg", "ps1", "ps2", "ps3", "ps4", "paste_mode"):
setattr(self, arg, prev_state[arg])
self.prepare()
pass

def finish(self) -> None:
"""Called when a command signals that we're finished."""
Expand Down
30 changes: 21 additions & 9 deletions Lib/_pyrepl/windows_console.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,11 @@ class CHAR_INFO(Structure):
FillConsoleOutputCharacter.argtypes = [HANDLE, CHAR, DWORD, _COORD, POINTER(DWORD)]
FillConsoleOutputCharacter.restype = BOOL

FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute
FillConsoleOutputAttribute.use_last_error = True
FillConsoleOutputAttribute.argtypes = [HANDLE, WORD, DWORD, _COORD, POINTER(DWORD)]
FillConsoleOutputAttribute.restype = BOOL

ScrollConsoleScreenBuffer = windll.kernel32.ScrollConsoleScreenBufferW
ScrollConsoleScreenBuffer.use_last_error = True
ScrollConsoleScreenBuffer.argtypes = [HANDLE, POINTER(SMALL_RECT), POINTER(SMALL_RECT), _COORD, POINTER(CHAR_INFO)]
Expand All @@ -99,7 +104,7 @@ class CHAR_INFO(Structure):
class Char(Union):
_fields_ = [
("UnicodeChar",WCHAR),
("Char", CHAR),
("Char", CHAR),
]

class KeyEvent(ctypes.Structure):
Expand Down Expand Up @@ -191,7 +196,7 @@ def __init__(
term: str = "",
encoding: str = "",
):

SetConsoleMode(OutHandle, ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING)
self.encoding = encoding or sys.getdefaultencoding()

Expand Down Expand Up @@ -487,14 +492,14 @@ def move_cursor(self, x: int, y: int) -> None:
trace(f'move to {x} {y}')

if x < 0 or y < 0:
raise ValueError(f"Bad cussor position {x}, {y}")
raise ValueError(f"Bad cursor position {x}, {y}")

self.__move(x, y)
self.__posxy = x, y
self.flushoutput()


def set_cursor_vis(self, visible: bool) -> None:

def set_cursor_vis(self, visible: bool) -> None:
if visible:
self.__show_cursor()
else:
Expand All @@ -506,9 +511,9 @@ def getheightwidth(self) -> tuple[int, int]:
info = CONSOLE_SCREEN_BUFFER_INFO()
if not GetConsoleScreenBufferInfo(OutHandle, info):
raise ctypes.WinError(ctypes.GetLastError())
return (info.srWindow.Bottom - info.srWindow.Top + 1,
return (info.srWindow.Bottom - info.srWindow.Top + 1,
info.srWindow.Right - info.srWindow.Left + 1)

def get_event(self, block: bool = True) -> Event | None:
"""Return an Event instance. Returns None if |block| is false
and there is no event pending, otherwise waits for the
Expand All @@ -527,7 +532,7 @@ def get_event(self, block: bool = True) -> Event | None:
key = chr(rec.Event.KeyEvent.uChar.Char[0])
# self.push_char(key)
if rec.Event.KeyEvent.uChar.Char == b'\r':
return Event(evt="key", data="\n", raw="\n")
return Event(evt="key", data="\n", raw="\n")
trace('virtual key code', rec.Event.KeyEvent.wVirtualKeyCode, rec.Event.KeyEvent.uChar.Char)
if rec.Event.KeyEvent.wVirtualKeyCode == 8:
return Event(evt="key", data="backspace", raw=rec.Event.KeyEvent.uChar.Char)
Expand All @@ -536,7 +541,7 @@ def get_event(self, block: bool = True) -> Event | None:
if rec.Event.KeyEvent.uChar.Char == b'\x00':
code = VK_MAP.get(rec.Event.KeyEvent.wVirtualKeyCode)
if code:
return Event(evt="key", data=code, raw=rec.Event.KeyEvent.uChar.Char)
return Event(evt="key", data=code, raw=rec.Event.KeyEvent.uChar.Char)
continue
#print(key, rec.Event.KeyEvent.wVirtualKeyCode)
return Event(evt="key", data=key, raw=rec.Event.KeyEvent.uChar.Char)
Expand All @@ -557,6 +562,13 @@ def clear(self) -> None:
size = info.dwSize.X * info.dwSize.Y
if not FillConsoleOutputCharacter(OutHandle, b' ', size, _COORD(), DWORD()):
raise ctypes.WinError(ctypes.GetLastError())
if not FillConsoleOutputAttribute(OutHandle, 0, size, _COORD(), DWORD()):
raise ctypes.WinError(ctypes.GetLastError())
y = info.srWindow.Bottom - info.srWindow.Top + 1
self.__move_absolute(0, y - info.dwSize.Y)
self.__posxy = 0, 0
self.screen = [""]


def finish(self) -> None:
"""Move the cursor to the end of the display and otherwise get
Expand Down
Loading