~bzr-pqm/bzr/bzr.dev

1185.16.86 by mbp at sourcefrog
- win32 get_console_size from Alexander
1
"""
2
Set of functions to work with console on Windows.
3
Author: Alexander Belchenko (e-mail: bialix AT ukr.net)
4
License: Public domain
5
"""
6
7
import struct
8
9
try:
10
   import ctypes
11
except ImportError:
12
   ctypes = None
13
14
15
WIN32_STDIN_HANDLE = -10
1704.2.3 by Martin Pool
(win32) Detect terminal width using GetConsoleScreenBufferInfo (Alexander)
16
WIN32_STDOUT_HANDLE = -11
17
WIN32_STDERR_HANDLE = -12
18
19
20
def get_console_size(defaultx=80, defaulty=25):
1185.16.86 by mbp at sourcefrog
- win32 get_console_size from Alexander
21
   """ Return size of current console.
22
23
   This function try to determine actual size of current working
24
   console window and return tuple (sizex, sizey) if success,
25
   or default size (defaultx, defaulty) otherwise.
26
27
   Dependencies: ctypes should be installed.
28
   """
29
   if ctypes is None:
30
       # no ctypes is found
31
       return (defaultx, defaulty)
32
33
   # To avoid problem with redirecting output via pipe
1704.2.3 by Martin Pool
(win32) Detect terminal width using GetConsoleScreenBufferInfo (Alexander)
34
   # need to use stderr instead of stdout
35
   h = ctypes.windll.kernel32.GetStdHandle(WIN32_STDERR_HANDLE)
36
   csbi = ctypes.create_string_buffer(22)
1185.16.86 by mbp at sourcefrog
- win32 get_console_size from Alexander
37
   res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
38
39
   if res:
40
       (bufx, bufy, curx, cury, wattr,
41
        left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
42
       sizex = right - left + 1
43
       sizey = bottom - top + 1
44
       return (sizex, sizey)
45
   else:
46
       return (defaultx, defaulty)
47