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

Revision 1572, 22.9 kB (checked in by jalet, 20 years ago)

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