renderPM.py now works to produce a pmout at least py33
authorrobin
Fri, 02 Aug 2013 16:38:41 +0100
branchpy33
changeset 3765 a7e7cd6e0003
parent 3764 010823faf496
child 3766 4fa0f4494409
renderPM.py now works to produce a pmout at least
.hgignore
src/reportlab/graphics/renderPM.py
src/reportlab/graphics/renderPS.py
src/reportlab/graphics/renderSVG.py
src/reportlab/graphics/shapes.py
src/reportlab/lib/utils.py
src/reportlab/pdfbase/pdfmetrics.py
src/reportlab/pdfbase/pdfutils.py
src/reportlab/pdfbase/ttfonts.py
src/reportlab/pdfgen/canvas.py
src/reportlab/pdfgen/textobject.py
src/rl_addons/renderPM/_renderPM.c
src/rl_addons/rl_accel/_rl_accel.c
--- a/.hgignore	Thu Aug 01 17:35:55 2013 +0100
+++ b/.hgignore	Fri Aug 02 16:38:41 2013 +0100
@@ -43,6 +43,7 @@
 src/reportlab/fonts/*.ttf
 src/reportlab/graphics/barcode/*.pdf
 src/reportlab/graphics/barcode/test_cbcim.*
+src/reportlab/graphics/pmout
 tools/docco/*.pdf
 tests/test_*.pdf
 tests/test_*.svg
--- a/src/reportlab/graphics/renderPM.py	Thu Aug 01 17:35:55 2013 +0100
+++ b/src/reportlab/graphics/renderPM.py	Fri Aug 02 16:38:41 2013 +0100
@@ -22,7 +22,7 @@
 class RenderPMError(Exception):
     pass
 
-import string, os, sys
+import os, sys
 
 try:
     from reportlab.graphics import _renderPM
@@ -216,15 +216,12 @@
 def _setFont(gs,fontName,fontSize):
     try:
         gs.setFont(fontName,fontSize)
-    except _renderPM.Error as errMsg:
-        if errMsg.args[0]!="Can't find font!": raise
+    except ValueError as e:
+        if not e.args[0].endswith("Can't find font!"): raise
         #here's where we try to add a font to the canvas
         try:
             f = getFont(fontName)
-            if _renderPM._version<='0.98':  #added reader arg in 0.99
-                _renderPM.makeT1Font(fontName,f.face.findT1File(),f.encoding.vector)
-            else:
-                _renderPM.makeT1Font(fontName,f.face.findT1File(),f.encoding.vector,open_and_read)
+            _renderPM.makeT1Font(fontName,f.face.findT1File(),f.encoding.vector,open_and_read)
         except:
             s1, s2 = list(map(str,sys.exc_info()[:2]))
             raise RenderPMError("Can't setFont(%s) missing the T1 files?\nOriginally %s: %s" % (fontName,s1,s2))
@@ -246,7 +243,7 @@
     #s = _renderPM.pil2pict(cols,rows,im.tostring(),im.im.getpalette(),transparent is not None and Color2Hex(transparent) or -1)
     s = _renderPM.pil2pict(cols,rows,im.tostring(),im.im.getpalette())
     if not hasattr(fn,'write'):
-        open(os.path.splitext(fn)[0]+'.'+string.lower(fmt),'wb').write(s)
+        open(os.path.splitext(fn)[0]+'.'+fmt.lower(),'wb').write(s)
         if os.name=='mac':
             from reportlab.lib.utils import markfilename
             markfilename(fn,ext='PICT')
@@ -299,7 +296,7 @@
         preConvertCB=configPIL.pop('preConvertCB')
         if preConvertCB:
             im = preConvertCB(im)
-        fmt = string.upper(fmt)
+        fmt = fmt.upper()
         if fmt in ('GIF',):
             im = _convert2pilp(im)
         elif fmt in ('TIFF','TIFFP','TIFFL','TIF','TIFF1'):
@@ -511,7 +508,7 @@
                     fc = f
                 gs.drawString(x,y,t)
                 if i!=nm1:
-                    x += wscale*sum(map(f.widths.__getitem__,list(map(ord,t))))
+                    x += wscale*sum(map(f.widths.__getitem__,t))
             if font!=fc:
                 _setFont(gs,fontName,fontSize)
 
@@ -709,7 +706,7 @@
 
         for k in E:
             if k in ['gif','png','jpg','pct']:
-                html.append('<p>%s format</p>\n' % string.upper(k))
+                html.append('<p>%s format</p>\n' % k.upper())
             try:
                 filename = '%s.%s' % (fnRoot, ext(k))
                 fullpath = os.path.join('pmout', filename)
@@ -733,7 +730,7 @@
                 print('Problem drawing %s file'%k)
                 raise
         if os.environ.get('RL_NOEPSPREVIEW','0')=='1': drawing.__dict__['preview'] = 0
-        drawing.save(formats=['eps','pdf'],outDir='pmout',fnRoot=fnRoot)
+        #drawing.save(formats=['eps','pdf'],outDir='pmout',fnRoot=fnRoot)
     html.append(htmlBottom)
     htmlFileName = os.path.join('pmout', 'index.html')
     open(htmlFileName, 'w').writelines(html)
--- a/src/reportlab/graphics/renderPS.py	Thu Aug 01 17:35:55 2013 +0100
+++ b/src/reportlab/graphics/renderPS.py	Fri Aug 02 16:38:41 2013 +0100
@@ -4,14 +4,12 @@
 __version__=''' $Id$ '''
 __doc__="""Render drawing objects in Postscript"""
 
-import string, types
 from reportlab.pdfbase.pdfmetrics import getFont, stringWidth, unicode2T1 # for font info
-from reportlab.lib.utils import fp_str, getBytesIO
+from reportlab.lib.utils import fp_str, getBytesIO, isPy3
 from reportlab.lib.colors import black
 from reportlab.graphics.renderbase import Renderer, StateTracker, getStateDelta, renderScaledDrawing
 from reportlab.graphics.shapes import STATE_DEFAULTS
 import math
-from types import StringType
 from operator import getitem
 from reportlab import rl_config
 _ESCAPEDICT={}
@@ -25,6 +23,8 @@
     del c
 
 def _escape_and_limit(s):
+    if isPy3 and not isinstance(s,str):
+        s = s.decode('utf8')
     R = []
     aR = R.append
     n = 0
@@ -133,7 +133,7 @@
                 C.append('WinAnsiEncoding /%s /%s RE' % (fontName, fontName))    
         if C:
             C.insert(0,PS_WinAnsiEncoding)
-            self.code.insert(1, string.join(C, self._sep))
+            self.code.insert(1, self._sep.join(C))
 
     def save(self,f=None):
         if not hasattr(f,'write'):
@@ -151,7 +151,7 @@
 ''' % (self.width,self.height))
 
         self._t1_re_encode()
-        file.write(string.join(self.code,self._sep))
+        file.write(self._sep.join(self.code))
         if file is not f:
             file.close()
             from reportlab.lib.utils import markfilename
@@ -190,7 +190,7 @@
             self.code_append('[%s %s] 0 %s' % (array, phase, psoperation))
         elif isinstance(array,(tuple,list)):
             assert phase >= 0, "phase is a length in user space"
-            textarray = string.join(map(str, array))
+            textarray = ' '.join(map(str, array))
             self.code_append('[%s] %s %s' % (textarray, phase, psoperation))
 
     def setStrokeColor(self, color):
--- a/src/reportlab/graphics/renderSVG.py	Thu Aug 01 17:35:55 2013 +0100
+++ b/src/reportlab/graphics/renderSVG.py	Fri Aug 02 16:38:41 2013 +0100
@@ -17,7 +17,7 @@
 from reportlab.graphics.shapes import STATE_DEFAULTS, Path, UserNode
 from reportlab.graphics.shapes import * # (only for test0)
 from reportlab import rl_config
-from reportlab.lib.utils import getBytesIO, RLString
+from reportlab.lib.utils import getBytesIO, RLString, isPy3
 
 from xml.dom import getDOMImplementation
 
@@ -96,8 +96,8 @@
 class EncodedWriter(list):
     '''
     EncodedWriter(encoding) assumes .write will be called with
-    either unicode or utf8 encoded strings.  it will accumulate
-    strings encoded as the specified encoding.
+    either trnicode or utf8 encoded bytes. it will accumulate
+    unicode
     '''
     BOMS =  {
         'utf-32':codecs.BOM_UTF32,
@@ -113,22 +113,18 @@
         if bom and '16' in encoding or '32' in encoding:
             self.write(self.BOMS[encoding])
 
-    def write(self,s):
-        if isinstance(s,str):
-            s = s.encode(self.encoding)
-        elif isinstance(s,str):
+    def write(self,u):
+        if isinstance(u,bytes):
             try:
-                 u = s.decode('utf-8')
+                 u = u.decode('utf-8')
             except:
                 et, ev, tb = sys.exc_info()
                 ev = str(ev)
                 del et, tb
-                raise ValueError("String %r not encoded as 'utf-8'\nerror=%s" % (s,ev))
-            if self.encoding!='utf-8':
-                s = u.decode(self.encoding)
-        else:
-            raise ValueError("EncodedWriter.write(%r) argument should be 'utf-8' string or unicode" % s)
-        self.append(s)
+                raise ValueError("String %r not encoded as 'utf-8'\nerror=%s" % (u,ev))
+        elif not isinstance(u,str):
+            raise ValueError("EncodedWriter.write(%r) argument should be 'utf-8' bytes or str" % u)
+        self.append(u)
 
     def getvalue(self):
         r = ''.join(self)
@@ -242,10 +238,14 @@
         writer = EncodedWriter(self.encoding,bom=self.bom)
         self.doc.writexml(writer,addindent="\t",newl="\n",encoding=self.encoding)
 
-        if type(fn) in str:
-            f = open(fn, 'w')
+        if hasattr(fn,'write'):
+            f = fn
         else:
-            f = fn
+            if isPy3:
+                f = open(fn, 'w',encoding=self.encoding)
+            else:
+                f = open(fn, 'w')
+
         svg = writer.getvalue()
         exd = self.extraXmlDecl
         if exd:
--- a/src/reportlab/graphics/shapes.py	Thu Aug 01 17:35:55 2013 +0100
+++ b/src/reportlab/graphics/shapes.py	Fri Aug 02 16:38:41 2013 +0100
@@ -5,7 +5,7 @@
 __version__=''' $Id$ '''
 __doc__='''Core of the graphics library - defines Drawing and Shapes'''
 
-import string, os, sys
+import os, sys
 from math import pi, cos, sin, tan, sqrt
 from pprint import pprint
 
@@ -570,7 +570,7 @@
         s = ''
         for v in self:
             s = s + '%s,' % _repr(v,I)
-        if isisntance(self,list):
+        if isinstance(self,list):
             return '[%s]' % s[:-1]
         else:
             return '(%s%s)' % (s[:-1],len(self)==1 and ',' or '')
@@ -659,7 +659,7 @@
         n = 'ExplodedDrawing_' + self.__class__.__name__
         s = '#Autogenerated by ReportLab guiedit do not edit\n'
         for m, o in I.items():
-            s = s + 'from %s import %s\n' % (m,string.replace(str(o)[1:-1],"'",""))
+            s = s + 'from %s import %s\n' % (m,str(o)[1:-1].replace("'",""))
         s = s + '\nclass %s(_DrawingEditorMixin,Drawing):\n' % n
         s = s + '\tdef __init__(self,width=%s,height=%s,*args,**kw):\n' % (self.width,self.height)
         s = s + '\t\tDrawing.__init__(self,width,height,*args,**kw)\n'
@@ -737,7 +737,7 @@
         if not os.path.isdir(outDir): os.makedirs(outDir)
         fnroot = os.path.normpath(os.path.join(outDir,fnRoot))
         plotMode = os.path.splitext(fnroot)
-        if string.lower(plotMode[1][1:]) in self._saveModes:
+        if plotMode[1][1:].lower() in self._saveModes:
             fnroot = plotMode[0]
 
         plotMode = [x.lower() for x in (formats or getattr(self,'formats',['pdf']))]
--- a/src/reportlab/lib/utils.py	Thu Aug 01 17:35:55 2013 +0100
+++ b/src/reportlab/lib/utils.py	Fri Aug 02 16:38:41 2013 +0100
@@ -20,7 +20,7 @@
     def _digester(s):
         return join(["%02x" % ord(x) for x in md5(s).digest()], '')
 
-isPython3 = sys.version_info[0]==3
+isPy3 = sys.version_info[0]==3
 
 def isFunction(v):
     return type(v) == type(isFunction)
@@ -38,7 +38,7 @@
 def isSeq(v,_st=(tuple,list)):
     return isinstance(v,_st)
 
-if isPython3:
+if isPy3:
     def UniChr(v):
         return chr(v)
 
@@ -679,7 +679,7 @@
                     palette = palette.palette
                 except:
                     palette = palette.data
-                if isPython3:
+                if isPy3:
                     return palette[transparency:transparency+3]
                 else:
                     return [ord(c) for c in palette[transparency:transparency+3]]
@@ -1133,7 +1133,7 @@
             e = i
             break
     if e>=0:
-        if not isPython3:
+        if not isPy3:
             if isinstance(a,unicode):
                 if not isinstance(msg,unicode):
                     msg=msg.decode(enc)
--- a/src/reportlab/pdfbase/pdfmetrics.py	Thu Aug 01 17:35:55 2013 +0100
+++ b/src/reportlab/pdfbase/pdfmetrics.py	Fri Aug 02 16:38:41 2013 +0100
@@ -21,7 +21,7 @@
 import string, os, sys
 from reportlab.pdfbase import _fontdata
 from reportlab.lib.logger import warnOnce
-from reportlab.lib.utils import rl_isfile, rl_glob, rl_isdir, open_and_read, open_and_readlines, findInPaths, isSeq, isStr, isUnicode, isPython3
+from reportlab.lib.utils import rl_isfile, rl_glob, rl_isdir, open_and_read, open_and_readlines, findInPaths, isSeq, isStr, isUnicode, isPy3
 from reportlab.rl_config import defaultEncoding, T1SearchPath
 from . import rl_codecs
 _notdefChar = b'n'
@@ -435,7 +435,7 @@
 PFB_BINARY=chr(2)
 PFB_EOF=chr(3)
 
-if isPython3:
+if isPy3:
     def _pfbCheck(p,d,m,fn):
         if chr(d[p])!=PFB_MARKER or chr(d[p+1])!=m:
             raise ValueError('Bad pfb file\'%s\' expected chr(%d)chr(%d) at char %d, got chr(%d)chr(%d)' % (fn,ord(PFB_MARKER),ord(m),p,d[p],d[p+1]))
--- a/src/reportlab/pdfbase/pdfutils.py	Thu Aug 01 17:35:55 2013 +0100
+++ b/src/reportlab/pdfbase/pdfutils.py	Fri Aug 02 16:38:41 2013 +0100
@@ -10,7 +10,7 @@
 import os
 import binascii
 from reportlab import rl_config
-from reportlab.lib.utils import getBytesIO, ImageReader, isStr, isUnicode, isPython3
+from reportlab.lib.utils import getBytesIO, ImageReader, isStr, isUnicode, isPy3
 
 LINEEND = '\015\012'
 
@@ -226,7 +226,7 @@
         whole_word_count, remainder_size = divmod(len(input), 4)
         cut = 4 * whole_word_count
         body, lastbit = input[0:cut], input[cut:]
-        if isPython3 and isStr(lastbit):
+        if isPy3 and isStr(lastbit):
             lastbit = lastbit.encode('utf-8')
 
         out = [].append
--- a/src/reportlab/pdfbase/ttfonts.py	Thu Aug 01 17:35:55 2013 +0100
+++ b/src/reportlab/pdfbase/ttfonts.py	Fri Aug 02 16:38:41 2013 +0100
@@ -53,7 +53,7 @@
 
 import string
 from struct import pack, unpack, error as structError
-from reportlab.lib.utils import getBytesIO
+from reportlab.lib.utils import getBytesIO, isPy3
 from reportlab.pdfbase import pdfmetrics, pdfdoc
 from reportlab import rl_config
 
@@ -114,12 +114,9 @@
     return splice(stream, offset, pack(">H", value))
 
 try:
-    import _rl_accel
+    from reportlab.lib import _rl_accel
 except ImportError:
-    try:
-        from reportlab.lib import _rl_accel
-    except ImportError:
-        _rl_accel = None
+    _rl_accel = None
 
 try:
     hex32 = _rl_accel.hex32
@@ -304,10 +301,24 @@
         self._pos = self.get_table_pos(tag)[0] + offset_in_table
         return self._pos
 
-    def read_tag(self):
-        "Read a 4-character tag"
-        self._pos += 4
-        return self._ttf_data[self._pos - 4:self._pos]
+    if isPy3:
+        def read_tag(self):
+            "Read a 4-character tag"
+            self._pos += 4
+            return str(self._ttf_data[self._pos - 4:self._pos],'utf8')
+
+        def get_chunk(self, pos, length):
+            "Return a chunk of raw data at given position"
+            return str(self._ttf_data[pos:pos+length],'utf8')
+    else:
+        def read_tag(self):
+            "Read a 4-character tag"
+            self._pos += 4
+            return self._ttf_data[self._pos - 4:self._pos]
+
+        def get_chunk(self, pos, length):
+            "Return a chunk of raw data at given position"
+            return self._ttf_data[pos:pos+length]
 
     def read_ushort(self):
         "Reads an unsigned short"
@@ -335,10 +346,6 @@
         "Return an unsigned long at given position"
         return unpack('>L',self._ttf_data[pos:pos+4])[0]
 
-    def get_chunk(self, pos, length):
-        "Return a chunk of raw data at given position"
-        return self._ttf_data[pos:pos+length]
-
     def get_table(self, tag):
         "Return the given TTF table"
         pos, length = self.get_table_pos(tag)
--- a/src/reportlab/pdfgen/canvas.py	Thu Aug 01 17:35:55 2013 +0100
+++ b/src/reportlab/pdfgen/canvas.py	Fri Aug 02 16:38:41 2013 +0100
@@ -398,9 +398,8 @@
                 P('BT %s 12 Tf 14.4 TL ET' % self._doc.getInternalFontName(self._fontname))
         self._preamble = ' '.join(P.__self__)
 
-    if not _instanceEscapePDF:
-        def _escape(self, s):
-            return _escapePDF(s)
+    def _escape(self, s):
+        return _escapePDF(s)
 
     #info functions - non-standard
     def setAuthor(self, author):
--- a/src/reportlab/pdfgen/textobject.py	Thu Aug 01 17:35:55 2013 +0100
+++ b/src/reportlab/pdfgen/textobject.py	Fri Aug 02 16:38:41 2013 +0100
@@ -12,7 +12,7 @@
 import string
 from types import *
 from reportlab.lib.colors import Color, CMYKColor, CMYKColorSep, toColor, black, white, _CMYK_black, _CMYK_white
-from reportlab.lib.utils import fp_str, isStr, isPython3
+from reportlab.lib.utils import fp_str, isStr, isPy3
 from reportlab.pdfbase import pdfmetrics
 
 class _PDFColorSetter:
@@ -383,7 +383,7 @@
         else:
             #convert to T1  coding
             fc = font
-            if not isPython3 and not isinstance(text,unicode):
+            if not isPy3 and not isinstance(text,unicode):
                 try:
                     text = text.decode('utf8')
                 except UnicodeDecodeError as e:
--- a/src/rl_addons/renderPM/_renderPM.c	Thu Aug 01 17:35:55 2013 +0100
+++ b/src/rl_addons/renderPM/_renderPM.c	Fri Aug 02 16:38:41 2013 +0100
@@ -1098,17 +1098,24 @@
 	Gt1EncodedFont*	f;
 	double	fontSize, fontEMSize;
 	int		ft_font;
-	PyObject *fontNameObj;
+	PyObject *fontNameObj,*b=NULL;
 
 	if(!PyArg_ParseTuple(args,"Od:setFont", &fontNameObj, &fontSize)) return NULL;
-	fontName = PyBytes_AsString(fontNameObj);
+	if(PyUnicode_Check(fontNameObj)){
+		b=PyUnicode_AsUTF8String(fontNameObj);
+		if(!b) goto err;
+		fontName = PyBytes_AsString(b);
+		}
+	else{
+		fontName = PyBytes_AsString(fontNameObj);
+		}
 	if(!fontName){
 		PyErr_SetString(PyExc_ValueError, "_renderPM.gstate_setFont: Invalid fontName");
-		return NULL;
+		goto err;
 		}
 	if(fontSize<0){
 		PyErr_SetString(PyExc_ValueError, "_renderPM.gstate_setFont: Invalid fontSize");
-		return NULL;
+		goto err;
 		}
 	f=gt1_get_encoded_font(fontName);
 	if(f){
@@ -1137,6 +1144,8 @@
 		}
 
 	PyErr_SetString(PyExc_ValueError, "_renderPM.gstate_setFont: Can't find font!");
+err:
+	Py_XDECREF(b);
 	return NULL;
 }
 
--- a/src/rl_addons/rl_accel/_rl_accel.c	Thu Aug 01 17:35:55 2013 +0100
+++ b/src/rl_addons/rl_accel/_rl_accel.c	Fri Aug 02 16:38:41 2013 +0100
@@ -281,7 +281,11 @@
 			pB = pB + strlen(pB);
 			}
 		*pB = 0;
+#ifdef isPy3
+		retVal = PyUnicode_FromString(buf);
+#else
 		retVal = PyBytes_FromString(buf);
+#endif
 		free(buf);
 		return retVal;
 		}