#!/usr/bin/python import random class Color(object): """Represents a color for the keyboard""" def __init__(self, red=None, green=None, blue=None, rgb=None): # Expects integer values, no floats if rgb is None: rgb = (red, green, blue) else: rgb = tuple(rgb) if None in rgb: raise Exception("bad value in %r" % rgb) for name, value in zip(['red' , 'green', 'blue'], rgb): if not 0 <= value < 256: raise Exception("Bad value %s for %s" % (value, name)) self.rgb = rgb @classmethod def blend(cls, c1, c2, transparency): """Given two colors, return a color based on a weighted combination""" blended = [a+b for a, b in zip([(1 - transparency) * x for x in c1.rgb], [transparency * x for x in c2.rgb])] return cls(rgb=blended) @classmethod def average(cls, colors): """Return the mean color among the given colors""" return cls(rgb=[sum(x)/len(colors) for x in zip(*[c.rgb for c in colors])]) @classmethod def fromstring(cls, hexstring): """Convert a 6-digit hex string into a Color object""" r = int(hexstring[0:2], 16) g = int(hexstring[2:4], 16) b = int(hexstring[4:6], 16) return cls(r, g, b) @classmethod def random8(cls, exclude=None): """Returns a random color from the 8 basic colors, optionally excluding a choice. """ while True: candidate = cls(rgb=[random.choice([0,255]) for _n in range(3)]) if not exclude or candidate != exclude: return candidate def __str__(self): """6-hex-digit representation of the color This is the representation used by ckb-daemon """ return '%02x%02x%02x' % self.rgb def __cmp__(self, other): return cmp(self.rgb, other.rgb) def __eq__(self, other): return self.rgb == other.rgb def __hash__(self): return hash(self.rgb) class Colors(object): """Pre-defined colors""" WHITE = Color.fromstring('ffffff') GREY = Color.fromstring('808080') DARK_GREY = Color.fromstring('404040') BLACK = Color.fromstring('000000') RED = Color.fromstring('ff0000') GREEN = Color.fromstring('00ff00') BLUE = Color.fromstring('0000ff') PURPLE = Color.fromstring('ff00ff') YELLOW = Color.fromstring('ffff00') CYAN = Color.fromstring('00ffff') DARKCYAN = Color.fromstring('004040') ORANGE = Color.fromstring('ff8000')