Purge Jython support

Claude Paroz <[email protected]> Fri, 11 Feb 2022 23:14:06 +0100
Newsgroups gmane.comp.python.reportlab.user
Message-ID <[email protected]>
Jython is a currently dead project and it was never ported to Python 3.
The attached patch is a suggestion to purge Reportlab from Jython 
remainings.

Claude
-- 
www.2xlibre.net
0001-Jython-is-dead-from-some-time.patch (text/x-patch, 20.7 KB)
From 9296e749bf6c95c420a0317564ee91d1177a8a97 Mon Sep 17 00:00:00 2001
From: Claude Paroz <[email protected]>
Date: Fri, 11 Feb 2022 23:12:06 +0100
Subject: [PATCH] Jython is dead from some time

---
 MANIFEST.in                           |   2 +-
 demos/odyssey/00readme.txt            |   2 +-
 demos/odyssey/odyssey.py              |   6 +-
 src/reportlab/lib/utils.py            | 115 +++++--------
 src/reportlab/pdfbase/pdfdoc.py       |   9 -
 src/reportlab/pdfgen/pdfimages.py     |   7 +-
 src/rl_addons/rl_accel/_rl_accel.java | 231 --------------------------
 tests/test_docs_build.py              |   3 +-
 tests/test_docstrings.py              |   2 +-
 tests/test_extra.py                   |   3 +-
 tests/test_pdfgen_general.py          |   4 +-
 tests/test_pyfiles.py                 |   5 +-
 12 files changed, 50 insertions(+), 339 deletions(-)
 delete mode 100644 src/rl_addons/rl_accel/_rl_accel.java

diff --git a/MANIFEST.in b/MANIFEST.in
index 8adac8fa..97c18d96 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -3,7 +3,7 @@ include src/reportlab/graphics/barcode/README
 include src/reportlab/graphics/barcode/TODO
 include src/reportlab/license.txt
 include src/reportlab/MANIFEST.in
-recursive-include src/rl_addons *.c *.h *.in AUTHORS autogen.* ChangeLog *.am NEWS README* COPYING *.m4 *.py *.java hyphen.mashed
+recursive-include src/rl_addons *.c *.h *.in AUTHORS autogen.* ChangeLog *.am NEWS README* COPYING *.m4 *.py hyphen.mashed
 recursive-include demos *.py *.txt
 recursive-include docs *.py *.txt *.gif *.a85 *.png *.jpg *.rst *.html gen_epydoc *.bat Makefile *.yml *.css
 recursive-include tests *.py *.gif *.jpg *.png 00readme.txt *.tiff
diff --git a/demos/odyssey/00readme.txt b/demos/odyssey/00readme.txt
index f7b782e3..315db414 100644
--- a/demos/odyssey/00readme.txt
+++ b/demos/odyssey/00readme.txt
@@ -15,7 +15,7 @@ and unzip to extract odyssey.full.txt (608kb).
 
 Benchmark speed depends quite critically
 on the presence of our accelerator module,
-_rl_accel, which is a C (or Java) extension.
+_rl_accel, which is a C extension.
 Serious users ought to compile or download this!
 
 The times quoted are from one machine (Andy Robinson's
diff --git a/demos/odyssey/odyssey.py b/demos/odyssey/odyssey.py
index df861312..8cb52830 100644
--- a/demos/odyssey/odyssey.py
+++ b/demos/odyssey/odyssey.py
@@ -58,16 +58,12 @@ def drawPageFrame(canv):
 
 
 def run(verbose=1):
-    if sys.platform[0:4] == 'java':
-        impl = 'Jython'
-    else:
-        impl = 'Python'
     verStr = '%d.%d' % (sys.version_info[0:2])
     if ACCEL:
         accelStr = 'with _rl_accel'
     else:
         accelStr = 'without _rl_accel'
-    print('Benchmark of %s %s %s' % (impl, verStr, accelStr))
+    print('Benchmark of Python %s %s' % (verStr, accelStr))
 
     started = time.time()
     canv = canvas.Canvas('odyssey.pdf', invariant=1)
diff --git a/src/reportlab/lib/utils.py b/src/reportlab/lib/utils.py
index 00825212..7925d44f 100644
--- a/src/reportlab/lib/utils.py
+++ b/src/reportlab/lib/utils.py
@@ -420,25 +420,17 @@ def import_zlib():
     return zlib
 
 # Image Capability Detection.  Set a flag haveImages
-# to tell us if either PIL or Java imaging libraries present.
+# to tell us if PIL library is present.
 # define PIL_Image as either None, or an alias for the PIL.Image
 # module, as there are 2 ways to import it
-if sys.platform[0:4] == 'java':
-    try:
-        import javax.imageio
-        import java.awt.image
-        haveImages = 1
-    except:
-        haveImages = 0
-else:
+try:
+    from PIL import Image
+except ImportError:
     try:
-        from PIL import Image
+        import Image
     except ImportError:
-        try:
-            import Image
-        except ImportError:
-            Image = None
-    haveImages = Image is not None
+        Image = None
+haveImages = Image is not None
 
 class ArgvDictValue:
     '''A type to allow clients of getArgvDict to specify a conversion function'''
@@ -664,7 +656,7 @@ def _isPILImage(im):
         return 0
 
 class ImageReader:
-    "Wraps up either PIL or Java to get data from bitmaps"
+    "Wraps up PIL to get data from bitmaps"
     _cache={}
     _max_image_size = None
     def __init__(self, fileName,ident=None):
@@ -742,11 +734,7 @@ class ImageReader:
         return '[%s@%s%s%s]' % (self.__class__.__name__,hex(id(self)),ident and (' ident=%r' % ident) or '',fn and (' filename=%r' % fn) or '')
 
     def _read_image(self,fp):
-        if sys.platform[0:4] == 'java':
-            from javax.imageio import ImageIO
-            return ImageIO.read(fp)
-        else:
-            return Image.open(fp)
+        return Image.open(fp)
 
     @classmethod
     def check_pil_image_size(cls, im):
@@ -775,11 +763,7 @@ class ImageReader:
 
     def getSize(self):
         if (self._width is None or self._height is None):
-            if sys.platform[0:4] == 'java':
-                self._width = self._image.getWidth()
-                self._height = self._image.getHeight()
-            else:
-                self._width, self._height = self._image.size
+            self._width, self._height = self._image.size
         return (self._width, self._height)
 
     def getRGBData(self):
@@ -787,42 +771,24 @@ class ImageReader:
         try:
             if self._data is None:
                 self._dataA = None
-                if sys.platform[0:4] == 'java':
-                    import jarray
-                    from java.awt.image import PixelGrabber
-                    width, height = self.getSize()
-                    buffer = jarray.zeros(width*height, 'i')
-                    pg = PixelGrabber(self._image, 0,0,width,height,buffer,0,width)
-                    pg.grabPixels()
-                    # there must be a way to do this with a cast not a byte-level loop,
-                    # I just haven't found it yet...
-                    pixels = []
-                    a = pixels.append
-                    for i in range(len(buffer)):
-                        rgb = buffer[i]
-                        a(chr((rgb>>16)&0xff))
-                        a(chr((rgb>>8)&0xff))
-                        a(chr(rgb&0xff))
-                    self._data = ''.join(pixels)
+                im = self._image
+                mode = self.mode = im.mode
+                if mode in ('LA','RGBA'):
+                    if getattr(Image,'VERSION','').startswith('1.1.7'):
+                        im.load()
+                    self._dataA = ImageReader(im.split()[3 if mode=='RGBA' else 1])
+                    nm = mode[:-1]
+                    im = im.convert(nm)
+                    self.mode = nm
+                elif mode not in ('L','RGB','CMYK'):
+                    if im.format=='PNG' and im.mode=='P' and 'transparency' in im.info:
+                        im = im.convert('RGBA')
+                        self._dataA = ImageReader(im.split()[3])
+                        im = im.convert('RGB')
+                    else:
+                        im = im.convert('RGB')
                     self.mode = 'RGB'
-                else:
-                    im = self._image
-                    mode = self.mode = im.mode
-                    if mode in ('LA','RGBA'):
-                        if getattr(Image,'VERSION','').startswith('1.1.7'): im.load()
-                        self._dataA = ImageReader(im.split()[3 if mode=='RGBA' else 1])
-                        nm = mode[:-1]
-                        im = im.convert(nm)
-                        self.mode = nm
-                    elif mode not in ('L','RGB','CMYK'):
-                        if im.format=='PNG' and im.mode=='P' and 'transparency' in im.info:
-                            im = im.convert('RGBA')
-                            self._dataA = ImageReader(im.split()[3])
-                            im = im.convert('RGB')
-                        else:
-                            im = im.convert('RGB')
-                        self.mode = 'RGB'
-                    self._data = (im.tobytes if hasattr(im, 'tobytes') else im.tostring)()  #make pillow and PIL both happy, for now
+                self._data = (im.tobytes if hasattr(im, 'tobytes') else im.tostring)()  #make pillow and PIL both happy, for now
             return self._data
         except:
             annotateException('\nidentity=%s'%self.identity())
@@ -832,22 +798,19 @@ class ImageReader:
         return width, height, self.getRGBData()
 
     def getTransparent(self):
-        if sys.platform[0:4] == 'java':
-            return None
-        else:
-            if "transparency" in self._image.info:
-                transparency = self._image.info["transparency"] * 3
-                palette = self._image.palette
+        if "transparency" in self._image.info:
+            transparency = self._image.info["transparency"] * 3
+            palette = self._image.palette
+            try:
+                palette = palette.palette
+            except:
                 try:
-                    palette = palette.palette
+                    palette = palette.data
                 except:
-                    try:
-                        palette = palette.data
-                    except:
-                        return None
-                return palette[transparency:transparency+3]
-            else:
-                return None
+                    return None
+            return palette[transparency:transparency+3]
+        else:
+            return None
 
 class LazyImageReader(ImageReader): 
     def fp(self): 
@@ -859,7 +822,7 @@ class LazyImageReader(ImageReader):
     _image=property(_image) 
 
 def getImageData(imageFileName):
-    "Get width, height and RGB pixels from image file.  Wraps Java/PIL"
+    "Get width, height and RGB pixels from image file.  Wraps PIL"
     try:
         return imageFileName.getImageData()
     except AttributeError:
diff --git a/src/reportlab/pdfbase/pdfdoc.py b/src/reportlab/pdfbase/pdfdoc.py
index 82bb3a17..78ef74de 100755
--- a/src/reportlab/pdfbase/pdfdoc.py
+++ b/src/reportlab/pdfbase/pdfdoc.py
@@ -23,17 +23,8 @@ from reportlab.lib.rl_accel import escapePDF, fp_str, asciiBase85Encode, asciiBa
 from reportlab.pdfbase import pdfmetrics
 from hashlib import md5
 
-from sys import platform
-from sys import version_info
 from sys import stderr
 
-if platform[:4] == 'java' and version_info[:2] == (2, 1):
-    # workaround for list()-bug in Jython 2.1 (should be fixed in 2.2)
-    def list(sequence):
-        def f(x):
-            return x
-        return list(map(f, sequence))
-
 class PDFError(Exception):
     pass
 
diff --git a/src/reportlab/pdfgen/pdfimages.py b/src/reportlab/pdfgen/pdfimages.py
index 0a923118..07c7e5e1 100644
--- a/src/reportlab/pdfgen/pdfimages.py
+++ b/src/reportlab/pdfgen/pdfimages.py
@@ -157,12 +157,7 @@ class PDFImage:
             else:
                 imagedata, imgwidth, imgheight = self.non_jpg_imagedata(image)
         else:
-            import sys
-            if sys.platform[0:4] == 'java':
-                #jython, PIL not available
-                imagedata, imgwidth, imgheight = self.JAVA_imagedata()
-            else:
-                imagedata, imgwidth, imgheight = self.PIL_imagedata()
+            imagedata, imgwidth, imgheight = self.PIL_imagedata()
         self.imageData = imagedata
         self.imgwidth = imgwidth
         self.imgheight = imgheight
diff --git a/src/rl_addons/rl_accel/_rl_accel.java b/src/rl_addons/rl_accel/_rl_accel.java
deleted file mode 100644
index 783419b6..00000000
--- a/src/rl_addons/rl_accel/_rl_accel.java
+++ /dev/null
@@ -1,231 +0,0 @@
-import org.python.core.*;
-import java.text.*;
-import java.io.*;
-
-public class _rl_accel{
-    public static String version = "0.30";
-    private static String[] formats = {"#", "#.#", "#.##", "#.###", "#.####", "#.#####", "#.######"};
-
-    public static Object fp_str(PyObject[] args){
-        StringBuffer buffer = new StringBuffer();
-
-        if(args.length==1 && args[0] instanceof PySequence){
-            //iterate through the first element
-            PySequence seq = (PySequence)args[0];
-            for(int i=0;i<seq.__len__();i++){
-                format(buffer, seq.__getitem__(i).toString());
-            }
-        }
-        else{
-            //iterate through the args list
-            for(int i=0;i<args.length;i++){
-                format(buffer, args[i].toString());
-            }
-        }
-        return buffer.toString().trim();
-    }
-
-    private static double log_e_10 = Math.log(10.0);
-
-    private static void format(StringBuffer buffer, String a){
-        String num;
-        int l;
-        double d = Double.parseDouble(a);
-        if(Math.abs(d)<=1.0e-7) num = "0";
-        else{
-            if(Math.abs(d)>1.0)
-                l = (Math.min(Math.max(0,(6-(int)(Math.log(Math.abs(d))/log_e_10))),6));
-            else l = 6;
-            NumberFormat formatter = new DecimalFormat(formats[l]);
-            num = formatter.format(d);
-            if(num.startsWith("0")&&(num.length()>1))
-                num = num.substring(1);
-        }
-        buffer.append(num).append(' ');
-    }
-
-	public static String escapePDF(String text){
-		int textlen = text.length();
-		StringBuffer out = new StringBuffer(textlen*4);
-		int i=0;
-
-		while(i<textlen){
-			char c = text.charAt(i++);
-			if((int)c<32 || (int)c>=127){
-				String buf = Integer.toOctalString((int)c);
-				out.append('\\');
-				if(buf.length()<3){
-					if(buf.length()<2)
-						out.append('0');
-					out.append('0');
-				}
-				out.append(buf);
-				}
-			else{
-				if(c=='\\' || c=='(' || c==')')
-					out.append('\\');
-				out.append(c);
-			}
-		}
-
-		return out.toString();
-	}
-
-	public static String _instanceEscapePDF(String text){
-		return escapePDF(text);
-	}
-
-	static long a85_0 = 1;
-	static long a85_1 = 85;
-	static long a85_2 = 7225;
-	static long a85_3 = 614125;
-	static long a85_4 = 52200625;
-
-	public static String _AsciiBase85Encode(String inData){
-		int	length = inData.length();
-		int blocks, extra, i, k, lim;
-		long block, res;
-
-		blocks = length / 4;
-		extra = length % 4;
-
-		StringBuffer buf = new StringBuffer((blocks+1)*5+3);
-		lim = 4*blocks;
-
-		for(k=i=0; i<lim; i += 4){
-			/*
-			 * If you evere have trouble with this consider using masking to ensure
-			 * that the shifted quantity is only 8 bits long
-			 */
-			block = ((((int)inData.charAt(i))<<24)|(((int)inData.charAt(i+1))<<16)
-					|(((int)inData.charAt(i+2))<<8)|(int)inData.charAt(i+3)) & 0x00000000FFFFFFFFL;
-			if (block == 0) buf.append('z');
-			else {
-				res = block/a85_4;
-				buf.append((char)(res+33));
-				block -= res*a85_4;
-
-				res = block/a85_3;
-				buf.append((char)(res+33));
-				block -= res*a85_3;
-
-				res = block/a85_2;
-				buf.append((char)(res+33));
-				block -= res*a85_2;
-
-				res = block / a85_1;
-				buf.append((char)(res+33));
-
-				buf.append((char)(block-res*a85_1+33));
-				}
-			}
-
-		if(extra>0){
-			block = 0L;
-
-			for (i=0; i<extra; i++)
-				block += ((long)inData.charAt(length-extra+i)) << (24-8*i);
-
-			res = block/a85_4;
-			buf.append((char)(res+33));
-			if(extra>=1){
-				block -= res*a85_4;
-
-				res = block/a85_3;
-				buf.append((char)(res+33));
-				if(extra>=2){
-					block -= res*a85_3;
-
-					res = block/a85_2;
-					buf.append((char)(res+33));
-					if(extra>=3) buf.append((char)((block-res*a85_2)/a85_1+33));
-					}
-				}
-			}
-
-		buf.append('~');
-		buf.append('>');
-		return buf.toString();
-	}
-    public static final boolean isWhitespace(int ch){
-        return (ch == 0 || ch == 9 || ch == 10 || ch == 12 || ch == 13 || ch == 32);
-    	}
-	public static String _AsciiBase85Decode(String inData){
-        ByteArrayOutputStream out = new ByteArrayOutputStream();
-        int state = 0;
-        int chn[] = new int[5];
-	int len = inData.length();
-        for(int k = 0; k<len; ++k){
-            int ch = ((int)inData.charAt(k)) & 0xff;
-            if(ch == '~') break;
-            if(isWhitespace(ch)) continue;
-            if (ch=='z' && state==0){
-                out.write(0);
-                out.write(0);
-                out.write(0);
-                out.write(0);
-                continue;
-            	}
-            if (ch < '!' || ch > 'u') throw new RuntimeException("Illegal character in _AsciiBase85Decode.");
-            chn[state] = ch - '!';
-            ++state;
-            if(state == 5){
-                state = 0;
-                int r = 0;
-                for (int j = 0; j < 5; ++j) r = r*85 + chn[j];
-                out.write((byte)(r>>24));
-                out.write((byte)(r>>16));
-                out.write((byte)(r>>8));
-                out.write((byte)r);
-            	}
-        	}
-        long r;
-        if(state==1) throw new RuntimeException("Illegal length in _AsciiBase85Decode.");
-        if (state == 2) {
-            r = ((chn[0]*85+ chn[1])*85*85*85 + 0xfffff)&0x0ffffffffL;
-            out.write((byte)(r>>24));
-        }
-        else if (state == 3) {
-            r = (((chn[0]*85 + chn[1])*85 + chn[2])*85*85+0xffff)&0x0ffffffffL;
-            out.write((byte)(r >> 24));
-            out.write((byte)(r >> 16));
-        }
-        else if (state == 4) {
-            r = ((((chn[0]*85 + chn[1])*85 + chn[2])*85 + chn[3])*85+0xff)&0x0ffffffffL;
-            out.write((byte)(r >> 24));
-            out.write((byte)(r >> 16));
-            out.write((byte)(r >> 8));
-        }
-        return out.toString();
-		}
-		
-		
-	public static int calcChecksum(String data){
-		int	 dl = data.length();
-		int i;
-		long sum = 0L;
-		long n;
-		int leftover;
-		
-		/*full ULONGs*/
-		for(i=0;(dl-i)>=4;i+=4){
-			n = ((int)data.charAt(i)) << 24;
-			n += ((int)data.charAt(i+1)) << 16;
-			n += ((int)data.charAt(i+2)) << 8;
-			n += (int)data.charAt(i+3);
-			sum += n;
-			}
-	
-		/*pad with zeros*/
-		leftover = dl & 3;
-		if(leftover>0){
-			n = ((int)data.charAt(i)) << 24;;
-			if (leftover>1) n += ((int)data.charAt(i+1)) << 16;
-			if (leftover>2) n += ((int)data.charAt(i+2)) << 8;
-			sum += n;
-			}
-	
-		return (int)sum;
-	}
-		
-}
diff --git a/tests/test_docs_build.py b/tests/test_docs_build.py
index 48e60a01..7717d54f 100644
--- a/tests/test_docs_build.py
+++ b/tests/test_docs_build.py
@@ -34,8 +34,7 @@ class ManualTestCase(SecureTestCase):
 def makeSuite():
     suite = unittest.TestSuite()
     loader = unittest.TestLoader()
-    if sys.platform[:4] != 'java':
-        suite.addTest(loader.loadTestsFromTestCase(ManualTestCase))
+    suite.addTest(loader.loadTestsFromTestCase(ManualTestCase))
     return suite
 
 #noruntests
diff --git a/tests/test_docstrings.py b/tests/test_docstrings.py
index 31a1572e..d8469994 100644
--- a/tests/test_docstrings.py
+++ b/tests/test_docstrings.py
@@ -194,7 +194,7 @@ class DocstringTestCase(SecureTestCase):
 def makeSuite():
     suite = unittest.TestSuite()
     loader = unittest.TestLoader()
-    if sys.platform[:4] != 'java': suite.addTest(loader.loadTestsFromTestCase(DocstringTestCase))
+    suite.addTest(loader.loadTestsFromTestCase(DocstringTestCase))
     return suite
 
 #noruntests
diff --git a/tests/test_extra.py b/tests/test_extra.py
index dbe772df..ea68e377 100644
--- a/tests/test_extra.py
+++ b/tests/test_extra.py
@@ -78,8 +78,7 @@ class ExternalTestCase(SecureTestCase):
 def makeSuite():
     suite = unittest.TestSuite()
     loader = unittest.TestLoader()
-    if sys.platform[:4] != 'java':
-        suite.addTest(loader.loadTestsFromTestCase(ExternalTestCase))
+    suite.addTest(loader.loadTestsFromTestCase(ExternalTestCase))
 
     return suite
 
diff --git a/tests/test_pdfgen_general.py b/tests/test_pdfgen_general.py
index 83bb9824..ed2b3024 100644
--- a/tests/test_pdfgen_general.py
+++ b/tests/test_pdfgen_general.py
@@ -720,9 +720,9 @@ cost to performance.""")
     t = c.beginText(inch, 10 * inch)
     if not haveImages:
         c.drawString(inch, 11*inch,
-                     "Python or Java Imaging Library not found! Below you see rectangles instead of images.")
+                     "Python Imaging Library not found! Below you see rectangles instead of images.")
 
-    t.textLines("""PDFgen uses the Python Imaging Library (or, under Jython, java.awt.image and javax.imageio)
+    t.textLines("""PDFgen uses the Python Imaging Library
         to process a very wide variety of image formats.
         This page shows image capabilities.  If I've done things right, the bitmap should have
         its bottom left corner aligned with the crosshairs.
diff --git a/tests/test_pyfiles.py b/tests/test_pyfiles.py
index 21e030d0..1ed79aa5 100644
--- a/tests/test_pyfiles.py
+++ b/tests/test_pyfiles.py
@@ -141,9 +141,8 @@ class FirstLineTestCase(SecureTestCase):
 
 def makeSuite():
     suite = makeSuiteForClasses(SelfTestCase, AsciiFileTestCase, FilenameTestCase)
-    if sys.platform[:4] != 'java':
-        loader = unittest.TestLoader()
-        suite.addTest(loader.loadTestsFromTestCase(FirstLineTestCase))
+    loader = unittest.TestLoader()
+    suite.addTest(loader.loadTestsFromTestCase(FirstLineTestCase))
     return suite
 
 #noruntests
-- 
2.30.2