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

Revision 1564, 20.0 kB (checked in by jalet, 20 years ago)

Fixed PCL5 parser according to the sources of rastertohp

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