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

Revision 1551, 21.3 kB (checked in by jalet, 20 years ago)

"ERROR:" prefix added

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