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

Revision 1570, 23.4 kB (checked in by jalet, 20 years ago)

Now uses Psyco if it is available

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