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

Revision 1487, 17.4 kB (checked in by jalet, 20 years ago)

All the code for pkpgcounter is now in pdlanalyzer.py

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