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

Revision 1574, 24.2 kB (checked in by jalet, 20 years ago)

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