From b1c0398bba156d86f88a75466054b7b750202420 Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Sun, 31 Oct 2021 14:04:07 +0530 Subject: [PATCH] Avoid unnecessary CPU churn when reading from stdin for @ send-text --- kitty/rc/send_text.py | 6 +++++- kitty/utils.py | 10 +++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/kitty/rc/send_text.py b/kitty/rc/send_text.py index 1a583cb7b..6067efc03 100644 --- a/kitty/rc/send_text.py +++ b/kitty/rc/send_text.py @@ -69,9 +69,13 @@ Do not send text to the active window, even if it is one of the matched windows. ret['exclude_active'] = True keep_going = True from kitty.utils import TTYIO - with TTYIO() as tty: + with TTYIO(read_with_timeout=False) as tty: while keep_going: + if not tty.wait_till_read_available(): + break data = os.read(tty.tty_fd, limit) + if not data: + break decoded_data = data.decode('utf-8') if '\x04' in decoded_data: decoded_data = decoded_data[:decoded_data.index('\x04')] diff --git a/kitty/utils.py b/kitty/utils.py index 150545dfe..ba9ca853a 100644 --- a/kitty/utils.py +++ b/kitty/utils.py @@ -442,15 +442,23 @@ def write_all(fd: int, data: Union[str, bytes]) -> None: class TTYIO: + def __init__(self, read_with_timeout: bool = True): + self.read_with_timeout = read_with_timeout + def __enter__(self) -> 'TTYIO': from .fast_data_types import open_tty - self.tty_fd, self.original_termios = open_tty(True) + self.tty_fd, self.original_termios = open_tty(self.read_with_timeout) return self def __exit__(self, *a: Any) -> None: from .fast_data_types import close_tty close_tty(self.tty_fd, self.original_termios) + def wait_till_read_available(self) -> bool: + import select + rd = select.select([self.tty_fd], [], [])[0] + return bool(rd) + def send(self, data: Union[str, bytes, Iterable[Union[str, bytes]]]) -> None: if isinstance(data, (str, bytes)): write_all(self.tty_fd, data)