color_util.py 5.5 KB

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