Skip to content

Commit

Permalink
Merge pull request #4 from kylemacfarlane/performance
Browse files Browse the repository at this point in the history
Some performance tweaks
  • Loading branch information
strichter committed Mar 7, 2013
2 parents 3d19e6a + bce7f7f commit 761f42e
Show file tree
Hide file tree
Showing 10 changed files with 53 additions and 18 deletions.
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*.pdf -crlf diff=astextplain
*.PDF -crlf diff=astextplain
5 changes: 4 additions & 1 deletion src/z3c/rml/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@

# Hook up our custom paragraph parser.
import z3c.rml.paraparser
import z3c.rml.rlfix


from reportlab.lib.styles import getSampleStyleSheet
SampleStyleSheet = getSampleStyleSheet()
15 changes: 9 additions & 6 deletions src/z3c/rml/attr.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
import zope.schema
from lxml import etree

from z3c.rml import interfaces
from z3c.rml import interfaces, SampleStyleSheet

MISSING = object()
logger = logging.getLogger("z3c.rml")
Expand All @@ -48,7 +48,11 @@ def getManager(context, interface=None):
from z3c.rml import interfaces
interface = interfaces.IManager
# Walk up the path until the manager is found
while (not interface.providedBy(context) and context is not None):
# Using interface.providedBy is much slower because it does many more checks
while (
context is not None and
not interface in context.__class__.__dict__.get('__implemented__', {})
):
context = context.parent
# If no manager was found, raise an error
if context is None:
Expand Down Expand Up @@ -431,8 +435,7 @@ def fromUnicode(self, value):

def _getStyle(context, value):
manager = getManager(context)
for styles in (manager.styles,
reportlab.lib.styles.getSampleStyleSheet().byName):
for styles in (manager.styles, SampleStyleSheet.byName):
if value in styles:
return styles[value]
elif 'style.' + value in styles:
Expand All @@ -448,7 +451,7 @@ class Style(String):
Whether the style is a paragraph, table or box style is irrelevant, except
that it has to fit the tag.
"""
default = reportlab.lib.styles.getSampleStyleSheet().byName['Normal']
default = SampleStyleSheet.byName['Normal']

def fromUnicode(self, value):
return _getStyle(self.context, value)
Expand Down Expand Up @@ -570,7 +573,7 @@ def __init__(self, *args, **kw):
def get(self):
# ReportLab's paragraph parser does not like attributes from other
# namespaces; sigh. So we have to improvize.
text = etree.tounicode(self.context.element)
text = etree.tounicode(self.context.element, pretty_print=False)
text = text[text.find('>')+1:text.rfind('<')]
return text

Expand Down
13 changes: 12 additions & 1 deletion src/z3c/rml/directive.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

from lxml import etree
from z3c.rml import interfaces
from z3c.rml.attr import getManager

logging.raiseExceptions = False
logger = logging.getLogger("z3c.rml")
Expand Down Expand Up @@ -48,8 +49,18 @@ def __init__(self, element, parent):
def getAttributeValues(self, ignore=None, select=None, attrMapping=None,
includeMissing=False, valuesOnly=False):
"""See interfaces.IRMLDirective"""
manager = getManager(self)
cache = '%s.%s' % (self.signature.__module__, self.signature.__name__)
if cache in manager.attributesCache:
fields = manager.attributesCache[cache]
else:
fields = []
for name, attr in zope.schema.getFieldsInOrder(self.signature):
fields.append((name, attr))
manager.attributesCache[cache] = fields

items = []
for name, attr in zope.schema.getFieldsInOrder(self.signature):
for name, attr in fields:
# Only add the attribute to the list, if it is supposed there
if ((ignore is None or name not in ignore) and
(select is None or name in select)):
Expand Down
7 changes: 7 additions & 0 deletions src/z3c/rml/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -579,6 +579,7 @@ class IDocument(interfaces.IRMLDirectiveSignature):
debug = attr.Boolean(
title=u'Debug',
description=u'A flag to activate the debug output.',
default=False,
required=False)

compression = attr.BooleanWithDefault(
Expand Down Expand Up @@ -622,6 +623,7 @@ def __init__(self, element):
self.pageMode = None
self.logger = None
self.svgs = {}
self.attributesCache = {}
for name in DocInit.viewerOptions:
setattr(self, name, None)

Expand Down Expand Up @@ -649,6 +651,10 @@ def process(self, outputFile=None):
# ReportLab not to fail.
reportlab.rl_config._reset()

debug = self.getAttributeValues(select=('debug',), valuesOnly=True)[0]
if not debug:
reportlab.rl_config.shapeChecking = 0

# Add our colors mapping to the default ones.
colors.toColor.setExtraColorsNameSpace(self.colors)

Expand Down Expand Up @@ -694,6 +700,7 @@ def process(self, outputFile=None):

# Cleanup.
colors.toColor.setExtraColorsNameSpace({})
reportlab.rl_config.shapeChecking = 1

def get_name(self, name, default=None):
if default is None:
Expand Down
12 changes: 8 additions & 4 deletions src/z3c/rml/flowable.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from reportlab.lib import styles, pygments2xpre
from xml.sax.saxutils import unescape
from z3c.rml import attr, directive, interfaces, occurence
from z3c.rml import form, platypus, special, stylesheet
from z3c.rml import form, platypus, special, SampleStyleSheet, stylesheet

try:
import reportlab.graphics.barcode
Expand Down Expand Up @@ -188,7 +188,7 @@ class IPreformatted(IMinimalParagraphBase):
description=(u'The paragraph style that is applied to the paragraph. '
u'See the ``paraStyle`` tag for creating a paragraph '
u'style.'),
default=reportlab.lib.styles.getSampleStyleSheet()['Code'],
default=SampleStyleSheet['Code'],
required=False)

text = attr.RawXMLContent(
Expand Down Expand Up @@ -218,7 +218,7 @@ class IXPreformatted(IParagraphBase):
description=(u'The paragraph style that is applied to the paragraph. '
u'See the ``paraStyle`` tag for creating a paragraph '
u'style.'),
default=reportlab.lib.styles.getSampleStyleSheet()['Normal'],
default=SampleStyleSheet['Normal'],
required=False)

text = attr.RawXMLContent(
Expand Down Expand Up @@ -277,7 +277,11 @@ class Paragraph(Flowable):
styleAttributes = zope.schema.getFieldNames(stylesheet.IBaseParagraphStyle)

def processStyle(self, style):
attrs = self.getAttributeValues(select=self.styleAttributes)
attrs = []
for attr in self.styleAttributes:
if self.element.get(attr) is not None:
attrs.append(attr)
attrs = self.getAttributeValues(select=attrs)
if attrs:
style = copy.deepcopy(style)
for name, value in attrs:
Expand Down
6 changes: 5 additions & 1 deletion src/z3c/rml/rlfix.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,11 @@ def resetPdfForm():
pdfform.ZADB = PDFPattern(pdfform.ZaDbPattern)

def resetFonts():
for f in testshapes._setup():
# testshapes._setup registers the Vera fonts every time which is a little
# slow on all platforms. On Windows it lists the entire system font
# directory and registers them all which is very slow.
for f in ('Times-Roman','Courier','Helvetica','Vera', 'VeraBd', 'VeraIt',
'VeraBI'):
if f not in testshapes._FONTS:
testshapes._FONTS.append(f)

Expand Down
5 changes: 3 additions & 2 deletions src/z3c/rml/stylesheet.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
import reportlab.lib.styles
import reportlab.lib.enums
import reportlab.platypus
from z3c.rml import attr, directive, interfaces, occurence, special
from z3c.rml import attr, directive, interfaces, occurence, SampleStyleSheet, \
special


class IInitialize(interfaces.IRMLDirectiveSignature):
Expand Down Expand Up @@ -202,7 +203,7 @@ class ParagraphStyle(directive.RMLDirective):
def process(self):
kwargs = dict(self.getAttributeValues())
parent = kwargs.pop(
'parent', reportlab.lib.styles.getSampleStyleSheet()['Normal'])
'parent', SampleStyleSheet['Normal'])
name = kwargs.pop('name')
style = copy.deepcopy(parent)
style.name = name[6:] if name.startswith('style.') else name
Expand Down
Binary file not shown.
6 changes: 3 additions & 3 deletions src/z3c/rml/tests/module.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import reportlab.graphics.widgets.markers
from reportlab.graphics import renderPDF, shapes
from reportlab.lib import colors
from z3c.rml import interfaces, attr
from z3c.rml import attr, interfaces, SampleStyleSheet

def myPreformatted(params):
return reportlab.platypus.Preformatted('''
Expand All @@ -32,7 +32,7 @@ def myPreformatted(params):
plugin. Hey, this is a long text from a plugin. Hey, this is a long
text from a plugin. Hey, this is a long text from a plugin. Hey, this
is a long text from a plugin.''',
reportlab.lib.styles.getSampleStyleSheet()['Normal'])
SampleStyleSheet['Normal'])

class LinkURL(reportlab.platypus.flowables.Flowable):
def __init__(self, link):
Expand All @@ -49,7 +49,7 @@ def linkURL(params):
params = eval(params)
return (
reportlab.platypus.Paragraph(
params[0], reportlab.lib.styles.getSampleStyleSheet()['Normal']),
params[0], SampleStyleSheet['Normal']),
LinkURL(*params))

class IMarker(interfaces.IRMLDirectiveSignature):
Expand Down

0 comments on commit 761f42e

Please sign in to comment.