codekingpro/portable-devtools
114k
1from collections import ChainMap2from typing import TYPE_CHECKING, Any, Optional3 4if TYPE_CHECKING:5 from rich.theme import Theme6 7from httpie.output.ui.palette import GenericColor, PieStyle, Styles, ColorString, _StyledGenericColor # noqa8 9RICH_BOLD = ColorString('bold')10 11# Rich-specific color code declarations12# <https://github.com/Textualize/rich/blob/fcd684dd3a482977cab620e71ccaebb94bf13ac9/rich/default_styles.py>13CUSTOM_STYLES = {14 'progress.description': RICH_BOLD | GenericColor.WHITE,15 'progress.data.speed': RICH_BOLD | GenericColor.GREEN,16 'progress.percentage': RICH_BOLD | GenericColor.AQUA,17 'progress.download': RICH_BOLD | GenericColor.AQUA,18 'progress.remaining': RICH_BOLD | GenericColor.ORANGE,19 'bar.complete': RICH_BOLD | GenericColor.PURPLE,20 'bar.finished': RICH_BOLD | GenericColor.GREEN,21 'bar.pulse': RICH_BOLD | GenericColor.PURPLE,22 'option': RICH_BOLD | GenericColor.PINK,23}24 25 26class _GenericColorCaster(dict):27 """28 Translate GenericColor to a regular string on the attribute access29 phase.30 """31 32 def _translate(self, key: Any) -> Any:33 if isinstance(key, GenericColor):34 return key.name.lower()35 else:36 return key37 38 def __getitem__(self, key: Any) -> Any:39 return super().__getitem__(self._translate(key))40 41 def get(self, key: Any) -> Any:42 return super().get(self._translate(key))43 44 45def _make_rich_color_theme(style_name: Optional[str] = None) -> 'Theme':46 from rich.style import Style47 from rich.theme import Theme48 49 try:50 PieStyle(style_name)51 except ValueError:52 style = Styles.ANSI53 else:54 style = Styles.PIE55 56 theme = Theme()57 for color, color_set in ChainMap(58 GenericColor.__members__, CUSTOM_STYLES59 ).items():60 if isinstance(color_set, _StyledGenericColor):61 properties = dict.fromkeys(color_set.styles, True)62 color_set = color_set.color63 else:64 properties = {}65 66 theme.styles[color.lower()] = Style(67 color=color_set.apply_style(style, style_name=style_name),68 **properties,69 )70 71 # E.g translate GenericColor.BLUE into blue on key access72 theme.styles = _GenericColorCaster(theme.styles)73 return theme74 