diff --git a/kitty.py b/kitty.py index ded95da..146b469 100755 --- a/kitty.py +++ b/kitty.py @@ -10,9 +10,11 @@ import fcntl def draw_to_terminal(buffer: BytesIO) -> None: + '''Display a PNG image in the terminal.''' write_chunked(a="T", i=1, f=100, q=2, data=buffer.getvalue()) def get_terminal_cell_size() -> tuple[int, int]: + '''Get (height, width) of a single cell in px''' reply = _query_terminal("\x1b[16t", "t") match = re.search(r"\[6;(\d+);(\d+)t", reply) @@ -24,6 +26,7 @@ def get_terminal_cell_size() -> tuple[int, int]: raise ValueError("Failed to parse terminal cell size response") def get_terminal_size_pixel() -> tuple[int, int]: + '''Get (height, width) of the terminal in px''' reply = _query_terminal("\x1b[14t", "t") match = re.search(r"\[4;(\d+);(\d+)t", reply) @@ -34,6 +37,7 @@ def get_terminal_size_pixel() -> tuple[int, int]: raise ValueError("Failed to parse terminal pixel size response") def get_terminal_size() -> tuple[int, int]: + '''Get (rows, cols) of the terminal''' buf = array.array('H', [0, 0, 0, 0]) fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, buf) rows, cols, width, height = buf @@ -63,14 +67,17 @@ def write_chunked(**cmd) -> None: def hide_cursor() -> None: + '''Tell the terminal to hide the cursor.''' _write_stdout("\x1b[?25l") def show_cursor() -> None: + '''Tell the terminal to show the cursor.''' _write_stdout("\x1b[?25h") def set_position(y: int, x: int) -> None: + '''Set the cursor position to y, x''' _write_stdout(f"\x1b[{y};{x}H") def _write_stdout(cmd: str) -> None: @@ -78,6 +85,10 @@ def _write_stdout(cmd: str) -> None: sys.stdout.flush() def _query_terminal(escape: str, endchar: str) -> str: + ''' + Send `escape` to the terminal, read the response until + `endchar`, return response (including `endchar`) + ''' # Save the current terminal settings fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) @@ -85,10 +96,8 @@ def _query_terminal(escape: str, endchar: str) -> str: try: # Set terminal to raw mode tty.setraw(fd) - # Send the ESC[6n command to request cursor position _write_stdout(escape) - # Read the response: ESC [ row ; col R response = "" while True: ch = sys.stdin.read(1) @@ -102,6 +111,7 @@ def _query_terminal(escape: str, endchar: str) -> str: return response def get_position() -> tuple[int, int]: + '''Get the (y, x) position of the cursor''' reply = _query_terminal("\x1b[6n", "R") match = re.search(r"\[(\d+);(\d+)R", reply)