Skip to content

Commit 58da2dc

Browse files
committed
gh-119842: Honor PyOS_InputHook in the new REPL
Signed-off-by: Pablo Galindo <pablogsal@gmail.com>
1 parent b9965ef commit 58da2dc

File tree

8 files changed

+150
-11
lines changed

8 files changed

+150
-11
lines changed

Lib/_pyrepl/console.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929

3030
if TYPE_CHECKING:
3131
from typing import IO
32+
from typing import Callable
3233

3334

3435
@dataclass
@@ -130,9 +131,16 @@ def getpending(self) -> Event:
130131
...
131132

132133
@abstractmethod
133-
def wait(self) -> None:
134-
"""Wait for an event."""
134+
def wait(self, timeout: float | None) -> bool:
135+
"""Wait for an event. The return value is True if an event is
136+
available, False if the timeout has been reached. If timeout is
137+
None, wait forever. The timeout is in milliseconds."""
135138
...
136139

137140
@abstractmethod
138141
def repaint(self) -> None: ...
142+
143+
@property
144+
def input_hook(self) -> Callable[[], int]:
145+
"""Returns the current input hook."""
146+
...

Lib/_pyrepl/reader.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -643,7 +643,15 @@ def handle1(self, block: bool = True) -> bool:
643643
self.dirty = True
644644

645645
while True:
646-
event = self.console.get_event(block)
646+
input_hook = self.console.input_hook
647+
if input_hook:
648+
input_hook()
649+
# We use the same timeout as in readline.c: 100ms
650+
while not self.console.wait(100):
651+
input_hook()
652+
event = self.console.get_event(block=False)
653+
else:
654+
event = self.console.get_event(block)
647655
if not event: # can only happen if we're not blocking
648656
return False
649657

Lib/_pyrepl/unix_console.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -118,9 +118,12 @@ def __init__(self):
118118

119119
def register(self, fd, flag):
120120
self.fd = fd
121-
122-
def poll(self): # note: a 'timeout' argument would be *milliseconds*
123-
r, w, e = select.select([self.fd], [], [])
121+
# note: The 'timeout' argument is received as *milliseconds*
122+
def poll(self, timeout: float | None = None):
123+
if timeout is None:
124+
r, w, e = select.select([self.fd], [], [])
125+
else:
126+
r, w, e = select.select([self.fd], [], [], timeout/1000)
124127
return r
125128

126129
poll = MinimalPoll # type: ignore[assignment]
@@ -385,11 +388,11 @@ def get_event(self, block: bool = True) -> Event | None:
385388
break
386389
return self.event_queue.get()
387390

388-
def wait(self):
391+
def wait(self, timeout: float | None = None) -> bool:
389392
"""
390393
Wait for events on the console.
391394
"""
392-
self.pollob.poll()
395+
return bool(self.pollob.poll(timeout))
393396

394397
def set_cursor_vis(self, visible):
395398
"""
@@ -527,6 +530,15 @@ def clear(self):
527530
self.__posxy = 0, 0
528531
self.screen = []
529532

533+
@property
534+
def input_hook(self):
535+
try:
536+
import posix
537+
except ImportError:
538+
return None
539+
if posix._is_inputhook_installed():
540+
return posix._inputhook
541+
530542
def __enable_bracketed_paste(self) -> None:
531543
os.write(self.output_fd, b"\x1b[?2004h")
532544

Lib/_pyrepl/windows_console.py

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
from multiprocessing import Value
2424
import os
2525
import sys
26+
import time
27+
import msvcrt
2628

2729
from abc import ABC, abstractmethod
2830
from collections import deque
@@ -202,6 +204,15 @@ def refresh(self, screen: list[str], c_xy: tuple[int, int]) -> None:
202204
self.screen = screen
203205
self.move_cursor(cx, cy)
204206

207+
@property
208+
def input_hook(self):
209+
try:
210+
import nt
211+
except ImportError:
212+
return None
213+
if nt._is_inputhook_installed():
214+
return nt._inputhook
215+
205216
def __write_changed_line(
206217
self, y: int, oldline: str, newline: str, px_coord: int
207218
) -> None:
@@ -460,9 +471,16 @@ def getpending(self) -> Event:
460471
processed."""
461472
return Event("key", "", b"")
462473

463-
def wait(self) -> None:
474+
def wait(self, timeout: float | None) -> bool:
464475
"""Wait for an event."""
465-
raise NotImplementedError("No wait support")
476+
# Poor man's Windows select loop
477+
start_time = time.time()
478+
while True:
479+
if msvcrt.kbhit():
480+
return True
481+
if timeout and time.time() - start_time > timeout:
482+
return False
483+
time.sleep(0.01)
466484

467485
def repaint(self) -> None:
468486
raise NotImplementedError("No repaint support")

Lib/test/test_pyrepl/test_reader.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import itertools
22
import functools
33
from unittest import TestCase
4+
from unittest.mock import MagicMock
45

56
from .support import handle_all_events, handle_events_narrow_console, code_to_events, prepare_reader
7+
from test.support import import_helper
68
from _pyrepl.console import Event
79

810

@@ -176,3 +178,24 @@ def test_newline_within_block_trailing_whitespace(self):
176178
)
177179
self.assert_screen_equals(reader, expected)
178180
self.assertTrue(reader.finished)
181+
182+
def test_input_hook_is_called_if_set(self):
183+
import_helper.import_module('ctypes')
184+
from ctypes import pythonapi, c_int, CFUNCTYPE, c_void_p, POINTER, cast
185+
186+
CMPFUNC = CFUNCTYPE(c_int)
187+
the_mock = MagicMock()
188+
189+
def input_hook():
190+
the_mock()
191+
return 0
192+
193+
the_input_hook = CMPFUNC(input_hook)
194+
prev_value = c_void_p.in_dll(pythonapi, "PyOS_InputHook").value
195+
try:
196+
c_void_p.in_dll(pythonapi, "PyOS_InputHook").value = cast(the_input_hook, c_void_p).value
197+
events = code_to_events("a")
198+
reader, _ = handle_all_events(events)
199+
the_mock.assert_called()
200+
finally:
201+
c_void_p.in_dll(pythonapi, "PyOS_InputHook").value = prev_value
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Honor :c:func:`PyOS_InputHook` in the new REPL. Patch by Pablo Galindo

Modules/clinic/posixmodule.c.h

Lines changed: 37 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Modules/posixmodule.c

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16726,6 +16726,37 @@ os__supports_virtual_terminal_impl(PyObject *module)
1672616726
}
1672716727
#endif
1672816728

16729+
/*[clinic input]
16730+
os._inputhook
16731+
16732+
Calls PyOS_CallInputHook droppong the GIL first
16733+
[clinic start generated code]*/
16734+
16735+
static PyObject *
16736+
os__inputhook_impl(PyObject *module)
16737+
/*[clinic end generated code: output=525aca4ef3c6149f input=fc531701930d064f]*/
16738+
{
16739+
int result = 0;
16740+
if (PyOS_InputHook) {
16741+
Py_BEGIN_ALLOW_THREADS;
16742+
result = PyOS_InputHook();
16743+
Py_END_ALLOW_THREADS;
16744+
}
16745+
return PyLong_FromLong(result);
16746+
}
16747+
16748+
/*[clinic input]
16749+
os._is_inputhook_installed
16750+
16751+
Checks if PyOS_CallInputHook is set
16752+
[clinic start generated code]*/
16753+
16754+
static PyObject *
16755+
os__is_inputhook_installed_impl(PyObject *module)
16756+
/*[clinic end generated code: output=3b3eab4f672c689a input=ff177c9938dd76d8]*/
16757+
{
16758+
return PyBool_FromLong(PyOS_InputHook != NULL);
16759+
}
1672916760

1673016761
static PyMethodDef posix_methods[] = {
1673116762

@@ -16939,6 +16970,8 @@ static PyMethodDef posix_methods[] = {
1693916970
OS__PATH_LEXISTS_METHODDEF
1694016971

1694116972
OS__SUPPORTS_VIRTUAL_TERMINAL_METHODDEF
16973+
OS__INPUTHOOK_METHODDEF
16974+
OS__IS_INPUTHOOK_INSTALLED_METHODDEF
1694216975
{NULL, NULL} /* Sentinel */
1694316976
};
1694416977

0 commit comments

Comments
 (0)