Debian Codegraph @

lib/view/colors.py

raw
1 # -*- coding: utf-8 -*-
2 # This program is free software; you can redistribute it and/or modify
3 # it under the terms of the GNU General Public License as published by
4 # the Free Software Foundation; either version 2 of the License, or
5 # (at your option) any later version.
6 #
7 # This program is distributed in the hope that it will be useful,
8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 # GNU General Public License for more details.
11 #
12 # You should have received a copy of the GNU General Public License
13 # along with this program; if not, write to the Free Software
14 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
15 # MA 02110-1301, USA.
16 #
17 # Author: Mauro Soria
18
19 import re
20
21 from colorama import init, Fore, Back, Style
22
23
24 BACK_COLORS = {
25 "red": Back.RED,
26 "green": Back.GREEN,
27 "yellow": Back.YELLOW,
28 "blue": Back.BLUE,
29 "magenta": Back.MAGENTA,
30 "cyan": Back.CYAN,
31 "white": Back.WHITE,
32 "none": "",
33 }
34
35 FORE_COLORS = {
36 "red": Fore.RED,
37 "green": Fore.GREEN,
38 "yellow": Fore.YELLOW,
39 "blue": Fore.BLUE,
40 "magenta": Fore.MAGENTA,
41 "cyan": Fore.CYAN,
42 "white": Fore.WHITE,
43 "none": "",
44 }
45
46 STYLES = {
47 "bright": Style.BRIGHT,
48 "dim": Style.DIM,
49 "normal": ""
50 }
51
52 # Credit: https://stackoverflow.com/a/14693789
53 _ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
54
55 init()
56
57
58 def disable_color():
59 for style in STYLES:
60 STYLES[style] = STYLES["normal"]
61
62 for table in (FORE_COLORS, BACK_COLORS):
63 for color in ("red", "green", "yellow", "blue", "magenta", "cyan", "white"):
64 table[color] = table["none"]
65
66
67 def set_color(msg, fore="none", back="none", style="normal"):
68 msg = STYLES[style] + FORE_COLORS[fore] + BACK_COLORS[back] + msg
69 return msg + Style.RESET_ALL
70
71
72 def clean_color(msg):
73 return _ansi_escape.sub("", msg)