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

Revision 1547, 20.1 kB (checked in by jalet, 20 years ago)

Added PDF support in smart PDL analyzer (through GhostScript? for now)

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