|
| 1 | +""" |
| 2 | +This module provides a method to detect if a given file object supports virtual terminal escape codes. |
| 3 | +""" |
| 4 | +import os |
| 5 | +import sys |
| 6 | +from typing import IO |
| 7 | + |
| 8 | +if os.name == "nt": |
| 9 | + from ctypes import byref, windll # type: ignore |
| 10 | + from ctypes.wintypes import BOOL, DWORD, HANDLE, LPDWORD |
| 11 | + |
| 12 | + ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004 |
| 13 | + STD_OUTPUT_HANDLE = -11 |
| 14 | + STD_ERROR_HANDLE = -12 |
| 15 | + |
| 16 | + # https://docs.microsoft.com/de-de/windows/console/getstdhandle |
| 17 | + GetStdHandle = windll.kernel32.GetStdHandle |
| 18 | + GetStdHandle.argtypes = [DWORD] |
| 19 | + GetStdHandle.restype = HANDLE |
| 20 | + |
| 21 | + # https://docs.microsoft.com/de-de/windows/console/getconsolemode |
| 22 | + GetConsoleMode = windll.kernel32.GetConsoleMode |
| 23 | + GetConsoleMode.argtypes = [HANDLE, LPDWORD] |
| 24 | + GetConsoleMode.restype = BOOL |
| 25 | + |
| 26 | + # https://docs.microsoft.com/de-de/windows/console/setconsolemode |
| 27 | + SetConsoleMode = windll.kernel32.SetConsoleMode |
| 28 | + SetConsoleMode.argtypes = [HANDLE, DWORD] |
| 29 | + SetConsoleMode.restype = BOOL |
| 30 | + |
| 31 | + def ensure_supported(f: IO[str]) -> bool: |
| 32 | + if not f.isatty(): |
| 33 | + return False |
| 34 | + if f == sys.stdout: |
| 35 | + h = STD_OUTPUT_HANDLE |
| 36 | + elif f == sys.stderr: |
| 37 | + h = STD_ERROR_HANDLE |
| 38 | + else: |
| 39 | + return False |
| 40 | + |
| 41 | + handle = GetStdHandle(h) |
| 42 | + console_mode = DWORD() |
| 43 | + ok = GetConsoleMode(handle, byref(console_mode)) |
| 44 | + if not ok: |
| 45 | + return False |
| 46 | + |
| 47 | + ok = SetConsoleMode(handle, console_mode.value | ENABLE_VIRTUAL_TERMINAL_PROCESSING) |
| 48 | + return ok |
| 49 | +else: |
| 50 | + def ensure_supported(f: IO[str]) -> bool: |
| 51 | + return f.isatty() |
0 commit comments