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

Revision 1566, 20.7 kB (checked in by jalet, 20 years ago)

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