From 22f74b60ce285579af2848889b18ee3d1721312c Mon Sep 17 00:00:00 2001 From: Calum Lind Date: Mon, 27 Feb 2023 12:22:56 +0000 Subject: [PATCH] [Console] Cleanup terminal resize handler Improve readability Move imports available on Windows out of try..except. For future reference in Python 3.11 termios now has window size methods but the added complexity of handling older Python versions is not worth it. https://docs.python.org/3/library/termios.html#termios.tcgetwinsize --- deluge/ui/console/main.py | 4 ++-- deluge/ui/console/modes/basemode.py | 22 +++++++++++++--------- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/deluge/ui/console/main.py b/deluge/ui/console/main.py index e52d87116..af89dbf44 100644 --- a/deluge/ui/console/main.py +++ b/deluge/ui/console/main.py @@ -253,8 +253,8 @@ deluge-console.exe "add -p c:\\mytorrents c:\\new.torrent" reactor.run() @overrides(TermResizeHandler) - def on_terminal_size(self, *args): - rows, cols = super().on_terminal_size(args) + def on_resize(self, *args): + rows, cols = super().on_resize(*args) for mode in self.modes: self.modes[mode].on_resize(rows, cols) diff --git a/deluge/ui/console/modes/basemode.py b/deluge/ui/console/modes/basemode.py index 5ebaf86fe..a8ab1dbd9 100644 --- a/deluge/ui/console/modes/basemode.py +++ b/deluge/ui/console/modes/basemode.py @@ -8,7 +8,10 @@ # import logging +import signal +import struct import sys +from typing import Tuple import deluge.component as component import deluge.ui.console.utils.colors as colors @@ -22,10 +25,8 @@ except ImportError: pass try: - import signal - import struct - import termios from fcntl import ioctl + from termios import TIOCGWINSZ except ImportError: pass @@ -62,17 +63,20 @@ class InputKeyHandler: class TermResizeHandler: def __init__(self): try: - signal.signal(signal.SIGWINCH, self.on_terminal_size) + signal.signal(signal.SIGWINCH, self.on_resize) except ValueError as ex: log.debug('TermResize unavailable, unable to catch SIGWINCH signal: %s', ex) except AttributeError as ex: log.debug('TermResize unavailable, no SIGWINCH signal on Windows: %s', ex) - def on_terminal_size(self, *args): - # Get the new rows and cols value - rows, cols = struct.unpack('hhhh', ioctl(0, termios.TIOCGWINSZ, b'\000' * 8))[ - 0:2 - ] + @staticmethod + def get_window_size(fd: int = 0) -> Tuple[int, int]: + """Return the tty window size as row, col.""" + return struct.unpack('4h', ioctl(fd, TIOCGWINSZ, b'\x00' * 8))[0:2] + + def on_resize(self, _signum, _frame): + """Handler for SIGWINCH when terminal changes size""" + rows, cols = self.get_window_size() curses.resizeterm(rows, cols) return rows, cols