color_util.py 5.5 KB

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