Add a highlight_color util function.

This commit is contained in:
Florian Bruhin 2014-07-15 11:07:43 +02:00
parent 20e8c464e6
commit b47d53953b
2 changed files with 62 additions and 1 deletions

View File

@ -576,5 +576,36 @@ class NormalizeTests(unittest.TestCase):
self.assertEqual(utils.normalize_keystr(orig), repl, orig)
class HighlightColorTests(unittest.TestCase):
"""Test highlight_color."""
def test_invalid(self):
"""Test with an invalid Color."""
col = Color()
with self.assertRaises(QtValueError):
utils.highlight_color(col)
def test_large_factor(self):
"""Test with a too large factor."""
col = Color('black')
with self.assertRaises(OverflowError):
utils.highlight_color(col, 2 ** 31)
def test_white(self):
"""Test highlighting white."""
col = Color('white')
c1 = Color(utils.highlight_color(col, 1))
c2 = Color(127, 127, 127)
self.assertEqual(c1, c2)
def test_black(self):
"""Test highlighting black."""
col = Color('black')
self.assertEqual(Color(utils.highlight_color(col, 0.5)),
Color(204, 204, 204))
if __name__ == '__main__':
unittest.main()

View File

@ -36,7 +36,8 @@ from pkg_resources import resource_string
import qutebrowser
import qutebrowser.utils.log as log
from qutebrowser.utils.qt import qt_version_check, qt_ensure_valid
from qutebrowser.utils.qt import (qt_version_check, qt_ensure_valid,
check_overflow)
def elide(text, length):
@ -489,3 +490,32 @@ def normalize_keystr(keystr):
for mod in ('Ctrl', 'Meta', 'Alt', 'Shift'):
keystr = keystr.replace(mod + '-', mod + '+')
return keystr.lower()
def highlight_color(color, factor=0.5):
"""Get a highlighted color based on a base color.
If the passed color is dark, it will get lighter. If it is light, it will
get darker.
Args:
color: A QColor with the initial color.
factor: How much to lighten/darken the color (0.5: 50% lighter/darker).
Return:
A QColor with the highlighted color.
"""
qt_ensure_valid(color)
qt_factor = 100 * (1 + factor)
check_overflow(qt_factor, 'int')
if color == QColor('black'):
# Black isn't handled by QColor::lighter because that just multiplies
# the HSV value by a factor.
# We also add an additional 30% because the effect would be way too
# subtle if we didn't.
return interpolate_color(QColor('black'), QColor('white'),
min((100 * factor) + 30, 100))
elif color.value() < 128:
return color.lighter(qt_factor)
else:
return color.darker(qt_factor)