~n-muench/+junk/cssutils

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
"""CSSUnknownRule implements DOM Level 2 CSS CSSUnknownRule."""
__all__ = ['CSSUnknownRule']
__docformat__ = 'restructuredtext'
__version__ = '$Id: cssunknownrule.py 1949 2010-03-26 22:16:33Z cthedot $'

import cssrule
import cssutils
import xml.dom

class CSSUnknownRule(cssrule.CSSRule):
    """
    Represents an at-rule not supported by this user agent, so in 
    effect all other at-rules not defined in cssutils.

    Format::

        @xxx until ';' or block {...}
    """
    def __init__(self, cssText=u'', parentRule=None, 
                 parentStyleSheet=None, readonly=False):
        """
        :param cssText:
            of type string
        """
        super(CSSUnknownRule, self).__init__(parentRule=parentRule, 
                                             parentStyleSheet=parentStyleSheet)
        self._atkeyword = None
        if cssText:
            self.cssText = cssText

        self._readonly = readonly

    def __repr__(self):
        return u"cssutils.css.%s(cssText=%r)" % (
                self.__class__.__name__,
                self.cssText)
        
    def __str__(self):
        return u"<cssutils.css.%s object cssText=%r at 0x%x>" % (
                self.__class__.__name__,
                self.cssText,
                id(self))

    def _getCssText(self):
        """Return serialized property cssText."""
        return cssutils.ser.do_CSSUnknownRule(self)

    def _setCssText(self, cssText):
        """
        :exceptions:
            - :exc:`~xml.dom.SyntaxErr`:
              Raised if the specified CSS string value has a syntax error and
              is unparsable.
            - :exc:`~xml.dom.InvalidModificationErr`:
              Raised if the specified CSS string value represents a different
              type of rule than the current one.
            - :exc:`~xml.dom.HierarchyRequestErr`:
              Raised if the rule cannot be inserted at this point in the
              style sheet.
            - :exc:`~xml.dom.NoModificationAllowedErr`:
              Raised if the rule is readonly.
        """
        super(CSSUnknownRule, self)._setCssText(cssText)
        tokenizer = self._tokenize2(cssText)
        attoken = self._nexttoken(tokenizer, None)
        if not attoken or self._type(attoken) != self._prods.ATKEYWORD:
            self._log.error(u'CSSUnknownRule: No CSSUnknownRule found: %s' %
                self._valuestr(cssText),
                error=xml.dom.InvalidModificationErr)
        else:
            # for closures: must be a mutable
            new = {'nesting': [], # {} [] or ()
                   'wellformed': True
                   }

            def CHAR(expected, seq, token, tokenizer=None):
                type_, val, line, col = token
                if expected != 'EOF':
                    if val in u'{[(':
                        new['nesting'].append(val)
                    elif val in u'}])':
                        opening = {u'}': u'{', u']': u'[', u')': u'('}[val]
                        try:
                            if new['nesting'][-1] == opening:
                                new['nesting'].pop()
                            else:
                                raise IndexError()
                        except IndexError:
                            new['wellformed'] = False
                            self._log.error(u'CSSUnknownRule: Wrong nesting of '
                                            u'{, [ or (.', token=token)
    
                    if val in u'};' and not new['nesting']:
                        expected = 'EOF' 
    
                    seq.append(val, type_, line=line, col=col)
                    return expected
                else:
                    new['wellformed'] = False
                    self._log.error(u'CSSUnknownRule: Expected end of rule.',
                                    token=token)
                    return expected

            def FUNCTION(expected, seq, token, tokenizer=None):
                # handled as opening (
                type_, val, line, col = token
                val = self._tokenvalue(token)
                if expected != 'EOF':
                    new['nesting'].append(u'(')
                    seq.append(val, type_, line=line, col=col)
                    return expected
                else:
                    new['wellformed'] = False
                    self._log.error(u'CSSUnknownRule: Expected end of rule.',
                                    token=token)
                    return expected                

            def EOF(expected, seq, token, tokenizer=None):
                "close all blocks and return 'EOF'"
                for x in reversed(new['nesting']):
                    closing = {u'{': u'}', u'[': u']', u'(': u')'}[x]
                    seq.append(closing, closing)
                new['nesting'] = []
                return 'EOF'
                
            def INVALID(expected, seq, token, tokenizer=None):
                # makes rule invalid
                self._log.error(u'CSSUnknownRule: Bad syntax.',
                                token=token, error=xml.dom.SyntaxErr)
                new['wellformed'] = False
                return expected

            def STRING(expected, seq, token, tokenizer=None):
                type_, val, line, col = token
                val = self._stringtokenvalue(token)
                if expected != 'EOF':
                    seq.append(val, type_, line=line, col=col)
                    return expected
                else:
                    new['wellformed'] = False
                    self._log.error(u'CSSUnknownRule: Expected end of rule.',
                                    token=token)
                    return expected                

            def URI(expected, seq, token, tokenizer=None):
                type_, val, line, col = token
                val = self._uritokenvalue(token)
                if expected != 'EOF':
                    seq.append(val, type_, line=line, col=col)
                    return expected
                else:
                    new['wellformed'] = False
                    self._log.error(u'CSSUnknownRule: Expected end of rule.',
                                    token=token)
                    return expected                

            def default(expected, seq, token, tokenizer=None):
                type_, val, line, col = token
                if expected != 'EOF':
                    seq.append(val, type_, line=line, col=col)
                    return expected
                else:
                    new['wellformed'] = False
                    self._log.error(u'CSSUnknownRule: Expected end of rule.',
                                    token=token)
                    return expected                

            # unknown : ATKEYWORD S* ... ; | }
            newseq = self._tempSeq()
            wellformed, expected = self._parse(expected=None,
                seq=newseq, tokenizer=tokenizer,
                productions={'CHAR': CHAR,
                             'EOF': EOF,
                             'FUNCTION': FUNCTION,
                             'INVALID': INVALID,
                             'STRING': STRING,
                             'URI': URI,
                             'S': default # overwrite default default!
                }, 
                default=default,
                new=new)

            # wellformed set by parse
            wellformed = wellformed and new['wellformed']
            
            # post conditions
            if expected != 'EOF':
                wellformed = False
                self._log.error(u'CSSUnknownRule: No ending ";" or "}" found: '
                                u'%r' % self._valuestr(cssText))
            elif new['nesting']:
                wellformed = False
                self._log.error(u'CSSUnknownRule: Unclosed "{", "[" or "(": %r'
                                % self._valuestr(cssText))

            # set all
            if wellformed:
                self.atkeyword = self._tokenvalue(attoken)
                self._setSeq(newseq)

    cssText = property(fget=_getCssText, fset=_setCssText,
                       doc=u"(DOM) The parsable textual representation.")
    
    type = property(lambda self: self.UNKNOWN_RULE, 
                    doc=u"The type of this rule, as defined by a CSSRule "
                        u"type constant.")
    
    wellformed = property(lambda self: bool(self.atkeyword))