cssutils-1.0.2/0000755000175000017500000000000013056507504011472 5ustar hlehlecssutils-1.0.2/examples/0000755000175000017500000000000013056507504013310 5ustar hlehlecssutils-1.0.2/examples/codec.py0000644000175000017500000000031312625431016014727 0ustar hlehle"""codec usage example """ import codecs import cssutils cssText = codecs.open('../sheets/cases.css', encoding='css').read() sheet = cssutils.parseString(cssText) print sheet print sheet.cssTextcssutils-1.0.2/examples/testutil.py0000644000175000017500000000547712625431016015547 0ustar hlehle# -*- coding: utf-8 -*- """test utils for tests of examples A module to test must have: - main(): a method - EXPOUT: string which contains expected output - EXPERR: string which contains expected error output """ __all__ = ['TestUtil'] import logging import os import StringIO import sys import cssutils PY2x = sys.version_info < (3,0) class OutReplacement(object): "io.StringIO does not work somehow?!" def __init__(self): self.t = '' def write(self, t): if not PY2x: # py3 hack if t.startswith('b') and t.endswith("'"): t = t[2:-1] self.t += t def getvalue(self): if not PY2x: # py3 hack self.t = self.t.replace('\\n', '\n') self.t = self.t.replace('\\\\', '\\') return self.t class TestUtil(object): def __init__(self): "init out and err to catch both" self._out = OutReplacement()#StringIO() sys.stdout = self._out self._err = StringIO.StringIO() hdlr = logging.StreamHandler(self._err) cssutils.log._log.addHandler(hdlr) def end(self, expo, expe): "return out, err" sys.stdout = sys.__stdout__ out = self._out.getvalue() err = self._err.getvalue() ok = (out == expo and err == expe) if not ok: print if out != expo: print '### out:\n%r\n### != expout:\n%r\n' % (out, expo) else: print '### err:\n%r\n### != experr:\n%r\n' % (err, expe) return ok modules = 0 errors = 0 def mod(module): global modules, errors modules += 1 t = TestUtil() module.main() ok = t.end(module.EXPOUT, module.EXPERR) if not ok: errors += 1 print '---', ok, ':', os.path.basename(module.__file__) print def main(): if PY2x: print "DOCTESTS:::::::::::::" # doctests import website import doctest doctest.testmod(website) print print 80*'-' print print global modules, errors import build mod(build) import customlog mod(customlog) import imports mod(imports) import parse mod(parse) import selectors_tolower mod(selectors_tolower) import cssencodings mod(cssencodings) import minify mod(minify) print print 80*'-' print 'Ran %i tests (%i errors).' % (modules, errors) if PY2x: print '**Check doctest results above!**' else: print 'doctests do not work in Python 3 (yet?)!' if __name__ == '__main__': main() cssutils-1.0.2/examples/parse.py0000644000175000017500000000255712625431016015000 0ustar hlehle# -*- coding: utf-8 -*- import cssutils import xml.dom EXPOUT = '''\n--- source CSS ---\n/* This is a comment */\n body {\n background: white;\n top: red;\n x: 1;\n }\n a { y }\n \n\n--- simple parsing ---\n/* This is a comment */\nbody {\n background: white;\n top: red;\n x: 1\n }\n\n--- CSSParser(raiseExceptions=True) ---\n:::RAISED::: Property: No ":" after name found: y [7:10: ]\n''' EXPERR = u'Property: Invalid value for "CSS Level 2.1" property: red [4:9: top]\nProperty: Unknown Property name. [5:9: x]\nProperty: No ":" after name found: y [7:10: ]\nProperty: No property value found: y [7:10: ]\nCSSStyleDeclaration: Syntax Error in Property: y \nProperty: Invalid value for "CSS Level 2.1" property: red [4:9: top]\nProperty: Unknown Property name. [5:9: x]\n' def main(): css = '''/* This is a comment */ body { background: white; top: red; x: 1; } a { y } ''' print "\n--- source CSS ---" print css print "\n--- simple parsing ---" c1 = cssutils.parseString(css) print c1.cssText print "\n--- CSSParser(raiseExceptions=True) ---" p = cssutils.CSSParser(raiseExceptions=True) try: c2 = p.parseString(css) except xml.dom.DOMException, e: print ":::RAISED:::", e if __name__ == '__main__': main()cssutils-1.0.2/examples/styledeclaration.py0000644000175000017500000000245112625431016017225 0ustar hlehleimport cssutils def show(style): print "style.length ==", style.length print "style.item(0) ==", style.item(0) print "style.item(1) ==", style.item(1) print "style.getProperties('color', all=True) == [" for x in style.getProperties('color', all=True): print "\t", x.cssText print "\t]" print "style.getPropertyValue('color') ==", style.getPropertyValue('color'), '\n' styledeclaration = ''' x:1; color: yellow; color: red; c\olor: green !important; c\olor: blue; FONT-FAMILY: serif; ''' print "\nGiven styledeclaration:" print styledeclaration print "------------" print "setting cssText" style = cssutils.css.CSSStyleDeclaration(cssText=styledeclaration) show(style) print "------------" # overwrite in any case print "style.setProperty('color', 'yellow','!important')" style.setProperty('color', 'yellow','!important') show(style) # overwrite in any case, even !important print "style.setProperty('color', 'red')" style.setProperty('color', 'red') show(style) print "------------" # overwrite in any case, even !important print "style.setProperty('color', 'green', '!important')" style.setProperty('color', 'green', '!important') show(style) # overwrite in any case, even !important print "style.setProperty('color', 'blue')" style.setProperty('color', 'blue') show(style) cssutils-1.0.2/examples/minify.py0000644000175000017500000000116112625431016015147 0ustar hlehleimport logging, StringIO EXPOUT = "@variables{c:#0f0}a{color:var(c)}\na{color:#0f0}\n" EXPERR = u'Property: Found valid "CSS Level 2.1" value: #0f0 [6:9: color]\n' def main(): import cssutils import cssutils.script css = ''' @variables { c: #0f0; } a { color: var(c); } ''' s = cssutils.parseString(css) cssutils.ser.prefs.useMinified() cssutils.ser.prefs.resolveVariables = False print s.cssText # reset cssutils.ser.prefs.resolveVariables = True print s.cssText if __name__ == '__main__': main()cssutils-1.0.2/examples/style.py0000644000175000017500000001753112625431016015024 0ustar hlehle# -*- coding: utf-8 -*- """ example renderer moves infos from external stylesheet "css" to internal @style attributes and for debugging also in @title attributes. adds css as text to html """ from pprint import pprint import codecs import cssutils import os import sys import webbrowser # lxml egg may be in a lib dir below this file (not in SVN though) sys.path.append(os.path.join(os.path.dirname(__file__), 'lib')) try: import pkg_resources pkg_resources.require('lxml') except pkg_resources.DistributionNotFound, e: pass try: from lxml import etree from lxml.builder import E from lxml.cssselect import CSSSelector except ImportError, e: print 'You need lxml for this example:', e sys.exit(1) def log(level, *msg): """print '%s- %s' % (level * '\t ', ' '.join((str(m) for m in msg)))""" def getDocument(html, css=None): """ returns a DOM of html, if css is given it is appended to html/body as pre.cssutils """ document = etree.HTML(html) if css: # prepare document (add css for debugging) e = etree.Element('pre', {'class': 'cssutils'}) e.text = css document.find('body').append(e) return document def styleattribute(element): "returns css.CSSStyleDeclaration of inline styles, for html: @style" cssText = element.get('style') if cssText: return cssutils.css.CSSStyleDeclaration(cssText=cssText) else: return None def getView(document, css, media='all', name=None, styleCallback=lambda element: None): """ document a DOM document, currently an lxml HTML document css a CSS StyleSheet string media: optional TODO: view for which media it should be name: optional TODO: names of sheets only styleCallback: optional should return css.CSSStyleDeclaration of inline styles, for html a style declaration for ``element@style``. Gets one parameter ``element`` which is the relevant DOMElement returns style view a dict of {DOMElement: css.CSSStyleDeclaration} for html """ sheet = cssutils.parseString(css) view = {} specificities = {} # needed temporarily # TODO: filter rules simpler?, add @media rules = (rule for rule in sheet if rule.type == rule.STYLE_RULE) for rule in rules: for selector in rule.selectorList: log(0, 'SELECTOR', selector.selectorText) # TODO: make this a callback to be able to use other stuff than lxml cssselector = CSSSelector(selector.selectorText) matching = cssselector.evaluate(document) for element in matching: #if element.tag in ('div',): # add styles for all matching DOM elements log(1, 'ELEMENT', id(element), element.text) if element not in view: # add initial empty style declatation view[element] = cssutils.css.CSSStyleDeclaration() specificities[element] = {} # and add inline @style if present inlinestyle = styleCallback(element) if inlinestyle: for p in inlinestyle: # set inline style specificity view[element].setProperty(p) specificities[element][p.name] = (1,0,0,0) for p in rule.style: # update style declaration if p not in view[element]: # setProperty needs a new Property object and # MUST NOT reuse the existing Property # which would be the same for all elements! # see Issue #23 view[element].setProperty(p.name, p.value, p.priority) specificities[element][p.name] = selector.specificity log(2, view[element].getProperty('color')) else: log(2, view[element].getProperty('color')) sameprio = (p.priority == view[element].getPropertyPriority(p.name)) if not sameprio and bool(p.priority) or ( sameprio and selector.specificity >= specificities[element][p.name]): # later, more specific or higher prio view[element].setProperty(p.name, p.value, p.priority) #pprint(view) return view def render2style(document, view): """ - add style into @style attribute - add style into @title attribute (for debugging) """ for element, style in view.items(): v = style.getCssText(separator=u'') element.set('style', v) element.set('title', v) def render2content(document, view, css): """ - add css as class CSSCaptureHTMLParser(HTMLParser.HTMLParser): """CSSCapture helper: Parse given data for link and style elements""" curtag = u'' sheets = [] # (type, [atts, cssText]) def _loweratts(self, atts): return dict([(a.lower(), v.lower()) for a, v in atts]) def handle_starttag(self, tag, atts): if tag == u'link': atts = self._loweratts(atts) if u'text/css' == atts.get(u'type', u''): self.sheets.append((LINK, atts)) elif tag == u'style': # also get content of style atts = self._loweratts(atts) if u'text/css' == atts.get(u'type', u''): self.sheets.append((STYLE, [atts, u''])) self.curtag = tag else: # close as only intersting