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

Revision 1543, 17.6 kB (checked in by jalet, 20 years ago)

Fixes PostScript? detection code for incorrect drivers

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