-
Notifications
You must be signed in to change notification settings - Fork 11
/
detect-size.py
executable file
·49 lines (36 loc) · 1.26 KB
/
detect-size.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/env python3
# detect-size - detect and set real height/width of a terminal
#
# replacement for xterm's resize command for systems that
# don't package it separately (e.g. in xterm-resize as Fedora does)
#
# useful for terminals that are attached to a serial line,
# including emulated ones (e.g. on a VM)
#
# SPDX-License-Identifier: GPL-3.0-or-later
# SPDX-FileCopyrightText: © 2021 Georg Sauthoff <[email protected]>
import fcntl
import os
import struct
import sys
import termios
import tty
def main():
# source: https://sources.debian.org/src/xterm/366-1/resize.c/?hl=137#L139
print('\x1b' '7' '\x1b' '[r' '\x1b' '[9999;9999H' '\x1b' '[6n',
flush=True, end='')
# cf. https://stackoverflow.com/q/40931467/427158
bak = termios.tcgetattr(sys.stdin.fileno())
tty.setcbreak(sys.stdin.fileno())
r = b''.join(iter(lambda : os.read(sys.stdin.fileno(), 1), b'R'))
termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, bak)
i = r.rindex(b'[')
j = r.index(b';')
h = int(r[i+1:j])
w = int(r[j+1:])
x = struct.pack('HHHH', h, w, 0, 0)
print(f'\rheight: {h}, width: {w}')
fcntl.ioctl(sys.stdout, termios.TIOCSWINSZ, x)
# alternatively: ioctl() on /dev/tty
if __name__ == '__main__':
sys.exit(main())