I'm trying to write a function that would produce a simple widget when run in Python's console. This widget should be terminal-size-aware. After displaying the widget I will wait for user's keyboard input and adjust the content according to what the types. The difficulty that I have right now is how to make that widget adjust its display when the user resizes the terminal. Here's a simplified version of the code that I have right now:
def test():
import blessed
import signal
def draw():
n = term.width - 3
print("+" + "=" * n + "+" + term.clear_eol)
print("|" + " " * (n//2 - 2) +
"TEST" + " " * (n - n//2 - 2) + "|" + term.clear_eol)
print("+" + "=" * n + "+" + term.clear_eol)
def redraw(_, __):
print(term.move_up * 3, end="")
draw()
term = blessed.Terminal()
draw()
signal.signal(signal.SIGWINCH, redraw)
with term.cbreak():
term.inkey()
This works fine if the user expands the terminal, or if he shrinks the terminal but very slowly (1 character at a time). However reducing the terminal width quickly will cause long lines to wrap, corrupting the output. Is there a way to address this problem?