_windows.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import sys
  2. from dataclasses import dataclass
  3. @dataclass
  4. class WindowsConsoleFeatures:
  5. """Windows features available."""
  6. vt: bool = False
  7. """The console supports VT codes."""
  8. truecolor: bool = False
  9. """The console supports truecolor."""
  10. try:
  11. import ctypes
  12. from ctypes import LibraryLoader
  13. if sys.platform == "win32":
  14. windll = LibraryLoader(ctypes.WinDLL)
  15. else:
  16. windll = None
  17. raise ImportError("Not windows")
  18. from pip._vendor.rich._win32_console import (
  19. ENABLE_VIRTUAL_TERMINAL_PROCESSING,
  20. GetConsoleMode,
  21. GetStdHandle,
  22. LegacyWindowsError,
  23. )
  24. except (AttributeError, ImportError, ValueError):
  25. # Fallback if we can't load the Windows DLL
  26. def get_windows_console_features() -> WindowsConsoleFeatures:
  27. features = WindowsConsoleFeatures()
  28. return features
  29. else:
  30. def get_windows_console_features() -> WindowsConsoleFeatures:
  31. """Get windows console features.
  32. Returns:
  33. WindowsConsoleFeatures: An instance of WindowsConsoleFeatures.
  34. """
  35. handle = GetStdHandle()
  36. try:
  37. console_mode = GetConsoleMode(handle)
  38. success = True
  39. except LegacyWindowsError:
  40. console_mode = 0
  41. success = False
  42. vt = bool(success and console_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING)
  43. truecolor = False
  44. if vt:
  45. win_version = sys.getwindowsversion()
  46. truecolor = win_version.major > 10 or (
  47. win_version.major == 10 and win_version.build >= 15063
  48. )
  49. features = WindowsConsoleFeatures(vt=vt, truecolor=truecolor)
  50. return features
  51. if __name__ == "__main__":
  52. import platform
  53. features = get_windows_console_features()
  54. from pip._vendor.rich import print
  55. print(f'platform="{platform.system()}"')
  56. print(repr(features))