import re
-from cgi import escape
+from colorsys import rgb_to_hls, hls_to_rgb
+from cgi import escape as html_escape
from datetime import datetime
# Map of special chars to ascii from Darkplace's console.c.
_dec_colors = re.compile(r'\^(\d)')
_hex_colors = re.compile(r'\^x([\dA-Fa-f])([\dA-Fa-f])([\dA-Fa-f])')
+# On a light scale of 0 (black) to 1.0 (white)
+_contrast_threshold = 0.5
+
def qfont_decode(qstr=''):
""" Convert the qfont characters in a string to ascii.
if qstr == None:
qstr = ''
return _all_colors.sub('', qstr)
+
+
+def hex_repl(match):
+ # Convert hex to 8 bits and to 0.0-1.0 scale
+ r = int(match.group(1) * 2, 16) / 255.
+ g = int(match.group(2) * 2, 16) / 255.
+ b = int(match.group(3) * 2, 16) / 255.
+ hue, light, satur = rgb_to_hls(r, g, b)
+ if light < _contrast_threshold:
+ light = _contrast_threshold
+ # Get new rgb in 0-255 scale
+ r, g, b = tuple([255 * i for i in hls_to_rgb(hue, light, satur)])
+ return '<span style="color:rgb({0},{1},{2})">'.format(r, g, b)
def html_colors(qstr=''):
- qstr = escape(qfont_decode(qstr))
- def dec_repl(match):
- return _dec_spans[int(match.group(1))]
- qstr = qstr.replace('^^', '^')
- html = _dec_colors.sub(dec_repl, qstr)
- html = _hex_colors.sub(r"<span style='color:#\1\1\2\2\3\3'>", html)
+ qstr = html_escape(qfont_decode(qstr).replace('^^', '^'))
+ html = _dec_colors.sub(lambda match: _dec_spans[int(match.group(1))], qstr)
+ html = _hex_colors.sub(hex_repl, html)
return html + "</span>" * len(_all_colors.findall(qstr))