color_util.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. from __future__ import annotations
  2. import colorsys
  3. from typing import NamedTuple
  4. from typing_extensions import Literal
  5. from .constants import GLOBAL_CFG
  6. AnsiMode = Literal['default', 'ansi', '8bit', 'rgb']
  7. MINECRAFT_COLORS = ["&0/\033[0;30m", "&1/\033[0;34m", "&2/\033[0;32m", "&3/\033[0;36m", "&4/\033[0;31m",
  8. "&5/\033[0;35m", "&6/\033[0;33m", "&7/\033[0;37m", "&8/\033[1;30m", "&9/\033[1;34m",
  9. "&a/\033[1;32m", "&b/\033[1;36m", "&c/\033[1;31m", "&d/\033[1;35m", "&e/\033[1;33m",
  10. "&f/\033[1;37m",
  11. "&r/\033[0m", "&l/\033[1m", "&o/\033[3m", "&n/\033[4m", "&-/\n"]
  12. MINECRAFT_COLORS = [(r[:2], r[3:]) for r in MINECRAFT_COLORS]
  13. def color(msg: str) -> str:
  14. """
  15. Replace extended minecraft color codes in string
  16. :param msg: Message with minecraft color codes
  17. :return: Message with escape codes
  18. """
  19. for code, esc in MINECRAFT_COLORS:
  20. msg = msg.replace(code, esc)
  21. while '&gf(' in msg or '&gb(' in msg:
  22. i = msg.index('&gf(') if '&gf(' in msg else msg.index('&gb(')
  23. end = msg.index(')', i)
  24. code = msg[i + 4:end]
  25. fore = msg[i + 2] == 'f'
  26. if code.startswith('#'):
  27. rgb = tuple(int(code.lstrip('#')[i:i+2], 16) for i in (0, 2, 4))
  28. else:
  29. code = code.replace(',', ' ').replace(';', ' ').replace(' ', ' ')
  30. rgb = tuple(int(c) for c in code.split(' '))
  31. msg = msg[:i] + RGB(*rgb).to_ansi(foreground=fore) + msg[end + 1:]
  32. return msg
  33. def printc(msg: str):
  34. """
  35. Print with color
  36. :param msg: Message with minecraft color codes
  37. """
  38. print(color(msg + '&r'))
  39. def clear_screen(title: str = ''):
  40. """
  41. Clear screen using ANSI escape codes
  42. """
  43. if not GLOBAL_CFG.debug:
  44. print('\033[2J\033[H', end='')
  45. if title:
  46. print()
  47. printc(title)
  48. print()
  49. def redistribute_rgb(r: int, g: int, b: int) -> tuple[int, int, int]:
  50. """
  51. Redistribute RGB after lightening
  52. Credit: https://stackoverflow.com/a/141943/7346633
  53. """
  54. threshold = 255.999
  55. m = max(r, g, b)
  56. if m <= threshold:
  57. return int(r), int(g), int(b)
  58. total = r + g + b
  59. if total >= 3 * threshold:
  60. return int(threshold), int(threshold), int(threshold)
  61. x = (3 * threshold - total) / (3 * m - total)
  62. gray = threshold - x * m
  63. return int(gray + x * r), int(gray + x * g), int(gray + x * b)
  64. class RGB(NamedTuple):
  65. r: int
  66. g: int
  67. b: int
  68. @classmethod
  69. def from_hex(cls, hex: str) -> "RGB":
  70. """
  71. Create color from hex code
  72. >>> RGB.from_hex('#FFAAB7')
  73. RGB(r=255, g=170, b=183)
  74. :param hex: Hex color code
  75. :return: RGB object
  76. """
  77. while hex.startswith('#'):
  78. hex = hex[1:]
  79. r = int(hex[0:2], 16)
  80. g = int(hex[2:4], 16)
  81. b = int(hex[4:6], 16)
  82. return cls(r, g, b)
  83. def to_ansi_rgb(self, foreground: bool = True) -> str:
  84. """
  85. Convert RGB to ANSI TrueColor (RGB) Escape Code.
  86. This uses the 24-bit color encoding (an uint8 for each color value), and supports 16 million
  87. colors. However, not all terminal emulators support this escape code. (For example, IntelliJ
  88. debug console doesn't support it).
  89. Currently, we do not know how to detect whether a terminal environment supports ANSI RGB. If
  90. you have any thoughts, feel free to submit an issue on our Github page!
  91. :param foreground: Whether the color is for foreground text or background color
  92. :return: ANSI RGB escape code like \033[38;2;255;100;0m
  93. """
  94. c = '38' if foreground else '48'
  95. return f'\033[{c};2;{self.r};{self.g};{self.b}m'
  96. def to_ansi_8bit(self, foreground: bool = True) -> str:
  97. """
  98. Convert RGB to ANSI 8bit 256 Color Escape Code.
  99. This encoding supports 256 colors in total.
  100. :return: ANSI 256 escape code like \033[38;5;206m'
  101. """
  102. r, g, b = self.r, self.g, self.b
  103. sep = 42.5
  104. while True:
  105. if r < sep or g < sep or b < sep:
  106. gray = r < sep and g < sep and b < sep
  107. break
  108. sep += 42.5
  109. if gray:
  110. color = 232 + (r + g + b) / 33
  111. else:
  112. color = 16 + int(r / 256. * 6) * 36 + int(g / 256. * 6) * 6 + int(b / 256. * 6)
  113. c = '38' if foreground else '48'
  114. return f'\033[{c};5;{int(color)}m'
  115. def to_ansi_16(self, foreground: bool = True) -> str:
  116. """
  117. Convert RGB to ANSI 16 Color Escape Code
  118. :return: ANSI 16 escape code
  119. """
  120. raise NotImplementedError()
  121. def to_ansi(self, mode: AnsiMode | None = None, foreground: bool = True):
  122. if not mode:
  123. mode = GLOBAL_CFG.color_mode
  124. if mode == 'rgb':
  125. return self.to_ansi_rgb(foreground)
  126. if mode == '8bit':
  127. return self.to_ansi_8bit(foreground)
  128. if mode == 'ansi':
  129. return self.to_ansi_16(foreground)
  130. def lighten(self, multiplier: float) -> 'RGB':
  131. """
  132. Lighten the color by a multiplier
  133. :param multiplier: Multiplier
  134. :return: Lightened color (original isn't modified)
  135. """
  136. return RGB(*redistribute_rgb(*[v * multiplier for v in self]))
  137. def set_light(self, light: float) -> 'RGB':
  138. """
  139. Set HSL lightness value
  140. :param light: Lightness value (0-1)
  141. :return: New color (original isn't modified)
  142. """
  143. h, l, s = colorsys.rgb_to_hls(*[v / 255.0 for v in self])
  144. return RGB(*[round(v * 255.0) for v in colorsys.hls_to_rgb(h, light, s)])
  145. def set_min_light(self, light: float) -> 'RGB':
  146. h, l, s = colorsys.rgb_to_hls(*[v / 255.0 for v in self])
  147. return RGB(*[round(v * 255.0) for v in colorsys.hls_to_rgb(h, max(l, light), s)])