noether/prbraid/color.py

60 lines
1.4 KiB
Python
Raw Normal View History

2025-06-11 11:11:35 +10:00
from enum import Enum
2025-06-11 12:43:49 +10:00
from typing import Optional
2025-06-11 11:11:35 +10:00
class Color(Enum):
2025-06-11 12:43:49 +10:00
Reset = 0
Bold = 1
Italics = 2
Underline = 4
Black = 30
Red = 31
Green = 32
Yellow = 33
Blue = 34
Magenta = 35
Cyan = 36
White = 37
2025-06-11 11:11:35 +10:00
# escape sequence format string
2025-06-11 12:43:49 +10:00
__fescseq = '\033[{0}'
2025-06-11 11:11:35 +10:00
# ansi reset code
__ansi_rst = '\033[0m'
@staticmethod
def _ansi_ret(ansi):
return ansi, Color.__ansi_white
@staticmethod
def code(color: 'Color'):
2025-06-11 12:43:49 +10:00
return Color.__fescseq.format(f'{color.value}m')
# move the cursor up n lines
@staticmethod
def mvup_code(n: int):
return Color.__fescseq.format(f'{n}A')
2025-06-11 11:11:35 +10:00
def ansi(self):
code = Color.code(self)
if self == Color.White:
return code, ''
return code, Color.__ansi_rst
# !! ULTRA PRINT !!
def uprint(text: str,
2025-06-11 12:43:49 +10:00
color: Optional[Color] = None,
style: Optional[Color] = None,
moveup: int = 0,
2025-06-11 11:11:35 +10:00
end: str = '\n',
flush: bool = True):
2025-06-11 12:43:49 +10:00
if color is not None:
c = color.ansi()
text = f'{c[0]}{text}{c[1]}'
if style is not None:
s = style.ansi()
tail = '' if (c is not None and c[1] == '') else s[1]
text = f'{s[0]}{text}{tail}'
if moveup > 0:
text = Color.mvup_code(moveup) + text
2025-06-11 11:11:35 +10:00
print(text, end=end, flush=flush)