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

Revision 1568, 22.6 kB (checked in by jalet, 20 years ago)

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