- commit
- c55a4d20ed59b56e4b7a1a7ed5485e400f7c97a2
- parent
- 899180a341b5c316df4994a0d41a10fa39f0400e
- Author
- Tobias Bengfort <tobias.bengfort@posteo.de>
- Date
- 2024-07-09 06:43
simplify reusable context managers
Diffstat
| M | boon.py | 38 | ++++++++++++-------------------------- |
1 files changed, 12 insertions, 26 deletions
diff --git a/boon.py b/boon.py
@@ -7,7 +7,6 @@ import sys 7 7 import termios 8 8 import tty 9 9 from contextlib import contextmanager10 -1 from functools import wraps11 10 12 11 curses.setupterm() 13 12 @@ -48,29 +47,7 @@ def move(y, x): 48 47 sys.stdout.write(get_cap('cup', y, x)) 49 48 50 4951 -1 class ReusableContextManager:52 -1 def __init__(self, factory, *args, **kwargs):53 -1 self.factory = factory54 -1 self.args = args55 -1 self.kwargs = kwargs56 -157 -1 def __enter__(self):58 -1 self.mgr = self.factory(*self.args, **self.kwargs)59 -1 return self.mgr.__enter__()60 -161 -1 def __exit__(self, *args, **kwargs):62 -1 return self.mgr.__exit__(*args, **kwargs)63 -164 -165 -1 def reusable_contextmanager(func):66 -1 factory = contextmanager(func)67 -1 @wraps(func)68 -1 def wrapper(*args, **kwargs):69 -1 return ReusableContextManager(factory, *args, **kwargs)70 -1 return wrapper71 -172 -173 -1 @reusable_contextmanager-1 50 @contextmanager 74 51 def tty_restore(fd): 75 52 old = termios.tcgetattr(fd) 76 53 try: @@ -79,7 +56,7 @@ def tty_restore(fd): 79 56 termios.tcsetattr(fd, termios.TCSADRAIN, old) 80 57 81 5882 -1 @reusable_contextmanager-1 59 @contextmanager 83 60 def fullscreen(): 84 61 sys.stdout.write(get_cap('civis')) 85 62 sys.stdout.write(get_cap('smcup')) @@ -95,6 +72,15 @@ def fullscreen(): 95 72 sys.stdout.flush() 96 73 97 74 -1 75 class ReusableFullscreen: -1 76 def __enter__(self): -1 77 self.mgr = fullscreen() -1 78 return self.mgr.__enter__() -1 79 -1 80 def __exit__(self, *args, **kwargs): -1 81 return self.mgr.__exit__(*args, **kwargs) -1 82 -1 83 98 84 def getch(): 99 85 # NOTE: result might contain more than one key 100 86 fd = sys.stdin.fileno() @@ -112,7 +98,7 @@ class App: 112 98 self.running = False 113 99 self.timeout = 0.5 114 100 self.selector = selectors.DefaultSelector()115 -1 self.fullscreen = fullscreen()-1 101 self.fullscreen = ReusableFullscreen() 116 102 117 103 # self-pipe to avoid concurrency issues with signal 118 104 self.sig_in, self.sig_out = os.pipe2(os.O_NONBLOCK)