Skip to content

Commit

Permalink
Added an "approximate_rgb" function.
Browse files Browse the repository at this point in the history
Also covered 256 colour codes with test. Not 100% sure if those test are
any good though.
  • Loading branch information
exhuma committed Aug 9, 2013
1 parent 74e89a5 commit 024fffd
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
23 changes: 23 additions & 0 deletions blessings/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,29 @@ def _formatting_string(self, formatting):
"""Return a new ``FormattingString`` which implicitly receives my notion of "normal"."""
return FormattingString(formatting, self.normal)

def approximate_rgb(self, r, g, b):
if self.number_of_colors != 256:
return self.color(7)

if r == g == b:
offset = int(r / (256.0 / 24.0))
index = 232 + offset
else:
roundint = lambda n, p: (n + p / 2) / p * p

# Technically this ought to clamp to 0x5f, 0x87, 0xaf, and 0xd7
# rather than 0x33, 0x66, 0x99, and 0xcc, but who the hell came
# up with that? Seriously.
clamped_r = roundint(r, 0x33)
clamped_g = roundint(g, 0x33)
clamped_b = roundint(b, 0x33)

col = clamped_b / 0x33
row = clamped_g / 0x33
face = clamped_r / 0x33
index = 36 * face + 6 * row + col + 16

return self.color(index)

def derivative_colors(colors):
"""Return the names of valid color variants, given the base colors."""
Expand Down
29 changes: 28 additions & 1 deletion blessings/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@
from functools import partial
from StringIO import StringIO
import sys
import os

from nose import SkipTest
from nose.tools import eq_
from nose.tools import eq_, assert_in

# This tests that __all__ is correct, since we use below everything that should
# be imported:
Expand Down Expand Up @@ -254,3 +255,29 @@ def test_force_styling_none():
"""If ``force_styling=None`` is passed to the constructor, don't ever do styling."""
t = TestTerminal(force_styling=None)
eq_(t.save, '')


def test_256color():
"""Test 256 Color Support"""
if os.name != "posix":
# Blatantly assuming this won't work on non-posix systems.
raise SkipTest

t = TestTerminal()

for x in range(8):
assert_in(unicode(x + 30), t.color(x))

for x in range(8):
assert_in(unicode(x + 90), t.color(x + 8))

for x in range(16, 255):
assert_in(unicode(x), t.color(x))


def test_approximate_color():
"""Test Approximate Colors"""
t = TestTerminal()
assert_in(u'196m', t.approximate_rgb(255, 0, 0))
assert_in(u'46m', t.approximate_rgb(0, 255, 0))
assert_in(u'21m', t.approximate_rgb(0, 0, 255))

0 comments on commit 024fffd

Please sign in to comment.