Ejemplo n.º 1
0
 def __init__(self, tokens, type=None):
     self.tokens = tokens
     self.units = {}
     if tokens is None:
         self.value = 0.0
     elif isinstance(tokens, NumberValue):
         self.value = tokens.value
         self.units = tokens.units.copy()
         if tokens.units:
             type = None
     elif isinstance(tokens, (StringValue, basestring)):
         tokens = getattr(tokens, "value", tokens)
         try:
             if tokens and tokens[-1] == "%":
                 self.value = to_float(tokens[:-1]) / 100.0
                 self.units = {"%": _units_weights.get("%", 1), "_": "%"}
             else:
                 self.value = to_float(tokens)
         except ValueError:
             raise ValueError("Value is not a Number! (%s)" % tokens)
     elif isinstance(tokens, (int, float)):
         # TODO i don't like this; should store the original and only divide
         # when converting.  requires fixing __str__ though
         self.value = float(tokens) * _conv_factor.get(type, 1.0)
     else:
         raise ValueError("Can't convert to CSS number: %s" % repr(tokens))
     if type is not None:
         self.units = {type: _units_weights.get(type, 1), "_": type}
Ejemplo n.º 2
0
 def __init__(self, tokens, type=None):
     self.tokens = tokens
     self.units = {}
     if tokens is None:
         self.value = 0.0
     elif isinstance(tokens, ParserValue):
         self.value = float(tokens.value)
     elif isinstance(tokens, NumberValue):
         self.value = tokens.value
         self.units = tokens.units.copy()
         if tokens.units:
             type = None
     elif isinstance(tokens, (StringValue, basestring)):
         tokens = getattr(tokens, 'value', tokens)
         if _undefined_re.match(tokens):
             raise ValueError("Value is not a Number! (%s)" % tokens)
         try:
             if tokens and tokens[-1] == '%':
                 self.value = to_float(tokens[:-1]) / 100.0
                 self.units = {'%': _units_weights.get('%', 1), '_': '%'}
             else:
                 self.value = to_float(tokens)
         except ValueError:
             raise ValueError("Value is not a Number! (%s)" % tokens)
     elif isinstance(tokens, (int, float)):
         self.value = float(tokens)
     else:
         raise ValueError("Can't convert to CSS number: %r" % tokens)
     if type is not None:
         self.units = {type: _units_weights.get(type, 1), '_': type}
Ejemplo n.º 3
0
def __color_stops(percentages, *args):
    if len(args) == 1:
        if isinstance(args[0], (list, tuple, List)):
            return list(args[0])
        elif isinstance(args[0], (String, six.string_types)):
            color_stops = []
            colors = split_params(getattr(args[0], 'value', args[0]))
            for color in colors:
                color = color.strip()
                if color.startswith('color-stop('):
                    s, c = split_params(color[11:].rstrip(')'))
                    s = s.strip()
                    c = c.strip()
                else:
                    c, s = color.split()
                color_stops.append((to_float(s), c))
            return color_stops

    colors = []
    stops = []
    prev_color = False
    for c in args:
        for c in List.from_maybe(c):
            if _is_color(c):
                if prev_color:
                    stops.append(None)
                colors.append(c)
                prev_color = True
            elif isinstance(c, Number):
                stops.append(c)
                prev_color = False

    if prev_color:
        stops.append(None)
    stops = stops[:len(colors)]
    if stops[0] is None or stops[0] == Number(0):
        stops[0] = Number(0, '%')
    if stops[-1] is None:
        stops[-1] = Number(100, '%')

    maxable_stops = [s for s in stops if s and not s.is_simple_unit('%')]
    if maxable_stops:
        max_stops = max(maxable_stops)
    else:
        max_stops = None

    stops = [_s / max_stops if _s and not _s.is_simple_unit('%') else _s for _s in stops]

    init = 0
    start = None
    for i, s in enumerate(stops + [1.0]):
        if s is None:
            if start is None:
                start = i
            end = i
        else:
            final = s
            if start is not None:
                stride = (final - init) / Number(end - start + 1 + (1 if i < len(stops) else 0))
                for j in range(start, end + 1):
                    stops[j] = init + stride * Number(j - start + 1)
            init = final
            start = None

    if not max_stops or percentages:
        pass
    else:
        stops = [s if s.is_simple_unit('%') else s * max_stops for s in stops]

    return List(List(pair) for pair in zip(stops, colors))
Ejemplo n.º 4
0
 def __init__(self, tokens):
     self.tokens = tokens
     self.value = (0, 0, 0, 1)
     self.types = {}
     if tokens is None:
         self.value = (0, 0, 0, 1)
     elif isinstance(tokens, ParserValue):
         hex = tokens.value
         self.value = self.HEX2RGBA[len(hex)](hex)
         self.types = {"rgba": 1}
     elif isinstance(tokens, ColorValue):
         self.value = tokens.value
         self.types = tokens.types.copy()
     elif isinstance(tokens, NumberValue):
         val = tokens.value
         self.value = (val, val, val, 1)
     elif isinstance(tokens, (list, tuple)):
         c = tokens[:4]
         r = 255.0, 255.0, 255.0, 1.0
         c = [0.0 if c[i] < 0 else r[i] if c[i] > r[i] else c[i] for i in range(4)]
         self.value = tuple(c)
         type = tokens[-1]
         if type in ("rgb", "rgba", "hsl", "hsla"):
             self.types = {type: 1}
     elif isinstance(tokens, (int, float)):
         val = float(tokens)
         self.value = (val, val, val, 1)
     else:
         if isinstance(tokens, StringValue):
             tokens = tokens.value
         tokens = to_str(tokens)
         tokens.replace(" ", "").lower()
         try:
             self.value = self.HEX2RGBA[len(tokens)](tokens)
         except:
             try:
                 val = to_float(tokens)
                 self.value = (val, val, val, 1)
             except ValueError:
                 try:
                     type, _, colors = tokens.partition("(")
                     colors = colors.rstrip(")")
                     if type in ("rgb", "rgba"):
                         c = tuple(colors.split(","))
                         try:
                             c = [to_float(c[i]) for i in range(4)]
                             col = [0.0 if c[i] < 0 else 255.0 if c[i] > 255 else c[i] for i in range(3)]
                             col += [0.0 if c[3] < 0 else 1.0 if c[3] > 1 else c[3]]
                             self.value = tuple(col)
                             self.types = {type: 1}
                         except:
                             raise ValueError("Value is not a Color! (%s)" % tokens)
                     elif type in ("hsl", "hsla"):
                         c = colors.split(",")
                         try:
                             c = [to_float(c[i]) for i in range(4)]
                             col = [c[0] % 360.0] / 360.0
                             col += [0.0 if c[i] < 0 else 1.0 if c[i] > 1 else c[i] for i in range(1, 4)]
                             self.value = tuple(
                                 [
                                     c * 255.0
                                     for c in colorsys.hls_to_rgb(
                                         col[0],
                                         0.999999 if col[2] == 1 else col[2],
                                         0.999999 if col[1] == 1 else col[1],
                                     )
                                 ]
                                 + [col[3]]
                             )
                             self.types = {type: 1}
                         except:
                             raise ValueError("Value is not a Color! (%s)" % tokens)
                     else:
                         raise ValueError("Value is not a Color! (%s)" % tokens)
                 except:
                     raise ValueError("Value is not a Color! (%s)" % tokens)
Ejemplo n.º 5
0
def __color_stops(percentages, *args):
    if len(args) == 1:
        if isinstance(args[0], (list, tuple, List)):
            list(args[0])
        elif isinstance(args[0], (String, six.string_types)):
            color_stops = []
            colors = split_params(getattr(args[0], 'value', args[0]))
            for color in colors:
                color = color.strip()
                if color.startswith('color-stop('):
                    s, c = split_params(color[11:].rstrip(')'))
                    s = s.strip()
                    c = c.strip()
                else:
                    c, s = color.split()
                color_stops.append((to_float(s), c))
            return color_stops

    colors = []
    stops = []
    prev_color = False
    for c in args:
        for c in List.from_maybe(c):
            if isinstance(c, Color):
                if prev_color:
                    stops.append(None)
                colors.append(c)
                prev_color = True
            elif isinstance(c, Number):
                stops.append(c)
                prev_color = False

    if prev_color:
        stops.append(None)
    stops = stops[:len(colors)]
    if stops[0] is None:
        stops[0] = Number(0, '%')
    if stops[-1] is None:
        stops[-1] = Number(100, '%')

    maxable_stops = [s for s in stops if s and not s.is_simple_unit('%')]
    if maxable_stops:
        max_stops = max(maxable_stops)
    else:
        max_stops = None

    stops = [_s / max_stops if _s and not _s.is_simple_unit('%') else _s for _s in stops]

    init = 0
    start = None
    for i, s in enumerate(stops + [1.0]):
        if s is None:
            if start is None:
                start = i
            end = i
        else:
            final = s
            if start is not None:
                stride = (final - init) / Number(end - start + 1 + (1 if i < len(stops) else 0))
                for j in range(start, end + 1):
                    stops[j] = init + stride * Number(j - start + 1)
            init = final
            start = None

    if not max_stops or percentages:
        pass
    else:
        stops = [s if s.is_simple_unit('%') else s * max_stops for s in stops]

    return list(zip(stops, colors))
Ejemplo n.º 6
0
def __color_stops(percentages, *args):
    if len(args) == 1:
        if isinstance(args[0], (list, tuple, ListValue)):
            return ListValue(args[0]).values()
        elif isinstance(args[0], (StringValue, basestring)):
            color_stops = []
            colors = split_params(args[0].value)
            for color in colors:
                color = color.strip()
                if color.startswith('color-stop('):
                    s, c = split_params(color[11:].rstrip(')'))
                    s = s.strip()
                    c = c.strip()
                else:
                    c, s = color.split()
                color_stops.append((to_float(s), c))
            return color_stops

    colors = []
    stops = []
    prev_color = False
    for c in args:
        if isinstance(c, ListValue):
            for i, c in c.items():
                if isinstance(c, ColorValue):
                    if prev_color:
                        stops.append(None)
                    colors.append(c)
                    prev_color = True
                elif isinstance(c, NumberValue):
                    stops.append(c)
                    prev_color = False
        else:
            if isinstance(c, ColorValue):
                if prev_color:
                    stops.append(None)
                colors.append(c)
                prev_color = True
            elif isinstance(c, NumberValue):
                stops.append(NumberValue(c))
                prev_color = False
    if prev_color:
        stops.append(None)
    stops = stops[:len(colors)]
    if percentages:
        max_stops = max(s and (s.value if s.unit != '%' else None) or None for s in stops)
    else:
        max_stops = max(s and (s if s.unit != '%' else None) or None for s in stops)
    stops = [s and (s.value / max_stops if s.unit != '%' else s.value) for s in stops]

    init = 0
    start = None
    for i, s in enumerate(stops + [1.0]):
        if s is None:
            if start is None:
                start = i
            end = i
        else:
            final = s
            if start is not None:
                stride = (final - init) / (end - start + 1 + (1 if i < len(stops) else 0))
                for j in range(start, end + 1):
                    stops[j] = init + stride * (j - start + 1)
            init = final
            start = None

    if not max_stops or percentages:
        stops = [NumberValue(s, '%') for s in stops]
    else:
        stops = [s * max_stops for s in stops]
    return zip(stops, colors)