예제 #1
0
def _DimensionProd(parent, nextSor=False):
    return Prod(name='Dimension',
                match=lambda t, v: t in
                (u'DIMENSION', u'NUMBER', u'PERCENTAGE') or v in u'+-',
                nextSor=nextSor,
                toSeq=lambda t, tokens:
                (t[0], DimensionValue(pushtoken(t, tokens), parent=parent)))
예제 #2
0
def _MSValueProd(parent, nextSor=False):
    return Prod(
        name=MSValue._functionName,
        match=lambda t, v: (  # t == self._prods.FUNCTION and (
            normalize(v) in (
                'expression(',
                'alpha(',
                'blur(',
                'chroma(',
                'dropshadow(',
                'fliph(',
                'flipv(',
                'glow(',
                'gray(',
                'invert(',
                'mask(',
                'shadow(',
                'wave(',
                'xray(',
            ) or v.startswith('progid:DXImageTransform.Microsoft.')),
        nextSor=nextSor,
        toSeq=lambda t, tokens: (
            MSValue._functionName,
            MSValue(pushtoken(t, tokens), parent=parent),
        ),
    )
예제 #3
0
    def _productions(self):
        """Return definition used for parsing."""
        types = self._prods  # rename!

        func = Prod(name='MSValue-Sub',
                    match=lambda t, v: t == self._prods.FUNCTION,
                    toSeq=lambda t, tokens:
                    (MSValue._functionName,
                     MSValue(pushtoken(t, tokens), parent=self)))

        funcProds = Sequence(
            Prod(name='FUNCTION',
                 match=lambda t, v: t == types.FUNCTION,
                 toSeq=lambda t, tokens: (t[0], t[1])),
            Sequence(
                Choice(
                    _ColorProd(self),
                    _DimensionProd(self),
                    _URIProd(self),
                    _ValueProd(self),
                    _MSValueProd(self),
                    #_CalcValueProd(self),
                    _CSSVariableProd(self),
                    func,
                    #_CSSFunctionProd(self),
                    Prod(name='MSValuePart',
                         match=lambda t, v: v != u')',
                         toSeq=lambda t, tokens: (t[0], t[1]))),
                minmax=lambda: (0, None)),
            PreDef.funcEnd(stop=True))
        return funcProds
예제 #4
0
def _URIProd(parent, nextSor=False, toStore=None):
    return Prod(name='URIValue',
                match=lambda t, v: t == 'URI',
                toStore=toStore,
                nextSor=nextSor,
                toSeq=lambda t, tokens:
                ('URIValue', URIValue(pushtoken(t, tokens), parent=parent)))
예제 #5
0
파일: value.py 프로젝트: kgn/cssutils
def _MSValueProd(parent, nextSor=False):
    return Prod(name=MSValue._functionName,
                match=lambda t, v: (#t == self._prods.FUNCTION and (
                    normalize(v) in (u'expression(',
                                                     u'alpha(',
                                                     u'blur(',
                                                     u'chroma(',
                                                     u'dropshadow(',
                                                     u'fliph(',
                                                     u'flipv(',
                                                     u'glow(',
                                                     u'gray(',
                                                     u'invert(',
                                                     u'mask(',
                                                     u'shadow(',                                                               
                                                     u'wave(',
                                                     u'xray(') or
                    v.startswith(u'progid:DXImageTransform.Microsoft.')                               
                    ),
                nextSor=nextSor,
                toSeq=lambda t, tokens: (MSValue._functionName, 
                                         MSValue(pushtoken(t, 
                                                                           tokens
                                                                           ),
                                                 parent=parent
                                                 )
                                         )
                )
예제 #6
0
def _ValueProd(parent, nextSor=False, toStore=None):
    return Prod(name='Value',
                match=lambda t, v: t in ('IDENT', 'STRING', 'UNICODE-RANGE'),
                nextSor=nextSor,
                toStore=toStore,
                toSeq=lambda t, tokens:
                ('Value', Value(pushtoken(t, tokens), parent=parent)))
예제 #7
0
파일: value.py 프로젝트: kgn/cssutils
def _CSSVariableProd(parent, nextSor=False):
    return PreDef.variable(nextSor=nextSor,
                           toSeq=lambda t, tokens: (CSSVariable._functionName, 
                                                    CSSVariable(
                                pushtoken(t, tokens), 
                                parent=parent)
                                                    )
                           )  
예제 #8
0
def _DimensionProd(parent, nextSor=False, toStore=None):
    return Prod(
        name='Dimension',
        match=lambda t, v: t in ('DIMENSION', 'NUMBER', 'PERCENTAGE'),
        nextSor=nextSor,
        toStore=toStore,
        toSeq=lambda t, tokens:
        ('DIMENSION', DimensionValue(pushtoken(t, tokens), parent=parent)))
예제 #9
0
파일: value.py 프로젝트: kgn/cssutils
def _CSSFunctionProd(parent, nextSor=False):
    return PreDef.function(nextSor=nextSor,
                           toSeq=lambda t, tokens: (CSSFunction._functionName, 
                                                    CSSFunction(
                                pushtoken(t, tokens),
                                parent=parent)
                                )
                           )
예제 #10
0
def _CalcValueProd(parent, nextSor=False, toStore=None):
    return Prod(
        name=CSSCalc._functionName,
        match=lambda t, v: t == PreDef.types.FUNCTION and normalize(
            v) == 'calc(',
        toStore=toStore,
        toSeq=lambda t, tokens:
        (CSSCalc._functionName, CSSCalc(pushtoken(t, tokens), parent=parent)),
        nextSor=nextSor)
예제 #11
0
def _CSSVariableProd(parent, nextSor=False, toStore=None):
    return PreDef.variable(
        nextSor=nextSor,
        toStore=toStore,
        toSeq=lambda t, tokens: (
            CSSVariable._functionName,
            CSSVariable(pushtoken(t, tokens), parent=parent),
        ),
    )
예제 #12
0
def _ValueProd(parent, nextSor=False, toStore=None):
    return Prod(name='Value',
                match=lambda t, v: t in ('IDENT', 'STRING', 'UNICODE-RANGE'),
                nextSor = nextSor,
                toStore=toStore,
                toSeq=lambda t, tokens: ('Value', Value(pushtoken(t, tokens),
                                         parent=parent)
                                         )
                )
예제 #13
0
def _ColorProd(parent, nextSor=False):
    return Prod(
        name='ColorValue',
        match=lambda t, v: t == 'HASH' or
        (t == 'FUNCTION' and normalize(v) in
         (u'rgb(', u'rgba(', u'hsl(', u'hsla(')) or
        (t == 'IDENT' and normalize(v) in ColorValue.COLORS.keys()),
        nextSor=nextSor,
        toSeq=lambda t, tokens:
        ('ColorValue', ColorValue(pushtoken(t, tokens), parent=parent)))
예제 #14
0
파일: value.py 프로젝트: kgn/cssutils
def _URIProd(parent, nextSor=False):
    return Prod(name='URIValue',
                match=lambda t, v: t == 'URI',
                nextSor = nextSor,
                toSeq=lambda t, tokens: ('URIValue', URIValue(
                                            pushtoken(t, 
                                                                      tokens),
                                         parent=parent)
                                         )
                )
예제 #15
0
def _CalcValueProd(parent, nextSor=False, toStore=None):
    return Prod(name=CSSCalc._functionName,
                    match=lambda t, v: t == PreDef.types.FUNCTION and
                        normalize(v) == u'calc(',
                    toStore=toStore,
                    toSeq=lambda t, tokens: (CSSCalc._functionName,
                                                    CSSCalc(
                                pushtoken(t, tokens),
                                parent=parent)
                                                    ),
                    nextSor=nextSor)
예제 #16
0
def _ColorProd(parent, nextSor=False, toStore=None):
    return Prod(
        name='ColorValue',
        match=lambda t, v: (t == 'HASH' and reHexcolor.match(v)) or
        (t == 'FUNCTION' and normalize(v) in
         ('rgb(', 'rgba(', 'hsl(', 'hsla(')) or
        (t == 'IDENT' and normalize(v) in list(ColorValue.COLORS.keys())),
        nextSor=nextSor,
        toStore=toStore,
        toSeq=lambda t, tokens:
        ('ColorValue', ColorValue(pushtoken(t, tokens), parent=parent)))
예제 #17
0
파일: value.py 프로젝트: kgn/cssutils
def _DimensionProd(parent, nextSor=False):
    return Prod(name='Dimension',
                match=lambda t, v: t in (u'DIMENSION', 
                                         u'NUMBER', 
                                         u'PERCENTAGE') or v in u'+-',
                nextSor = nextSor,
                toSeq=lambda t, tokens: (t[0], DimensionValue(
                                            pushtoken(t, 
                                                                      tokens),
                                         parent=parent)
                                         )
                )
예제 #18
0
def _DimensionProd(parent, nextSor=False, toStore=None):
    return Prod(name='Dimension',
                match=lambda t, v: t in (u'DIMENSION',
                                         u'NUMBER',
                                         u'PERCENTAGE'),
                nextSor = nextSor,
                toStore=toStore,
                toSeq=lambda t, tokens: (u'DIMENSION', DimensionValue(
                                            pushtoken(t,
                                                      tokens),
                                            parent=parent)
                                         )
                )
예제 #19
0
파일: value.py 프로젝트: kgn/cssutils
def _ColorProd(parent, nextSor=False):
    return Prod(name='ColorValue',
                match=lambda t, v: t == 'HASH' or 
                                   (t == 'FUNCTION' and
                                    normalize(v) in (u'rgb(', 
                                                     u'rgba(',
                                                     u'hsl(', 
                                                     u'hsla(')) or
                                   (t == 'IDENT' and 
                                    normalize(v) in ColorValue.COLORS.keys()
                                    ),
                nextSor = nextSor,
                toSeq=lambda t, tokens: ('ColorValue', ColorValue(
                                            pushtoken(t, 
                                                                      tokens),
                                         parent=parent)
                                         )
                )
예제 #20
0
파일: value.py 프로젝트: kgn/cssutils
 def _productions(self):
     """Return definition used for parsing."""
     types = self._prods # rename!
     
     func = Prod(name='MSValue-Sub',
                 match=lambda t, v: t == self._prods.FUNCTION,
                 toSeq=lambda t, tokens: (MSValue._functionName, 
                                  MSValue(pushtoken(t, 
                                                                    tokens
                                                                    ),
                                         parent=self
                                         )
                                      )
                 )
     
     
     funcProds = Sequence(Prod(name='FUNCTION',
                               match=lambda t, v: t == types.FUNCTION,
                               toSeq=lambda t, tokens: (t[0], t[1])
                               ),
                          Sequence(Choice(_ColorProd(self),
                                          _DimensionProd(self),
                                          _URIProd(self),
                                          _ValueProd(self),
                                          _MSValueProd(self),
                                          #_CalcValueProd(self),
                                          _CSSVariableProd(self),
                                          func,
                                          #_CSSFunctionProd(self),
                                          Prod(name='MSValuePart',
                                               match=lambda t, v: v != u')',
                                               toSeq=lambda t, tokens: (t[0], t[1])
                                               )
                                          ),
                                   minmax=lambda: (0, None)
                                   ),
                          PreDef.funcEnd(stop=True)
                          )
     return funcProds
예제 #21
0
    def _setCssText(self, cssText):
        self._checkReadonly()
        types = self._prods # rename!

        component = Choice(PreDef.unary(toSeq=lambda t, tokens: (t[0],
                            DimensionValue(pushtoken(t, tokens),
                            parent=self)
                           )),
                           PreDef.number(toSeq=lambda t, tokens: (t[0],
                            DimensionValue(pushtoken(t, tokens),
                            parent=self)
                           )),
                           PreDef.percentage(toSeq=lambda t, tokens: (t[0],
                            DimensionValue(pushtoken(t, tokens),
                            parent=self)
                           ))
                   )
        noalp = Sequence(Prod(name='FUNCTION',
                              match=lambda t, v: t == types.FUNCTION and
                                                 v in (u'rgb(', u'hsl('),
                              toSeq=lambda t, tokens: (t[0], normalize(t[1]))),
                          component,
                          Sequence(PreDef.comma(optional=True),
                                   component,
                                   minmax=lambda: (2, 2)
                                   ),
                          PreDef.funcEnd(stop=True)
                          )
        witha = Sequence(Prod(name='FUNCTION',
                              match=lambda t, v: t == types.FUNCTION and
                                                 v in (u'rgba(', u'hsla('),
                              toSeq=lambda t, tokens: (t[0],
                                 normalize(t[1]))
                              ),
                          component,
                          Sequence(PreDef.comma(optional=True),
                                   component,
                                   minmax=lambda: (3, 3)
                                   ),
                          PreDef.funcEnd(stop=True)
                          )
        namedcolor = Prod(name='Named Color',
                     match=lambda t, v: t == 'IDENT' and (
                                        normalize(v) in self.COLORS.keys()
                                        ),
                     stop=True)

        prods = Choice(PreDef.hexcolor(stop=True),
                       namedcolor,
                       noalp,
                       witha)

        ok, seq, store, unused = ProdParser().parse(cssText,
                                                    self.type,
                                                    prods)
        self.wellformed = ok
        if ok:
            t, v = seq[0].type, seq[0].value
            if u'IDENT' == t:
                rgba = self.COLORS[normalize(v)]
            if u'HASH' == t:
                if len(v) == 4:
                    # HASH #rgb
                    rgba = (int(2*v[1], 16),
                            int(2*v[2], 16),
                            int(2*v[3], 16),
                            1.0)
                else:
                    # HASH #rrggbb
                    rgba = (int(v[1:3], 16),
                            int(v[3:5], 16),
                            int(v[5:7], 16),
                            1.0)

            elif u'FUNCTION' == t:
                functiontype, raw, check = None, [], u''
                HSL = False

                for item in seq:
                    try:
                        type_ = item.value.type
                    except AttributeError, e:
                        # type of function, e.g. rgb(
                        if item.type == 'FUNCTION':
                            functiontype = item.value
                            HSL = functiontype in (u'hsl(', u'hsla(')
                        continue

                    # save components
                    if type_ == Value.NUMBER:
                        raw.append(item.value.value)
                        check += u'N'
                    elif type_ == Value.PERCENTAGE:
                        if HSL:
                            # save as percentage fraction
                            raw.append(item.value.value / 100.0)
                        else:
                            # save as real value of percentage of 255
                            raw.append(int(255 * item.value.value / 100))
                        check += u'P'

                if HSL:
                    # convert to rgb
                    # h is 360 based (circle)
                    h, s, l = raw[0] / 360.0, raw[1], raw[2]
                    # ORDER h l s !!!
                    r, g, b = colorsys.hls_to_rgb(h, l, s)
                    # back to 255 based
                    rgba = [int(round(r*255)),
                            int(round(g*255)),
                            int(round(b*255))]

                    if len(raw) > 3:
                        rgba.append(raw[3])

                else:
                    # rgb, rgba
                    rgba = raw

                if len(rgba) < 4:
                    rgba.append(1.0)

                # validate
                checks = {u'rgb(': ('NNN', 'PPP'),
                         u'rgba(': ('NNNN', 'PPPN'),
                         u'hsl(': ('NPP',),
                         u'hsla(': ('NPPN',)
                         }
                if check not in checks[functiontype]:
                    self._log.error(u'ColorValue has invalid %s) parameters: '
                                    u'%s (N=Number, P=Percentage)' %
                                    (functiontype, check))

            self._colorType = t
            self._red, self._green, self._blue, self._alpha = tuple(rgba)
            self._setSeq(seq)
예제 #22
0
    def _setMediaText(self, mediaText):
        """
        :param mediaText:
            simple value or comma-separated list of media

        :exceptions:
            - - :exc:`~xml.dom.SyntaxErr`:
              Raised if the specified string value has a syntax error and is
              unparsable.
            - - :exc:`~xml.dom.NoModificationAllowedErr`:
              Raised if this media list is readonly.
        """
        self._checkReadonly()

        mediaquery = lambda: Prod(
            name='MediaQueryStart',
            match=lambda t, v: t == 'IDENT' or v == '(',
            toSeq=lambda t, tokens:
            ('MediaQuery', MediaQuery(pushtoken(t, tokens), _partof=True)))
        prods = Sequence(
            Sequence(PreDef.comment(parent=self), minmax=lambda: (0, None)),
            mediaquery(),
            Sequence(PreDef.comma(toSeq=False),
                     mediaquery(),
                     minmax=lambda: (0, None)))
        # parse
        ok, seq, store, unused = ProdParser().parse(mediaText,
                                                    'MediaList',
                                                    prods,
                                                    debug="ml")

        # each mq must be valid
        atleastone = False

        for item in seq:
            v = item.value
            if isinstance(v, MediaQuery):
                if not v.wellformed:
                    ok = False
                    break
                else:
                    atleastone = True

        # must be at least one value!
        if not atleastone:
            ok = False
            self._wellformed = ok
            self._log.error('MediaQuery: No content.', error=xml.dom.SyntaxErr)

        self._wellformed = ok

        if ok:
            mediaTypes = []
            finalseq = cssutils.util.Seq(readonly=False)
            commentseqonly = cssutils.util.Seq(readonly=False)
            for item in seq:
                # filter for doubles?
                if item.type == 'MediaQuery':
                    mediaType = item.value.mediaType
                    if mediaType:
                        if mediaType == 'all':
                            # remove anthing else and keep all+comments(!) only
                            finalseq = commentseqonly
                            finalseq.append(item)
                            break
                        elif mediaType in mediaTypes:
                            continue
                        else:
                            mediaTypes.append(mediaType)
                elif isinstance(item.value,
                                cssutils.css.csscomment.CSSComment):
                    commentseqonly.append(item)

                finalseq.append(item)

            self._setSeq(finalseq)
예제 #23
0
    def _setCssText(self, cssText):  # noqa: C901
        self._checkReadonly()
        types = self._prods  # rename!

        component = Choice(
            PreDef.unary(toSeq=lambda t, tokens: (
                t[0],
                DimensionValue(pushtoken(t, tokens), parent=self),
            )),
            PreDef.number(toSeq=lambda t, tokens: (
                t[0],
                DimensionValue(pushtoken(t, tokens), parent=self),
            )),
            PreDef.percentage(toSeq=lambda t, tokens: (
                t[0],
                DimensionValue(pushtoken(t, tokens), parent=self),
            )),
        )
        noalp = Sequence(
            Prod(
                name='FUNCTION',
                match=lambda t, v: t == types.FUNCTION and v in
                ('rgb(', 'hsl('),
                toSeq=lambda t, tokens: (t[0], normalize(t[1])),
            ),
            component,
            Sequence(PreDef.comma(optional=True),
                     component,
                     minmax=lambda: (2, 2)),
            PreDef.funcEnd(stop=True),
        )
        witha = Sequence(
            Prod(
                name='FUNCTION',
                match=lambda t, v: t == types.FUNCTION and v in
                ('rgba(', 'hsla('),
                toSeq=lambda t, tokens: (t[0], normalize(t[1])),
            ),
            component,
            Sequence(PreDef.comma(optional=True),
                     component,
                     minmax=lambda: (3, 3)),
            PreDef.funcEnd(stop=True),
        )
        namedcolor = Prod(
            name='Named Color',
            match=lambda t, v: t == 'IDENT' and
            (normalize(v) in list(self.COLORS.keys())),
            stop=True,
        )

        prods = Choice(PreDef.hexcolor(stop=True), namedcolor, noalp, witha)

        ok, seq, store, unused = ProdParser().parse(cssText, self.type, prods)
        self.wellformed = ok
        if ok:
            t, v = seq[0].type, seq[0].value
            if 'IDENT' == t:
                rgba = self.COLORS[normalize(v)]
            if 'HASH' == t:
                if len(v) == 4:
                    # HASH #rgb
                    rgba = (
                        int(2 * v[1], 16),
                        int(2 * v[2], 16),
                        int(2 * v[3], 16),
                        1.0,
                    )
                else:
                    # HASH #rrggbb
                    rgba = (int(v[1:3], 16), int(v[3:5], 16), int(v[5:7],
                                                                  16), 1.0)

            elif 'FUNCTION' == t:
                functiontype, raw, check = None, [], ''
                HSL = False

                for item in seq:
                    try:
                        type_ = item.value.type
                    except AttributeError:
                        # type of function, e.g. rgb(
                        if item.type == 'FUNCTION':
                            functiontype = item.value
                            HSL = functiontype in ('hsl(', 'hsla(')
                        continue

                    # save components
                    if type_ == Value.NUMBER:
                        raw.append(item.value.value)
                        check += 'N'
                    elif type_ == Value.PERCENTAGE:
                        if HSL:
                            # save as percentage fraction
                            raw.append(item.value.value / 100.0)
                        else:
                            # save as real value of percentage of 255
                            raw.append(int(255 * item.value.value / 100))
                        check += 'P'

                if HSL:
                    # convert to rgb
                    # h is 360 based (circle)
                    h, s, l_ = raw[0] / 360.0, raw[1], raw[2]
                    # ORDER h l s !!!
                    r, g, b = colorsys.hls_to_rgb(h, l_, s)
                    # back to 255 based
                    rgba = [
                        int(round(r * 255)),
                        int(round(g * 255)),
                        int(round(b * 255)),
                    ]

                    if len(raw) > 3:
                        rgba.append(raw[3])

                else:
                    # rgb, rgba
                    rgba = raw

                if len(rgba) < 4:
                    rgba.append(1.0)

                # validate
                checks = {
                    'rgb(': ('NNN', 'PPP'),
                    'rgba(': ('NNNN', 'PPPN'),
                    'hsl(': ('NPP', ),
                    'hsla(': ('NPPN', ),
                }
                if check not in checks[functiontype]:
                    self._log.error('ColorValue has invalid %s) parameters: '
                                    '%s (N=Number, P=Percentage)' %
                                    (functiontype, check))

            self._colorType = t
            self._red, self._green, self._blue, self._alpha = tuple(rgba)
            self._setSeq(seq)
예제 #24
0
파일: value.py 프로젝트: kgn/cssutils
    def _setCssText(self, cssText):
        self._checkReadonly()
        types = self._prods # rename!

        component = Choice(PreDef.unary(toSeq=lambda t, tokens: (t[0], 
                            DimensionValue(pushtoken(t, tokens),
                            parent=self)
                           )),
                           PreDef.number(toSeq=lambda t, tokens: (t[0], 
                            DimensionValue(pushtoken(t, tokens),
                            parent=self)
                           )),
                           PreDef.percentage(toSeq=lambda t, tokens: (t[0], 
                            DimensionValue(pushtoken(t, tokens),
                            parent=self)
                           ))
                   )
        noalp = Sequence(Prod(name='FUNCTION',
                              match=lambda t, v: t == types.FUNCTION and
                                                 v in (u'rgb(', u'hsl('),
                              toSeq=lambda t, tokens: (t[0], normalize(t[1]))),
                          component,
                          Sequence(PreDef.comma(), 
                                   component,
                                   minmax=lambda: (2, 2)
                                   ),
                          PreDef.funcEnd(stop=True)
                          )
        witha = Sequence(Prod(name='FUNCTION',
                              match=lambda t, v: t == types.FUNCTION and
                                                 v in (u'rgba(', u'hsla('),
                              toSeq=lambda t, tokens: (t[0], 
                                 normalize(t[1]))
                              ),
                          component,
                          Sequence(PreDef.comma(), 
                                   component,
                                   minmax=lambda: (3, 3)
                                   ),
                          PreDef.funcEnd(stop=True)
                          )
        namedcolor = Prod(name='Named Color',
                     match=lambda t, v: t == 'IDENT' and (
                                        normalize(v) in self.COLORS.keys()
                                        ),
                     stop=True)
        
        prods = Choice(PreDef.hexcolor(stop=True), 
                       namedcolor, 
                       noalp, 
                       witha)
        
        ok, seq, store, unused = ProdParser().parse(cssText, 
                                                    self.type,
                                                    prods)
        if ok:
            t, v = seq[0].type, seq[0].value
            if u'IDENT' == t:
                rgba = self.COLORS[normalize(v)]
            if u'HASH' == t:
                if len(v) == 4:
                    # HASH #rgb
                    rgba = (int(2*v[1], 16),
                            int(2*v[1], 16),
                            int(2*v[1], 16), 
                            1.0)
                else:
                    # HASH #rrggbb
                    rgba = (int(v[1:3], 16),
                            int(v[3:5], 16),
                            int(v[5:7], 16), 
                            1.0)
                    
            elif u'FUNCTION' == t:
                functiontype, rgba, check = None, [], u''
                for item in seq:
                    try:
                        type_ = item.value.type
                    except AttributeError, e:
                        # type of function, e.g. rgb(
                        if item.type == 'FUNCTION':
                            functiontype = item.value
                        continue

                    # save components                    
                    if type_ == Value.NUMBER:
                        rgba.append(item.value.value)
                        check += u'N'
                    elif type_ == Value.PERCENTAGE:
                        rgba.append(int(255 * item.value.value / 100))
                        check += u'P'
                        
                # validate
                checks = {u'rgb(': ('NNN', 'PPP'),
                         u'rgba(': ('NNNN', 'PPPN'),
                         u'hsl(': ('NPP',),
                         u'hsla(': ('NPPN',)
                         }
                if check not in checks[functiontype]:
                    self._log.error(u'ColorValue has invalid %s) parameters: '
                                    u'%s (N=Number, P=Percentage)' % 
                                    (functiontype, check))
                    
                if len(rgba) < 4:
                    rgba.append(1.0)
            
            self._colorType = t
            self._red, self._green, self._blue, self._alpha = tuple(rgba)
            self._setSeq(seq)
            self.wellformed = ok
예제 #25
0
def _CSSFunctionProd(parent, nextSor=False):
    return PreDef.function(nextSor=nextSor,
                           toSeq=lambda t, tokens:
                           (CSSFunction._functionName,
                            CSSFunction(pushtoken(t, tokens), parent=parent)))
    def _setMediaText(self, mediaText):
        """
        :param mediaText:
            simple value or comma-separated list of media

        :exceptions:
            - - :exc:`~xml.dom.SyntaxErr`:
              Raised if the specified string value has a syntax error and is
              unparsable.
            - - :exc:`~xml.dom.NoModificationAllowedErr`:
              Raised if this media list is readonly.
        """
        self._checkReadonly()


        mediaquery = lambda: Prod(name='MediaQueryStart',
                                  match=lambda t, v: t == 'IDENT' or v == u'(',
                                  toSeq=lambda t, tokens: ('MediaQuery', 
                                                           MediaQuery(pushtoken(t, tokens),
                                                                      _partof=True))
                                  )
        prods = Sequence(Sequence(PreDef.comment(parent=self),
                                  minmax=lambda: (0, None)
                                  ),
                         mediaquery(),
                         Sequence(PreDef.comma(toSeq=False),
                                  mediaquery(),
                                  minmax=lambda: (0, None))

                         )
        # parse
        ok, seq, store, unused = ProdParser().parse(mediaText,
                                                    u'MediaList',
                                                    prods, debug="ml")

        # each mq must be valid
        atleastone = False

        for item in seq:
            v = item.value
            if isinstance(v, MediaQuery):
               if not v.wellformed:
                   ok = False
                   break
               else:
                   atleastone = True

        # must be at least one value!
        if not atleastone:
            ok = False
            self._wellformed = ok
            self._log.error(u'MediaQuery: No content.',
                            error=xml.dom.SyntaxErr)

        self._wellformed = ok

        if ok: 
            mediaTypes = []
            finalseq = cssutils.util.Seq(readonly=False)
            commentseqonly = cssutils.util.Seq(readonly=False)
            for item in seq:
                # filter for doubles?
                if item.type == 'MediaQuery':
                    mediaType = item.value.mediaType
                    if mediaType:
                        if mediaType == u'all':
                            # remove anthing else and keep all+comments(!) only
                            finalseq = commentseqonly
                            finalseq.append(item)
                            break
                        elif mediaType in mediaTypes:
                            continue
                        else:
                            mediaTypes.append(mediaType)
                elif isinstance(item.value, cssutils.css.csscomment.CSSComment):
                    commentseqonly.append(item) 
                
                finalseq.append(item)

            self._setSeq(finalseq)
예제 #27
0
    def _setCssText(self, cssText):
        self._checkReadonly()
        types = self._prods  # rename!

        component = Choice(
            PreDef.unary(toSeq=lambda t, tokens: (t[
                0], DimensionValue(pushtoken(t, tokens), parent=self))),
            PreDef.number(toSeq=lambda t, tokens: (t[
                0], DimensionValue(pushtoken(t, tokens), parent=self))),
            PreDef.percentage(toSeq=lambda t, tokens: (t[
                0], DimensionValue(pushtoken(t, tokens), parent=self))))
        noalp = Sequence(
            Prod(name='FUNCTION',
                 match=lambda t, v: t == types.FUNCTION and v in
                 (u'rgb(', u'hsl('),
                 toSeq=lambda t, tokens: (t[0], normalize(t[1]))), component,
            Sequence(PreDef.comma(), component, minmax=lambda: (2, 2)),
            PreDef.funcEnd(stop=True))
        witha = Sequence(
            Prod(name='FUNCTION',
                 match=lambda t, v: t == types.FUNCTION and v in
                 (u'rgba(', u'hsla('),
                 toSeq=lambda t, tokens: (t[0], normalize(t[1]))), component,
            Sequence(PreDef.comma(), component, minmax=lambda: (3, 3)),
            PreDef.funcEnd(stop=True))
        namedcolor = Prod(name='Named Color',
                          match=lambda t, v: t == 'IDENT' and
                          (normalize(v) in self.COLORS.keys()),
                          stop=True)

        prods = Choice(PreDef.hexcolor(stop=True), namedcolor, noalp, witha)

        ok, seq, store, unused = ProdParser().parse(cssText, self.type, prods)
        if ok:
            t, v = seq[0].type, seq[0].value
            if u'IDENT' == t:
                rgba = self.COLORS[normalize(v)]
            if u'HASH' == t:
                if len(v) == 4:
                    # HASH #rgb
                    rgba = (int(2 * v[1], 16), int(2 * v[1],
                                                   16), int(2 * v[1], 16), 1.0)
                else:
                    # HASH #rrggbb
                    rgba = (int(v[1:3], 16), int(v[3:5], 16), int(v[5:7],
                                                                  16), 1.0)

            elif u'FUNCTION' == t:
                functiontype, rgba, check = None, [], u''
                for item in seq:
                    try:
                        type_ = item.value.type
                    except AttributeError, e:
                        # type of function, e.g. rgb(
                        if item.type == 'FUNCTION':
                            functiontype = item.value
                        continue

                    # save components
                    if type_ == Value.NUMBER:
                        rgba.append(item.value.value)
                        check += u'N'
                    elif type_ == Value.PERCENTAGE:
                        rgba.append(int(255 * item.value.value / 100))
                        check += u'P'

                # validate
                checks = {
                    u'rgb(': ('NNN', 'PPP'),
                    u'rgba(': ('NNNN', 'PPPN'),
                    u'hsl(': ('NPP', ),
                    u'hsla(': ('NPPN', )
                }
                if check not in checks[functiontype]:
                    self._log.error(u'ColorValue has invalid %s) parameters: '
                                    u'%s (N=Number, P=Percentage)' %
                                    (functiontype, check))

                if len(rgba) < 4:
                    rgba.append(1.0)

            self._colorType = t
            self._red, self._green, self._blue, self._alpha = tuple(rgba)
            self._setSeq(seq)
            self.wellformed = ok