root / pykota / trunk / pykota / pdlanalyzer.py @ 1567

Revision 1567, 20.8 kB (checked in by jalet, 20 years ago)

Another fix for PCL5 parser

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota - Print Quotas for CUPS and LPRng
5#
6# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20#
21# $Id$
22#
23# $Log$
24# Revision 1.13  2004/06/25 08:10:08  jalet
25# Another fix for PCL5 parser
26#
27# Revision 1.12  2004/06/24 23:09:53  jalet
28# Fix for number of copies in PCL5 parser
29#
30# Revision 1.11  2004/06/23 22:07:50  jalet
31# Fixed PCL5 parser according to the sources of rastertohp
32#
33# Revision 1.10  2004/06/18 22:24:03  jalet
34# Removed old comments
35#
36# Revision 1.9  2004/06/18 22:21:27  jalet
37# Native PDF parser greatly improved.
38# GhostScript based PDF parser completely removed because native code
39# is now portable across Python versions.
40#
41# Revision 1.8  2004/06/18 20:49:46  jalet
42# "ERROR:" prefix added
43#
44# Revision 1.7  2004/06/18 17:48:04  jalet
45# Added native fast PDF parsing method
46#
47# Revision 1.6  2004/06/18 14:00:16  jalet
48# Added PDF support in smart PDL analyzer (through GhostScript for now)
49#
50# Revision 1.5  2004/06/18 10:09:05  jalet
51# Resets file pointer to start of file in all cases
52#
53# Revision 1.4  2004/06/18 06:16:14  jalet
54# Fixes PostScript detection code for incorrect drivers
55#
56# Revision 1.3  2004/05/21 20:40:08  jalet
57# All the code for pkpgcounter is now in pdlanalyzer.py
58#
59# Revision 1.2  2004/05/19 19:09:36  jalet
60# Speed improvement
61#
62# Revision 1.1  2004/05/18 09:59:54  jalet
63# pkpgcounter is now just a wrapper around the PDLAnalyzer class
64#
65#
66#
67
68import sys
69import os
70import re
71import struct
72import tempfile
73import popen2
74   
75KILOBYTE = 1024   
76MEGABYTE = 1024 * KILOBYTE   
77
78class PDLAnalyzerError(Exception):
79    """An exception for PDL Analyzer related stuff."""
80    def __init__(self, message = ""):
81        self.message = message
82        Exception.__init__(self, message)
83    def __repr__(self):
84        return self.message
85    __str__ = __repr__
86   
87class PostScriptAnalyzer :
88    def __init__(self, infile) :
89        """Initialize PostScript Analyzer."""
90        self.infile = infile
91       
92    def getJobSize(self) :   
93        """Count pages in a DSC compliant PostScript document."""
94        pagecount = 0
95        for line in self.infile.xreadlines() : 
96            if line.startswith("%%Page: ") :
97                pagecount += 1
98        return pagecount
99       
100class PDFAnalyzer :
101    def __init__(self, infile) :
102        """Initialize PDF Analyzer."""
103        self.infile = infile
104               
105    def getJobSize(self) :   
106        """Counts pages in a PDF document."""
107        regexp = re.compile(r"(/Type) ?(/Page)[/ \r\n]")
108        pagecount = 0
109        for line in self.infile.xreadlines() : 
110            pagecount += len(regexp.findall(line))
111        return pagecount   
112       
113class PCLAnalyzer :
114    def __init__(self, infile) :
115        """Initialize PCL Analyzer."""
116        self.infile = infile
117       
118    def skip(self, nb) :   
119        """Reads a new datablock."""
120        newpos = self.pos + nb
121        if newpos >= self.len :
122            oldlen = self.len
123            self.data = self.infile.read(MEGABYTE)
124            self.len = len(self.data)
125            if not self.len :
126                return
127            self.pos = newpos - oldlen
128        else :   
129            self.pos = newpos
130       
131    def readone(self) :
132        """Reads a new byte."""
133        if self.pos < self.len :
134            char = self.data[self.pos]
135        else :   
136            self.data = self.infile.read(MEGABYTE)
137            self.len = len(self.data)
138            self.pos = 0
139            if not self.len :   
140                return
141            char = self.data[0]
142        self.pos += 1   
143        return char
144       
145    def getJobSize(self) :     
146        """Count pages in a PCL5 document."""
147        #
148        # Algorithm from pclcount
149        # (c) 2003, by Eduardo Gielamo Oliveira & Rodolfo Broco Manin
150        # published under the terms of the GNU General Public Licence v2.
151        #
152        # Backported from C to Python by Jerome Alet, then enhanced
153        # with more PCL tags detected. I think all the necessary PCL tags
154        # are recognized to correctly handle PCL5 files wrt their number
155        # of pages. The documentation used for this was :
156        #
157        # HP PCL/PJL Reference Set
158        # PCL5 Printer Language Technical Quick Reference Guide
159        # http://h20000.www2.hp.com/bc/docs/support/SupportManual/bpl13205/bpl13205.pdf
160        #
161        tagsends = { "&n" : "W", 
162                     "&b" : "W", 
163                     "*i" : "W", 
164                     "*l" : "W", 
165                     "*m" : "W", 
166                     "*v" : "W", 
167                     "*c" : "W", 
168                     "(f" : "W", 
169                     "*b" : "VW",
170                     "(s" : "W", 
171                     ")s" : "W", 
172                     "&p" : "X", 
173                     "&l" : "XH",
174                     "&a" : "G",
175                   } 
176        self.data = []             
177        self.pos = self.len = 0
178        pagecount = resets = ejects = backsides = 0
179        tag = None
180        copies = {}
181        while 1 :
182            char = self.readone()
183            if not char :       # EOF ?
184                break   
185            if char == "\014" :   
186                pagecount += 1
187            elif char == "\033" :   
188                #
189                #     <ESC>*b###W -> Start of a raster data row/block
190                #     <ESC>*b###V -> Start of a raster data plane
191                #     <ESC>*c###W -> Start of a user defined pattern
192                #     <ESC>*i###W -> Start of a viewing illuminant block
193                #     <ESC>*l###W -> Start of a color lookup table
194                #     <ESC>*m###W -> Start of a download dither matrix block
195                #     <ESC>*v###W -> Start of a configure image data block
196                #     <ESC>(s###W -> Start of a characters description block
197                #     <ESC>)s###W -> Start of a fonts description block
198                #     <ESC>(f###W -> Start of a symbol set block
199                #     <ESC>&b###W -> Start of configuration data block
200                #     <ESC>&l###X -> Number of copies for current page
201                #     <ESC>&n###W -> Starts an alphanumeric string ID block
202                #     <ESC>&p###X -> Start of a non printable characters block
203                #     <ESC>&a2G -> Back side when duplex mode as generated by rastertohp
204                #     <ESC>&l0H -> Eject if NumPlanes > 1, as generated by rastertohp
205                #
206                tagstart = self.readone()
207                if tagstart in "E9=YZ" : # one byte PCL tag
208                    if tagstart == "E" :
209                        resets += 1
210                    continue             # skip to next tag
211                tag = tagstart + self.readone()
212                try :
213                    tagend = tagsends[tag]
214                except KeyError :   
215                    pass    # Unsupported PCL tag
216                else :   
217                    # Now read the numeric argument
218                    size = 0
219                    while 1 :
220                        char = self.readone()
221                        if not char.isdigit() :
222                            break
223                        size = (size * 10) + int(char)   
224                    if char in tagend :   
225                        if (tag == "&l") and (char == "X") : # copies for current page
226                            copies[pagecount] = size
227                        elif (tag == "&l") and (char == "H") and (size == 0) :   
228                            ejects += 1         # Eject
229                        elif (tag == "&a") and (size == 2) :
230                            backsides += 1      # Back side in duplex mode
231                        else :   
232                            # doing a read will prevent the seek
233                            # for unseekable streams.
234                            # we just ignore the block anyway.
235                            if tag == "&n" : 
236                                # we have to take care of the operation id byte
237                                # which is before the string itself
238                                size += 1
239                            self.skip(size)
240                           
241        # if pagecount is still 0, we will use the number
242        # of resets instead of the number of form feed characters.
243        # but the number of resets is always at least 2 with a valid
244        # pcl file : one at the very start and one at the very end
245        # of the job's data. So we substract 2 from the number of
246        # resets. And since on our test data we needed to substract
247        # 1 more, we finally substract 3, and will test several
248        # PCL files with this. If resets < 2, then the file is
249        # probably not a valid PCL file, so we use 0
250        if not pagecount :
251            pagecount = (pagecount or ((resets - 3) * (resets > 2)))
252        else :   
253            # here we add counters for other ways new pages may have
254            # been printed and ejected by the printer
255            pagecount += ejects + backsides
256       
257        # now handle number of copies for each page (may differ).
258        # in duplex mode, number of copies may be sent only once.
259        for pnum in range(pagecount) :
260            # if no number of copies defined, take the preceding one else 1.
261            nb = copies.get(pnum, copies.get(pnum-1, 1))
262            pagecount += (nb - 1)
263        return pagecount
264       
265class PCLXLAnalyzer :
266    def __init__(self, infile) :
267        """Initialize PCLXL Analyzer."""
268        raise PDLAnalyzerError, "PCLXL (aka PCL6) is not supported yet."
269        self.infile = infile
270        self.islittleendian = None
271        found = 0
272        while not found :
273            line = self.infile.readline()
274            if not line :
275                break
276            if line[1:12] == " HP-PCL XL;" :
277                found = 1
278                if line[0] == ")" :
279                    self.littleendian()
280                elif line[0] == "(" :   
281                    self.bigendian()
282        if not found :
283            raise PDLAnalyzerError, "This file doesn't seem to be PCLXL (aka PCL6)"
284        else :   
285            self.tags = [lambda: None] * 256   
286            self.tags[0x28] = self.bigendian    # big endian
287            self.tags[0x29] = self.littleendian # big endian
288            self.tags[0x43] = self.beginPage    # BeginPage
289            self.tags[0x44] = self.endPage      # EndPage
290           
291            self.tags[0xc0] = lambda: 1 # ubyte
292            self.tags[0xc1] = lambda: 2 # uint16
293            self.tags[0xc2] = lambda: 4 # uint32
294            self.tags[0xc3] = lambda: 2 # sint16
295            self.tags[0xc4] = lambda: 4 # sint32
296            self.tags[0xc5] = lambda: 4 # real32
297           
298            self.tags[0xc8] = self.array_8  # ubyte_array
299            self.tags[0xc9] = self.array_16 # uint16_array
300            self.tags[0xca] = self.array_32 # uint32_array
301            self.tags[0xcb] = self.array_16 # sint16_array
302            self.tags[0xcc] = self.array_32 # sint32_array
303            self.tags[0xcd] = self.array_32 # real32_array
304           
305            self.tags[0xd0] = lambda: 2 # ubyte_xy
306            self.tags[0xd1] = lambda: 4 # uint16_xy
307            self.tags[0xd2] = lambda: 8 # uint32_xy
308            self.tags[0xd3] = lambda: 4 # sint16_xy
309            self.tags[0xd4] = lambda: 8 # sint32_xy
310            self.tags[0xd5] = lambda: 8 # real32_xy
311           
312            self.tags[0xd0] = lambda: 4  # ubyte_box
313            self.tags[0xd1] = lambda: 8  # uint16_box
314            self.tags[0xd2] = lambda: 16 # uint32_box
315            self.tags[0xd3] = lambda: 8  # sint16_box
316            self.tags[0xd4] = lambda: 16 # sint32_box
317            self.tags[0xd5] = lambda: 16 # real32_box
318           
319            self.tags[0xf8] = lambda: 1 # attr_ubyte
320            self.tags[0xf9] = lambda: 2 # attr_uint16
321           
322            self.tags[0xfa] = self.embeddedData      # dataLength
323            self.tags[0xfb] = self.embeddedDataSmall # dataLengthByte
324           
325    def debug(self, msg) :
326        """Outputs a debug message on stderr."""
327        sys.stderr.write("%s\n" % msg)
328        sys.stderr.flush()
329       
330    def beginPage(self) :
331        """Indicates the beginning of a new page."""
332        self.pagecount += 1
333        self.debug("Begin page %i at %s" % (self.pagecount, self.infile.tell()))
334       
335    def endPage(self) :
336        """Indicates the end of a page."""
337        self.debug("End page %i at %s" % (self.pagecount, self.infile.tell()))
338       
339    def handleArray(self, itemsize) :       
340        """Handles arrays."""
341        pos = self.infile.tell()
342        datatype = self.infile.read(1)
343        length = self.tags[ord(datatype)]()
344        if length is None :
345            self.debug("Bogus array length at %s" % pos)
346        else :   
347            sarraysize = self.infile.read(length)
348            if self.islittleendian :
349                fmt = "<"
350            else :   
351                fmt = ">"
352            if length == 1 :   
353                fmt += "B"
354            elif length == 2 :   
355                fmt += "H"
356            elif length == 4 :   
357                fmt += "I"
358            else :   
359                raise PDLAnalyzerError, "Error on array size at %s" % self.infile.tell()
360            arraysize = struct.unpack(fmt, sarraysize)[0]
361            self.debug("Array at %s, itemsize %s, datatype 0x%02x, size %s" % (pos, itemsize, ord(datatype), arraysize))
362            return arraysize * itemsize
363       
364    def array_8(self) :   
365        """Handles byte arrays."""
366        return self.handleArray(1)
367       
368    def array_16(self) :   
369        """Handles byte arrays."""
370        return self.handleArray(2)
371       
372    def array_32(self) :   
373        """Handles byte arrays."""
374        return self.handleArray(4)
375       
376    def embeddedDataSmall(self) :
377        """Handle small amounts of data."""
378        pos = self.infile.tell()
379        val = ord(self.infile.read(1))
380        self.debug("smalldatablock at %s (0x%02x)" % (pos, val))
381        return val
382       
383    def embeddedData(self) :
384        """Handle normal amounts of data."""
385        if self.islittleendian :
386            fmt = "<I"
387        else :   
388            fmt = ">I"
389        pos = self.infile.tell()
390        val = struct.unpack(fmt, self.infile.read(4))[0]
391        self.debug("datablock at %s (0x%08x)" % (pos, val))
392        return val
393       
394    def littleendian(self) :       
395        """Toggles to little endianness."""
396        self.islittleendian = 1 # little endian
397       
398    def bigendian(self) :   
399        """Toggles to big endianness."""
400        self.islittleendian = 0 # big endian
401   
402    def getJobSize(self) :
403        """Counts pages in a PCLXL (PCL6) document."""
404        self.pagecount = 0
405        while 1 :
406            char = self.infile.read(1)
407            if not char :
408                break
409            index = ord(char)   
410            length = self.tags[index]()
411            if length :   
412                self.infile.read(length)   
413        return self.pagecount
414       
415class PDLAnalyzer :   
416    """Generic PDL Analyzer class."""
417    def __init__(self, filename) :
418        """Initializes the PDL analyzer.
419       
420           filename is the name of the file or '-' for stdin.
421           filename can also be a file-like object which
422           supports read() and seek().
423        """
424        self.filename = filename
425       
426    def getJobSize(self) :   
427        """Returns the job's size."""
428        self.openFile()
429        try :
430            pdlhandler = self.detectPDLHandler()
431        except PDLAnalyzerError, msg :   
432            self.closeFile()
433            raise PDLAnalyzerError, "ERROR : Unknown file format for %s (%s)" % (self.filename, msg)
434        else :
435            try :
436                size = pdlhandler(self.infile).getJobSize()
437            finally :   
438                self.closeFile()
439            return size
440       
441    def openFile(self) :   
442        """Opens the job's data stream for reading."""
443        self.mustclose = 0  # by default we don't want to close the file when finished
444        if hasattr(self.filename, "read") and hasattr(self.filename, "seek") :
445            # filename is in fact a file-like object
446            infile = self.filename
447        elif self.filename == "-" :
448            # we must read from stdin
449            infile = sys.stdin
450        else :   
451            # normal file
452            self.infile = open(self.filename, "rb")
453            self.mustclose = 1
454            return
455           
456        # Use a temporary file, always seekable contrary to standard input.
457        self.infile = tempfile.TemporaryFile(mode="w+b")
458        while 1 :
459            data = infile.read(MEGABYTE) 
460            if not data :
461                break
462            self.infile.write(data)
463        self.infile.flush()   
464        self.infile.seek(0)
465           
466    def closeFile(self) :       
467        """Closes the job's data stream if we can close it."""
468        if self.mustclose :
469            self.infile.close()   
470        else :   
471            # if we don't have to close the file, then
472            # ensure the file pointer is reset to the
473            # start of the file in case the process wants
474            # to read the file again.
475            try :
476                self.infile.seek(0)
477            except :   
478                pass    # probably stdin, which is not seekable
479       
480    def isPostScript(self, data) :   
481        """Returns 1 if data is PostScript, else 0."""
482        if data.startswith("%!") or \
483           data.startswith("\004%!") or \
484           data.startswith("\033%-12345X%!PS") or \
485           ((data[:128].find("\033%-12345X") != -1) and \
486             ((data.find("LANGUAGE=POSTSCRIPT") != -1) or \
487              (data.find("LANGUAGE = POSTSCRIPT") != -1) or \
488              (data.find("LANGUAGE = Postscript") != -1))) or \
489              (data.find("%!PS-Adobe") != -1) :
490            return 1
491        else :   
492            return 0
493       
494    def isPDF(self, data) :   
495        """Returns 1 if data is PDF, else 0."""
496        if data.startswith("%PDF-") or \
497           data.startswith("\033%-12345X%PDF-") or \
498           ((data[:128].find("\033%-12345X") != -1) and (data.upper().find("LANGUAGE=PDF") != -1)) or \
499           (data.find("%PDF-") != -1) :
500            return 1
501        else :   
502            return 0
503       
504    def isPCL(self, data) :   
505        """Returns 1 if data is PCL, else 0."""
506        if data.startswith("\033E\033") or \
507           ((data[:128].find("\033%-12345X") != -1) and \
508             ((data.find("LANGUAGE=PCL") != -1) or \
509              (data.find("LANGUAGE = PCL") != -1) or \
510              (data.find("LANGUAGE = Pcl") != -1))) :
511            return 1
512        else :   
513            return 0
514       
515    def isPCLXL(self, data) :   
516        """Returns 1 if data is PCLXL aka PCL6, else 0."""
517        if ((data[:128].find("\033%-12345X") != -1) and \
518             (data.find(" HP-PCL XL;") != -1) and \
519             ((data.find("LANGUAGE=PCLXL") != -1) or \
520              (data.find("LANGUAGE = PCLXL") != -1))) :
521            return 1
522        else :   
523            return 0
524           
525    def detectPDLHandler(self) :   
526        """Tries to autodetect the document format.
527       
528           Returns the correct PDL handler class or None if format is unknown
529        """   
530        # Try to detect file type by reading first block of datas   
531        self.infile.seek(0)
532        firstblock = self.infile.read(KILOBYTE)
533        self.infile.seek(0)
534        if self.isPostScript(firstblock) :
535            return PostScriptAnalyzer
536        elif self.isPCLXL(firstblock) :   
537            return PCLXLAnalyzer
538        elif self.isPCL(firstblock) :   
539            return PCLAnalyzer
540        elif self.isPDF(firstblock) :   
541            return PDFAnalyzer
542        else :   
543            raise PDLAnalyzerError, "Analysis of first data block failed."
544           
545def main() :   
546    """Entry point for PDL Analyzer."""
547    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
548        sys.argv.append("-")
549       
550    totalsize = 0   
551    for arg in sys.argv[1:] :
552        try :
553            parser = PDLAnalyzer(arg)
554            totalsize += parser.getJobSize()
555        except PDLAnalyzerError, msg :   
556            sys.stderr.write("ERROR: %s\n" % msg)
557            sys.stderr.flush()
558    print "%s" % totalsize
559   
560if __name__ == "__main__" :   
561    main()       
Note: See TracBrowser for help on using the browser.