pmacs3/color.py

111 lines
2.9 KiB
Python

import curses
colors = {}
_colors = []
_pairs = {}
index = 1
attributes = {
'bold': curses.A_BOLD,
'reverse': curses.A_REVERSE,
'normal': curses.A_NORMAL,
'underline': curses.A_UNDERLINE,
'dim': curses.A_DIM,
'standout': curses.A_STANDOUT,
}
inited = False
default_color = True
ascii_map = {
'*': 'bold',
}
rev_ascii_map = {
'bold': '*',
}
def add_color(name, value, abbrev):
colors[name] = value
ascii_map[abbrev] = name
rev_ascii_map[name] = abbrev
def color256(name, fallback, abbrev, r, g, b):
name2 = '%s%d%d%d' % (name, r, g, b)
abbrev2 = '%s%d%d%d' % (abbrev, r, g, b)
if curses.COLORS == 256:
value = 16 + r * 36 + g * 6 + b
else:
value = fallback
add_color(name2, value, abbrev2)
# PUBLIC METHODS
def init():
global _pairs, inited
if inited:
return
add_color('cyan', curses.COLOR_CYAN, 'c')
add_color('blue', curses.COLOR_BLUE, 'b')
add_color('green', curses.COLOR_GREEN, 'g')
add_color('red', curses.COLOR_RED, 'r')
add_color('yellow', curses.COLOR_YELLOW, 'y')
add_color('magenta', curses.COLOR_MAGENTA, 'm')
add_color('black', curses.COLOR_BLACK, 'B')
add_color('white', curses.COLOR_WHITE, 'w')
inited = True
for i in range(0, 256):
name = 'f%02x' % i
abbrev = 'f%02x' % i
add_color(name, i, abbrev)
for i in range(0, 24):
color256('grey', curses.COLOR_WHITE, 'G', i, i, i)
for i in range(1, 6):
for j in range(0, i):
for k in range(0, i):
color256('red', curses.COLOR_RED, 'r', i, j, k)
color256('green', curses.COLOR_GREEN, 'g', j, i, k)
color256('blue', curses.COLOR_BLUE, 'b', j, k, i)
for i in range(1, 6):
for j in range(0, i):
color256('yellow', curses.COLOR_YELLOW, 'y', i, i, j)
color256('cyan', curses.COLOR_CYAN, 'c', j, i, i)
color256('magenta', curses.COLOR_MAGENTA, 'm', i, j, i)
if default_color:
colors['default'] = -1
ascii_map['d'] = 'default'
rev_ascii_map['default'] = 'd'
def build(fg, bg, *attr):
v = curses.A_NORMAL | pairs(fg, bg)
for x in attr:
if type(x) == type(''):
x = attributes[x]
v = v | x
return v
return build_attr(cattr, *attr)
# PRIVATE METHODS
def pairs(fg, bg):
if not curses.has_colors():
return curses.color_pair(0)
global index
fgi = colors.get(fg, colors['white'])
bgi = colors.get(bg, colors['black'])
key = (fgi, bgi)
if key not in _pairs:
assert index < curses.COLOR_PAIRS, "too many colors"
assert type(fgi) == type(0), "illegal fgi: %r" % fgi
assert type(bgi) == type(0), "illegal bgi: %r" % bgi
curses.init_pair(index, fgi, bgi)
_pairs[key] = curses.color_pair(index)
_colors.append(key)
index = len(_colors) + 1
return _pairs[key]