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

Revision 1553, 19.4 kB (checked in by jalet, 20 years ago)

Removed old comments

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