style_transformation.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. """
  2. Collection of style transformations.
  3. Think of it as a kind of color post processing after the rendering is done.
  4. This could be used for instance to change the contrast/saturation; swap light
  5. and dark colors or even change certain colors for other colors.
  6. When the UI is rendered, these transformations can be applied right after the
  7. style strings are turned into `Attrs` objects that represent the actual
  8. formatting.
  9. """
  10. from __future__ import annotations
  11. from abc import ABCMeta, abstractmethod
  12. from colorsys import hls_to_rgb, rgb_to_hls
  13. from typing import Callable, Hashable, Sequence
  14. from prompt_toolkit.cache import memoized
  15. from prompt_toolkit.filters import FilterOrBool, to_filter
  16. from prompt_toolkit.utils import AnyFloat, to_float, to_str
  17. from .base import ANSI_COLOR_NAMES, Attrs
  18. from .style import parse_color
  19. __all__ = [
  20. "StyleTransformation",
  21. "SwapLightAndDarkStyleTransformation",
  22. "ReverseStyleTransformation",
  23. "SetDefaultColorStyleTransformation",
  24. "AdjustBrightnessStyleTransformation",
  25. "DummyStyleTransformation",
  26. "ConditionalStyleTransformation",
  27. "DynamicStyleTransformation",
  28. "merge_style_transformations",
  29. ]
  30. class StyleTransformation(metaclass=ABCMeta):
  31. """
  32. Base class for any style transformation.
  33. """
  34. @abstractmethod
  35. def transform_attrs(self, attrs: Attrs) -> Attrs:
  36. """
  37. Take an `Attrs` object and return a new `Attrs` object.
  38. Remember that the color formats can be either "ansi..." or a 6 digit
  39. lowercase hexadecimal color (without '#' prefix).
  40. """
  41. def invalidation_hash(self) -> Hashable:
  42. """
  43. When this changes, the cache should be invalidated.
  44. """
  45. return f"{self.__class__.__name__}-{id(self)}"
  46. class SwapLightAndDarkStyleTransformation(StyleTransformation):
  47. """
  48. Turn dark colors into light colors and the other way around.
  49. This is meant to make color schemes that work on a dark background usable
  50. on a light background (and the other way around).
  51. Notice that this doesn't swap foreground and background like "reverse"
  52. does. It turns light green into dark green and the other way around.
  53. Foreground and background colors are considered individually.
  54. Also notice that when <reverse> is used somewhere and no colors are given
  55. in particular (like what is the default for the bottom toolbar), then this
  56. doesn't change anything. This is what makes sense, because when the
  57. 'default' color is chosen, it's what works best for the terminal, and
  58. reverse works good with that.
  59. """
  60. def transform_attrs(self, attrs: Attrs) -> Attrs:
  61. """
  62. Return the `Attrs` used when opposite luminosity should be used.
  63. """
  64. # Reverse colors.
  65. attrs = attrs._replace(color=get_opposite_color(attrs.color))
  66. attrs = attrs._replace(bgcolor=get_opposite_color(attrs.bgcolor))
  67. return attrs
  68. class ReverseStyleTransformation(StyleTransformation):
  69. """
  70. Swap the 'reverse' attribute.
  71. (This is still experimental.)
  72. """
  73. def transform_attrs(self, attrs: Attrs) -> Attrs:
  74. return attrs._replace(reverse=not attrs.reverse)
  75. class SetDefaultColorStyleTransformation(StyleTransformation):
  76. """
  77. Set default foreground/background color for output that doesn't specify
  78. anything. This is useful for overriding the terminal default colors.
  79. :param fg: Color string or callable that returns a color string for the
  80. foreground.
  81. :param bg: Like `fg`, but for the background.
  82. """
  83. def __init__(
  84. self, fg: str | Callable[[], str], bg: str | Callable[[], str]
  85. ) -> None:
  86. self.fg = fg
  87. self.bg = bg
  88. def transform_attrs(self, attrs: Attrs) -> Attrs:
  89. if attrs.bgcolor in ("", "default"):
  90. attrs = attrs._replace(bgcolor=parse_color(to_str(self.bg)))
  91. if attrs.color in ("", "default"):
  92. attrs = attrs._replace(color=parse_color(to_str(self.fg)))
  93. return attrs
  94. def invalidation_hash(self) -> Hashable:
  95. return (
  96. "set-default-color",
  97. to_str(self.fg),
  98. to_str(self.bg),
  99. )
  100. class AdjustBrightnessStyleTransformation(StyleTransformation):
  101. """
  102. Adjust the brightness to improve the rendering on either dark or light
  103. backgrounds.
  104. For dark backgrounds, it's best to increase `min_brightness`. For light
  105. backgrounds it's best to decrease `max_brightness`. Usually, only one
  106. setting is adjusted.
  107. This will only change the brightness for text that has a foreground color
  108. defined, but no background color. It works best for 256 or true color
  109. output.
  110. .. note:: Notice that there is no universal way to detect whether the
  111. application is running in a light or dark terminal. As a
  112. developer of an command line application, you'll have to make
  113. this configurable for the user.
  114. :param min_brightness: Float between 0.0 and 1.0 or a callable that returns
  115. a float.
  116. :param max_brightness: Float between 0.0 and 1.0 or a callable that returns
  117. a float.
  118. """
  119. def __init__(
  120. self, min_brightness: AnyFloat = 0.0, max_brightness: AnyFloat = 1.0
  121. ) -> None:
  122. self.min_brightness = min_brightness
  123. self.max_brightness = max_brightness
  124. def transform_attrs(self, attrs: Attrs) -> Attrs:
  125. min_brightness = to_float(self.min_brightness)
  126. max_brightness = to_float(self.max_brightness)
  127. assert 0 <= min_brightness <= 1
  128. assert 0 <= max_brightness <= 1
  129. # Don't do anything if the whole brightness range is acceptable.
  130. # This also avoids turning ansi colors into RGB sequences.
  131. if min_brightness == 0.0 and max_brightness == 1.0:
  132. return attrs
  133. # If a foreground color is given without a background color.
  134. no_background = not attrs.bgcolor or attrs.bgcolor == "default"
  135. has_fgcolor = attrs.color and attrs.color != "ansidefault"
  136. if has_fgcolor and no_background:
  137. # Calculate new RGB values.
  138. r, g, b = self._color_to_rgb(attrs.color or "")
  139. hue, brightness, saturation = rgb_to_hls(r, g, b)
  140. brightness = self._interpolate_brightness(
  141. brightness, min_brightness, max_brightness
  142. )
  143. r, g, b = hls_to_rgb(hue, brightness, saturation)
  144. new_color = f"{int(r * 255):02x}{int(g * 255):02x}{int(b * 255):02x}"
  145. attrs = attrs._replace(color=new_color)
  146. return attrs
  147. def _color_to_rgb(self, color: str) -> tuple[float, float, float]:
  148. """
  149. Parse `style.Attrs` color into RGB tuple.
  150. """
  151. # Do RGB lookup for ANSI colors.
  152. try:
  153. from prompt_toolkit.output.vt100 import ANSI_COLORS_TO_RGB
  154. r, g, b = ANSI_COLORS_TO_RGB[color]
  155. return r / 255.0, g / 255.0, b / 255.0
  156. except KeyError:
  157. pass
  158. # Parse RRGGBB format.
  159. return (
  160. int(color[0:2], 16) / 255.0,
  161. int(color[2:4], 16) / 255.0,
  162. int(color[4:6], 16) / 255.0,
  163. )
  164. # NOTE: we don't have to support named colors here. They are already
  165. # transformed into RGB values in `style.parse_color`.
  166. def _interpolate_brightness(
  167. self, value: float, min_brightness: float, max_brightness: float
  168. ) -> float:
  169. """
  170. Map the brightness to the (min_brightness..max_brightness) range.
  171. """
  172. return min_brightness + (max_brightness - min_brightness) * value
  173. def invalidation_hash(self) -> Hashable:
  174. return (
  175. "adjust-brightness",
  176. to_float(self.min_brightness),
  177. to_float(self.max_brightness),
  178. )
  179. class DummyStyleTransformation(StyleTransformation):
  180. """
  181. Don't transform anything at all.
  182. """
  183. def transform_attrs(self, attrs: Attrs) -> Attrs:
  184. return attrs
  185. def invalidation_hash(self) -> Hashable:
  186. # Always return the same hash for these dummy instances.
  187. return "dummy-style-transformation"
  188. class DynamicStyleTransformation(StyleTransformation):
  189. """
  190. StyleTransformation class that can dynamically returns any
  191. `StyleTransformation`.
  192. :param get_style_transformation: Callable that returns a
  193. :class:`.StyleTransformation` instance.
  194. """
  195. def __init__(
  196. self, get_style_transformation: Callable[[], StyleTransformation | None]
  197. ) -> None:
  198. self.get_style_transformation = get_style_transformation
  199. def transform_attrs(self, attrs: Attrs) -> Attrs:
  200. style_transformation = (
  201. self.get_style_transformation() or DummyStyleTransformation()
  202. )
  203. return style_transformation.transform_attrs(attrs)
  204. def invalidation_hash(self) -> Hashable:
  205. style_transformation = (
  206. self.get_style_transformation() or DummyStyleTransformation()
  207. )
  208. return style_transformation.invalidation_hash()
  209. class ConditionalStyleTransformation(StyleTransformation):
  210. """
  211. Apply the style transformation depending on a condition.
  212. """
  213. def __init__(
  214. self, style_transformation: StyleTransformation, filter: FilterOrBool
  215. ) -> None:
  216. self.style_transformation = style_transformation
  217. self.filter = to_filter(filter)
  218. def transform_attrs(self, attrs: Attrs) -> Attrs:
  219. if self.filter():
  220. return self.style_transformation.transform_attrs(attrs)
  221. return attrs
  222. def invalidation_hash(self) -> Hashable:
  223. return (self.filter(), self.style_transformation.invalidation_hash())
  224. class _MergedStyleTransformation(StyleTransformation):
  225. def __init__(self, style_transformations: Sequence[StyleTransformation]) -> None:
  226. self.style_transformations = style_transformations
  227. def transform_attrs(self, attrs: Attrs) -> Attrs:
  228. for transformation in self.style_transformations:
  229. attrs = transformation.transform_attrs(attrs)
  230. return attrs
  231. def invalidation_hash(self) -> Hashable:
  232. return tuple(t.invalidation_hash() for t in self.style_transformations)
  233. def merge_style_transformations(
  234. style_transformations: Sequence[StyleTransformation],
  235. ) -> StyleTransformation:
  236. """
  237. Merge multiple transformations together.
  238. """
  239. return _MergedStyleTransformation(style_transformations)
  240. # Dictionary that maps ANSI color names to their opposite. This is useful for
  241. # turning color schemes that are optimized for a black background usable for a
  242. # white background.
  243. OPPOSITE_ANSI_COLOR_NAMES = {
  244. "ansidefault": "ansidefault",
  245. "ansiblack": "ansiwhite",
  246. "ansired": "ansibrightred",
  247. "ansigreen": "ansibrightgreen",
  248. "ansiyellow": "ansibrightyellow",
  249. "ansiblue": "ansibrightblue",
  250. "ansimagenta": "ansibrightmagenta",
  251. "ansicyan": "ansibrightcyan",
  252. "ansigray": "ansibrightblack",
  253. "ansiwhite": "ansiblack",
  254. "ansibrightred": "ansired",
  255. "ansibrightgreen": "ansigreen",
  256. "ansibrightyellow": "ansiyellow",
  257. "ansibrightblue": "ansiblue",
  258. "ansibrightmagenta": "ansimagenta",
  259. "ansibrightcyan": "ansicyan",
  260. "ansibrightblack": "ansigray",
  261. }
  262. assert set(OPPOSITE_ANSI_COLOR_NAMES.keys()) == set(ANSI_COLOR_NAMES)
  263. assert set(OPPOSITE_ANSI_COLOR_NAMES.values()) == set(ANSI_COLOR_NAMES)
  264. @memoized()
  265. def get_opposite_color(colorname: str | None) -> str | None:
  266. """
  267. Take a color name in either 'ansi...' format or 6 digit RGB, return the
  268. color of opposite luminosity (same hue/saturation).
  269. This is used for turning color schemes that work on a light background
  270. usable on a dark background.
  271. """
  272. if colorname is None: # Because color/bgcolor can be None in `Attrs`.
  273. return None
  274. # Special values.
  275. if colorname in ("", "default"):
  276. return colorname
  277. # Try ANSI color names.
  278. try:
  279. return OPPOSITE_ANSI_COLOR_NAMES[colorname]
  280. except KeyError:
  281. # Try 6 digit RGB colors.
  282. r = int(colorname[:2], 16) / 255.0
  283. g = int(colorname[2:4], 16) / 255.0
  284. b = int(colorname[4:6], 16) / 255.0
  285. h, l, s = rgb_to_hls(r, g, b)
  286. l = 1 - l
  287. r, g, b = hls_to_rgb(h, l, s)
  288. r = int(r * 255)
  289. g = int(g * 255)
  290. b = int(b * 255)
  291. return f"{r:02x}{g:02x}{b:02x}"