<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################


import sys
import copy
import reportlab
import re
from reportlab.pdfgen import canvas
from reportlab import platypus
import utils
import color
import os
import logging
from lxml import etree
import base64
from reportlab.platypus.doctemplate import ActionFlowable
from openerp.tools.safe_eval import safe_eval as eval
from reportlab.lib.units import inch,cm,mm
from openerp.tools.misc import file_open
from reportlab.pdfbase import pdfmetrics
from reportlab.lib.pagesizes import A4, letter

try:
    from cStringIO import StringIO
    _hush_pyflakes = [ StringIO ]
except ImportError:
    from StringIO import StringIO

_logger = logging.getLogger(__name__)

encoding = 'utf-8'

def select_fontname(fontname, default_fontname):
    if fontname not in pdfmetrics.getRegisteredFontNames()\
         or fontname not in pdfmetrics.standardFonts:
        # let reportlab attempt to find it
        try:
            pdfmetrics.getFont(fontname)
        except Exception:
            _logger.warning('Could not locate font %s, substituting default: %s',
                fontname, default_fontname)
            fontname = default_fontname
    return fontname


def _open_image(filename, path=None):
    """Attempt to open a binary file and return the descriptor
    """
    if os.path.isfile(filename):
        return open(filename, 'rb')
    for p in (path or []):
        if p and os.path.isabs(p):
            fullpath = os.path.join(p, filename)
            if os.path.isfile(fullpath):
                return open(fullpath, 'rb')
        try:
            if p:
                fullpath = os.path.join(p, filename)
            else:
                fullpath = filename
            return file_open(fullpath)
        except IOError:
            pass
    raise IOError("File %s cannot be found in image path" % filename)

class NumberedCanvas(canvas.Canvas):
    def __init__(self, *args, **kwargs):
        canvas.Canvas.__init__(self, *args, **kwargs)
        self._codes = []
        self._flag=False
        self._pageCount=0
        self._currentPage =0
        self._pageCounter=0
        self.pages={}

    def showPage(self):
        self._currentPage +=1
        if not self._flag:
            self._pageCount += 1
        else:
            self.pages.update({self._currentPage:self._pageCount})
        self._codes.append({'code': self._code, 'stack': self._codeStack})
        self._startPage()
        self._flag=False

    def pageCount(self):
        if self.pages.get(self._pageCounter,False):
            self._pageNumber=0
        self._pageCounter +=1
        key=self._pageCounter
        if not self.pages.get(key,False):
            while not self.pages.get(key,False):
                key += 1
        self.setFont("Helvetica", 8)
        self.drawRightString((self._pagesize[0]-30), (self._pagesize[1]-40),
            " %(this)i / %(total)i" % {
               'this': self._pageNumber+1,
               'total': self.pages.get(key,False),
            }
        )

    def save(self):
        """add page info to each page (page x of y)"""
        # reset page counter
        self._pageNumber = 0
        for code in self._codes:
            self._code = code['code']
            self._codeStack = code['stack']
            self.pageCount()
            canvas.Canvas.showPage(self)
#        self.restoreState()
        self._doc.SaveToFile(self._filename, self)

class PageCount(platypus.Flowable):
    def __init__(self, story_count=0):
        platypus.Flowable.__init__(self)
        self.story_count = story_count

    def draw(self):
        self.canv.beginForm("pageCount%d" % self.story_count)
        self.canv.setFont("Helvetica", utils.unit_get(str(8)))
        self.canv.drawString(0, 0, str(self.canv.getPageNumber()))
        self.canv.endForm()

class PageReset(platypus.Flowable):
    def draw(self):
        self.canv._doPageReset = True

class _rml_styles(object,):
    def __init__(self, nodes, localcontext):
        self.localcontext = localcontext
        self.styles = {}
        self.styles_obj = {}
        self.names = {}
        self.table_styles = {}
        self.default_style = reportlab.lib.styles.getSampleStyleSheet()

        for node in nodes:
            for style in node.findall('blockTableStyle'):
                self.table_styles[style.get('id')] = self._table_style_get(style)
            for style in node.findall('paraStyle'):
                sname = style.get('name')
                self.styles[sname] = self._para_style_update(style)
                if sname in self.default_style:
                    for key, value in self.styles[sname].items():                    
                        setattr(self.default_style[sname], key, value)
                else:
                    self.styles_obj[sname] = reportlab.lib.styles.ParagraphStyle(sname, self.default_style["Normal"], **self.styles[sname])
            for variable in node.findall('initialize'):
                for name in variable.findall('name'):
                    self.names[ name.get('id')] = name.get('value')<commit_msg>[FIX] trml2pdf: reportlab 2.4.4 doesn't support the previous syntax (sname in self.default_style)<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################


import sys
import copy
import reportlab
import re
from reportlab.pdfgen import canvas
from reportlab import platypus
import utils
import color
import os
import logging
from lxml import etree
import base64
from reportlab.platypus.doctemplate import ActionFlowable
from openerp.tools.safe_eval import safe_eval as eval
from reportlab.lib.units import inch,cm,mm
from openerp.tools.misc import file_open
from reportlab.pdfbase import pdfmetrics
from reportlab.lib.pagesizes import A4, letter

try:
    from cStringIO import StringIO
    _hush_pyflakes = [ StringIO ]
except ImportError:
    from StringIO import StringIO

_logger = logging.getLogger(__name__)

encoding = 'utf-8'

def select_fontname(fontname, default_fontname):
    if fontname not in pdfmetrics.getRegisteredFontNames()\
         or fontname not in pdfmetrics.standardFonts:
        # let reportlab attempt to find it
        try:
            pdfmetrics.getFont(fontname)
        except Exception:
            _logger.warning('Could not locate font %s, substituting default: %s',
                fontname, default_fontname)
            fontname = default_fontname
    return fontname


def _open_image(filename, path=None):
    """Attempt to open a binary file and return the descriptor
    """
    if os.path.isfile(filename):
        return open(filename, 'rb')
    for p in (path or []):
        if p and os.path.isabs(p):
            fullpath = os.path.join(p, filename)
            if os.path.isfile(fullpath):
                return open(fullpath, 'rb')
        try:
            if p:
                fullpath = os.path.join(p, filename)
            else:
                fullpath = filename
            return file_open(fullpath)
        except IOError:
            pass
    raise IOError("File %s cannot be found in image path" % filename)

class NumberedCanvas(canvas.Canvas):
    def __init__(self, *args, **kwargs):
        canvas.Canvas.__init__(self, *args, **kwargs)
        self._codes = []
        self._flag=False
        self._pageCount=0
        self._currentPage =0
        self._pageCounter=0
        self.pages={}

    def showPage(self):
        self._currentPage +=1
        if not self._flag:
            self._pageCount += 1
        else:
            self.pages.update({self._currentPage:self._pageCount})
        self._codes.append({'code': self._code, 'stack': self._codeStack})
        self._startPage()
        self._flag=False

    def pageCount(self):
        if self.pages.get(self._pageCounter,False):
            self._pageNumber=0
        self._pageCounter +=1
        key=self._pageCounter
        if not self.pages.get(key,False):
            while not self.pages.get(key,False):
                key += 1
        self.setFont("Helvetica", 8)
        self.drawRightString((self._pagesize[0]-30), (self._pagesize[1]-40),
            " %(this)i / %(total)i" % {
               'this': self._pageNumber+1,
               'total': self.pages.get(key,False),
            }
        )

    def save(self):
        """add page info to each page (page x of y)"""
        # reset page counter
        self._pageNumber = 0
        for code in self._codes:
            self._code = code['code']
            self._codeStack = code['stack']
            self.pageCount()
            canvas.Canvas.showPage(self)
#        self.restoreState()
        self._doc.SaveToFile(self._filename, self)

class PageCount(platypus.Flowable):
    def __init__(self, story_count=0):
        platypus.Flowable.__init__(self)
        self.story_count = story_count

    def draw(self):
        self.canv.beginForm("pageCount%d" % self.story_count)
        self.canv.setFont("Helvetica", utils.unit_get(str(8)))
        self.canv.drawString(0, 0, str(self.canv.getPageNumber()))
        self.canv.endForm()

class PageReset(platypus.Flowable):
    def draw(self):
        self.canv._doPageReset = True

class _rml_styles(object,):
    def __init__(self, nodes, localcontext):
        self.localcontext = localcontext
        self.styles = {}
        self.styles_obj = {}
        self.names = {}
        self.table_styles = {}
        self.default_style = reportlab.lib.styles.getSampleStyleSheet()

        for node in nodes:
            for style in node.findall('blockTableStyle'):
                self.table_styles[style.get('id')] = self._table_style_get(style)
            for style in node.findall('paraStyle'):
                sname = style.get('name')
                self.styles[sname] = self._para_style_update(style)
                if self.default_style.has_key(sname):
                    for key, value in self.styles[sname].items():                    
                        setattr(self.default_style[sname], key, value)
                else:
                    self.styles_obj[sname] = reportlab.lib.styles.ParagraphStyle(sname, self.default_style["Normal"], **self.styles[sname])
            for variable in node.findall('initialize'):
                for name in variable.findall('name'):
                    self.names[ name.get('id')] = name.get('value')
{'fraction_non_alphanumeric': 0.12389235313423039, 'fraction_numerical': 0.006071545782737118, 'mean_word_length': 2.439334085778781, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6634325', 'n_tokens_mistral': 3509, 'n_tokens_neox': 3398, 'n_words': 928}