Rename gsh to polysh.
[gsh.git] / polysh / terminal_size.py
blob6fdefd0344f8aaa44fa6cb13c8758ba94f1d99de
1 # from http://pdos.csail.mit.edu/~cblake/cls/cls.py
2 # License in http://pdos.csail.mit.edu/~cblake/cls/cls_py_LICENSE reproduced
3 # thereafter:
4 # I, Charles Blake, hereby relinquish all rights to the functions
5 # terminal_size() and ioctl_GWINSZ() in file cls.py, located in this
6 # same code directory to the maximum extent applicable by this notice.
8 # These functions are provided "as is" and without any expressed or implied
9 # warranties, including, without limitation, the implied warranties of
10 # merchantibility and fitness for a particular purpose.
12 # It would be nice (but not necessary) to give me an artistic license credit
13 # somewhere in the licensing materials of any derivative product.
16 import os
18 def _ioctl_GWINSZ(fd): #### TABULATION FUNCTIONS
19 try: ### Discover terminal width
20 import fcntl
21 import termios
22 import struct
23 cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
24 except:
25 return
26 return cr
28 def terminal_size(): ### decide on *some* terminal size
29 """Return (lines, columns)."""
30 cr = _ioctl_GWINSZ(0) or _ioctl_GWINSZ(1) or _ioctl_GWINSZ(2) # try open fds
31 if not cr: # ...then ctty
32 try:
33 fd = os.open(os.ctermid(), os.O_RDONLY)
34 cr = _ioctl_GWINSZ(fd)
35 os.close(fd)
36 except:
37 pass
38 if not cr: # env vars or finally defaults
39 try:
40 cr = os.environ['LINES'], os.environ['COLUMNS']
41 except:
42 cr = 25, 80
43 return int(cr[1]), int(cr[0]) # reverse rows, cols