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

Revision 1575, 21.6 kB (checked in by jalet, 20 years ago)

PCLXL support now works !

  • 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.19  2004/06/28 21:20:30  jalet
25# PCLXL support now works !
26#
27# Revision 1.18  2004/06/27 22:59:37  jalet
28# More work on PCLXL parser
29#
30# Revision 1.17  2004/06/26 23:20:01  jalet
31# Additionnal speedup for GhostScript generated PCL5 files
32#
33# Revision 1.16  2004/06/26 15:31:00  jalet
34# mmap reintroduced in PCL5 parser
35#
36# Revision 1.15  2004/06/26 14:14:31  jalet
37# Now uses Psyco if it is available
38#
39# Revision 1.14  2004/06/25 09:50:28  jalet
40# More debug info in PCLXL parser
41#
42# Revision 1.13  2004/06/25 08:10:08  jalet
43# Another fix for PCL5 parser
44#
45# Revision 1.12  2004/06/24 23:09:53  jalet
46# Fix for number of copies in PCL5 parser
47#
48# Revision 1.11  2004/06/23 22:07:50  jalet
49# Fixed PCL5 parser according to the sources of rastertohp
50#
51# Revision 1.10  2004/06/18 22:24:03  jalet
52# Removed old comments
53#
54# Revision 1.9  2004/06/18 22:21:27  jalet
55# Native PDF parser greatly improved.
56# GhostScript based PDF parser completely removed because native code
57# is now portable across Python versions.
58#
59# Revision 1.8  2004/06/18 20:49:46  jalet
60# "ERROR:" prefix added
61#
62# Revision 1.7  2004/06/18 17:48:04  jalet
63# Added native fast PDF parsing method
64#
65# Revision 1.6  2004/06/18 14:00:16  jalet
66# Added PDF support in smart PDL analyzer (through GhostScript for now)
67#
68# Revision 1.5  2004/06/18 10:09:05  jalet
69# Resets file pointer to start of file in all cases
70#
71# Revision 1.4  2004/06/18 06:16:14  jalet
72# Fixes PostScript detection code for incorrect drivers
73#
74# Revision 1.3  2004/05/21 20:40:08  jalet
75# All the code for pkpgcounter is now in pdlanalyzer.py
76#
77# Revision 1.2  2004/05/19 19:09:36  jalet
78# Speed improvement
79#
80# Revision 1.1  2004/05/18 09:59:54  jalet
81# pkpgcounter is now just a wrapper around the PDLAnalyzer class
82#
83#
84#
85
86import sys
87import os
88import re
89import struct
90import tempfile
91import mmap
92   
93KILOBYTE = 1024   
94MEGABYTE = 1024 * KILOBYTE   
95
96class PDLAnalyzerError(Exception):
97    """An exception for PDL Analyzer related stuff."""
98    def __init__(self, message = ""):
99        self.message = message
100        Exception.__init__(self, message)
101    def __repr__(self):
102        return self.message
103    __str__ = __repr__
104   
105class PostScriptAnalyzer :
106    def __init__(self, infile) :
107        """Initialize PostScript Analyzer."""
108        self.infile = infile
109       
110    def getJobSize(self) :   
111        """Count pages in a DSC compliant PostScript document."""
112        pagecount = 0
113        for line in self.infile.xreadlines() : 
114            if line.startswith("%%Page: ") :
115                pagecount += 1
116        return pagecount
117       
118class PDFAnalyzer :
119    def __init__(self, infile) :
120        """Initialize PDF Analyzer."""
121        self.infile = infile
122               
123    def getJobSize(self) :   
124        """Counts pages in a PDF document."""
125        regexp = re.compile(r"(/Type) ?(/Page)[/ \t\r\n]")
126        pagecount = 0
127        for line in self.infile.xreadlines() : 
128            pagecount += len(regexp.findall(line))
129        return pagecount   
130       
131class PCLAnalyzer :
132    def __init__(self, infile) :
133        """Initialize PCL Analyzer."""
134        self.infile = infile
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        infileno = self.infile.fileno()
153        minfile = mmap.mmap(infileno, os.fstat(infileno).st_size, access=mmap.ACCESS_READ)
154        tagsends = { "&n" : "W", 
155                     "&b" : "W", 
156                     "*i" : "W", 
157                     "*l" : "W", 
158                     "*m" : "W", 
159                     "*v" : "W", 
160                     "*c" : "W", 
161                     "(f" : "W", 
162                     "(s" : "W", 
163                     ")s" : "W", 
164                     "&p" : "X", 
165                     "&l" : "XH",
166                     "&a" : "G",
167                     # "*b" : "VW", # treated specially because it occurs very often
168                   } 
169        pagecount = resets = ejects = backsides = 0
170        tag = None
171        copies = {}
172        pos = 0
173        try :
174            while 1 :
175                char = minfile[pos] ; pos += 1
176                if char == "\014" :   
177                    pagecount += 1
178                elif char == "\033" :   
179                    #
180                    #     <ESC>*b###W -> Start of a raster data row/block
181                    #     <ESC>*b###V -> Start of a raster data plane
182                    #     <ESC>*c###W -> Start of a user defined pattern
183                    #     <ESC>*i###W -> Start of a viewing illuminant block
184                    #     <ESC>*l###W -> Start of a color lookup table
185                    #     <ESC>*m###W -> Start of a download dither matrix block
186                    #     <ESC>*v###W -> Start of a configure image data block
187                    #     <ESC>(s###W -> Start of a characters description block
188                    #     <ESC>)s###W -> Start of a fonts description block
189                    #     <ESC>(f###W -> Start of a symbol set block
190                    #     <ESC>&b###W -> Start of configuration data block
191                    #     <ESC>&l###X -> Number of copies for current page
192                    #     <ESC>&n###W -> Starts an alphanumeric string ID block
193                    #     <ESC>&p###X -> Start of a non printable characters block
194                    #     <ESC>&a2G -> Back side when duplex mode as generated by rastertohp
195                    #     <ESC>&l0H -> Eject if NumPlanes > 1, as generated by rastertohp
196                    #
197                    tagstart = minfile[pos] ; pos += 1
198                    if tagstart in "E9=YZ" : # one byte PCL tag
199                        if tagstart == "E" :
200                            resets += 1
201                        continue             # skip to next tag
202                    tag = tagstart + minfile[pos] ; pos += 1
203                    if tag == "*b" : 
204                        tagend = "VW"
205                    else :   
206                        try :
207                            tagend = tagsends[tag]
208                        except KeyError :   
209                            continue # Unsupported PCL tag
210                    # Now read the numeric argument
211                    size = 0
212                    while 1 :
213                        char = minfile[pos] ; pos += 1
214                        if not char.isdigit() :
215                            break
216                        size = (size * 10) + int(char)   
217                    if char in tagend :   
218                        if (tag == "&l") and (char == "X") : # copies for current page
219                            copies[pagecount] = size
220                        elif (tag == "&l") and (char == "H") and (size == 0) :   
221                            ejects += 1         # Eject
222                        elif (tag == "&a") and (size == 2) :
223                            backsides += 1      # Back side in duplex mode
224                        else :   
225                            # we just ignore the block.
226                            if tag == "&n" : 
227                                # we have to take care of the operation id byte
228                                # which is before the string itself
229                                size += 1
230                            pos += size   
231        except IndexError : # EOF ?
232            minfile.close() # reached EOF
233                           
234        # if pagecount is still 0, we will use 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 use 0
243        if not pagecount :
244            pagecount = (pagecount or ((resets - 3) * (resets > 2)))
245        else :   
246            # here we add counters for other ways new pages may have
247            # been printed and ejected by the printer
248            pagecount += ejects + backsides
249       
250        # now handle number of copies for each page (may differ).
251        # in duplex mode, number of copies may be sent only once.
252        for pnum in range(pagecount) :
253            # if no number of copies defined, take the preceding one else 1.
254            nb = copies.get(pnum, copies.get(pnum-1, 1))
255            pagecount += (nb - 1)
256        return pagecount
257       
258class PCLXLAnalyzer :
259    def __init__(self, infile) :
260        """Initialize PCLXL Analyzer."""
261        # raise PDLAnalyzerError, "PCLXL (aka PCL6) is not supported yet."
262        self.infile = infile
263        self.islittleendian = None
264        found = 0
265        while not found :
266            line = self.infile.readline()
267            if not line :
268                break
269            if line[1:12] == " HP-PCL XL;" :
270                found = 1
271                endian = ord(line[0])
272                if endian == 0x29 :
273                    self.littleEndian()
274                elif endian == 0x28 :   
275                    self.bigEndian()
276                # elif endian == 0x27 : TODO : What can we do here ?   
277                #
278                else :   
279                    raise PDLAnalyzerError, "No endianness marker 0x%02x at start !" % endian
280        if not found :
281            raise PDLAnalyzerError, "This file doesn't seem to be PCLXL (aka PCL6)"
282        else :   
283            # Initialize table of tags
284            self.tags = [ 0 ] * 256   
285           
286            # GhostScript's sources tell us that HP printers
287            # only accept little endianness, but we can handle both.
288            self.tags[0x28] = self.bigEndian    # BigEndian
289            self.tags[0x29] = self.littleEndian # LittleEndian
290           
291            self.tags[0x43] = self.beginPage    # BeginPage
292           
293            self.tags[0xc0] = 1 # ubyte
294            self.tags[0xc1] = 2 # uint16
295            self.tags[0xc2] = 4 # uint32
296            self.tags[0xc3] = 2 # sint16
297            self.tags[0xc4] = 4 # sint32
298            self.tags[0xc5] = 4 # real32
299           
300            self.tags[0xc8] = self.array_8  # ubyte_array
301            self.tags[0xc9] = self.array_16 # uint16_array
302            self.tags[0xca] = self.array_32 # uint32_array
303            self.tags[0xcb] = self.array_16 # sint16_array
304            self.tags[0xcc] = self.array_32 # sint32_array
305            self.tags[0xcd] = self.array_32 # real32_array
306           
307            self.tags[0xd0] = 2 # ubyte_xy
308            self.tags[0xd1] = 4 # uint16_xy
309            self.tags[0xd2] = 8 # uint32_xy
310            self.tags[0xd3] = 4 # sint16_xy
311            self.tags[0xd4] = 8 # sint32_xy
312            self.tags[0xd5] = 8 # real32_xy
313           
314            self.tags[0xe0] = 4  # ubyte_box
315            self.tags[0xe1] = 8  # uint16_box
316            self.tags[0xe2] = 16 # uint32_box
317            self.tags[0xe3] = 8  # sint16_box
318            self.tags[0xe4] = 16 # sint32_box
319            self.tags[0xe5] = 16 # real32_box
320           
321            self.tags[0xf8] = 1 # attr_ubyte
322            self.tags[0xf9] = 2 # attr_uint16
323           
324            self.tags[0xfa] = self.embeddedData      # dataLength
325            self.tags[0xfb] = self.embeddedDataSmall # dataLengthByte
326           
327    def beginPage(self) :
328        """Indicates the beginning of a new page."""
329        self.pagecount += 1
330        return 0
331       
332    def handleArray(self, itemsize) :       
333        """Handles arrays."""
334        datatype = self.minfile[self.pos]
335        self.pos += 1
336        length = self.tags[ord(datatype)]
337        if length is None :
338            raise PDLAnalyzerError, "Error on array length at %s" % self.pos
339        elif callable(length) :
340            length = length()
341        pos = self.pos   
342        posl = pos + length
343        sarraysize = self.minfile[pos:posl]
344        self.pos = posl
345        if self.islittleendian :
346            fmt = "<"
347        else :   
348            fmt = ">"
349        if length == 1 :   
350            fmt += "B"
351        elif length == 2 :   
352            fmt += "H"
353        elif length == 4 :   
354            fmt += "I"
355        else :   
356            raise PDLAnalyzerError, "Error on array size at %s" % self.pos
357        arraysize = struct.unpack(fmt, sarraysize)[0]
358        return arraysize * itemsize
359       
360    def array_8(self) :   
361        """Handles byte arrays."""
362        return self.handleArray(1)
363       
364    def array_16(self) :   
365        """Handles byte arrays."""
366        return self.handleArray(2)
367       
368    def array_32(self) :   
369        """Handles byte arrays."""
370        return self.handleArray(4)
371       
372    def embeddedDataSmall(self) :
373        """Handle small amounts of data."""
374        length = ord(self.minfile[self.pos])
375        self.pos += 1
376        return length
377       
378    def embeddedData(self) :
379        """Handle normal amounts of data."""
380        if self.islittleendian :
381            fmt = "<I"
382        else :   
383            fmt = ">I"
384        pos = self.pos
385        pos4 = pos + 4
386        data = self.minfile[pos:pos4]
387        self.pos = pos4
388        return struct.unpack(fmt, data)[0]
389       
390    def littleEndian(self) :       
391        """Toggles to little endianness."""
392        self.islittleendian = 1 # little endian
393        return 0
394       
395    def bigEndian(self) :   
396        """Toggles to big endianness."""
397        self.islittleendian = 0 # big endian
398        return 0
399   
400    def getJobSize(self) :
401        """Counts pages in a PCLXL (PCL6) document."""
402        infileno = self.infile.fileno()
403        self.minfile = mmap.mmap(infileno, os.fstat(infileno).st_size, access=mmap.ACCESS_READ)
404        self.pagecount = 0
405        self.pos = self.infile.tell()
406        try :
407            while 1 :
408                char = self.minfile[self.pos]
409                self.pos += 1
410                length = self.tags[ord(char)]
411                if not length :   
412                    continue
413                if callable(length) :   
414                    length = length()
415                self.pos += length   
416        except IndexError : # EOF ?
417            self.minfile.close() # reached EOF
418        return self.pagecount
419       
420class PDLAnalyzer :   
421    """Generic PDL Analyzer class."""
422    def __init__(self, filename) :
423        """Initializes the PDL analyzer.
424       
425           filename is the name of the file or '-' for stdin.
426           filename can also be a file-like object which
427           supports read() and seek().
428        """
429        self.filename = filename
430        try :
431            import psyco 
432        except ImportError :   
433            pass # Psyco is not installed
434        else :   
435            # Psyco is installed, tell it to compile
436            # the CPU intensive methods : PCL and PCLXL
437            # parsing will greatly benefit from this,
438            # for PostScript and PDF the difference is
439            # barely noticeable since they are already
440            # almost optimal, and much more speedy anyway.
441            psyco.bind(PostScriptAnalyzer.getJobSize)
442            psyco.bind(PDFAnalyzer.getJobSize)
443            psyco.bind(PCLAnalyzer.getJobSize)
444            psyco.bind(PCLXLAnalyzer.getJobSize)
445       
446    def getJobSize(self) :   
447        """Returns the job's size."""
448        self.openFile()
449        try :
450            pdlhandler = self.detectPDLHandler()
451        except PDLAnalyzerError, msg :   
452            self.closeFile()
453            raise PDLAnalyzerError, "ERROR : Unknown file format for %s (%s)" % (self.filename, msg)
454        else :
455            try :
456                size = pdlhandler(self.infile).getJobSize()
457            finally :   
458                self.closeFile()
459            return size
460       
461    def openFile(self) :   
462        """Opens the job's data stream for reading."""
463        self.mustclose = 0  # by default we don't want to close the file when finished
464        if hasattr(self.filename, "read") and hasattr(self.filename, "seek") :
465            # filename is in fact a file-like object
466            infile = self.filename
467        elif self.filename == "-" :
468            # we must read from stdin
469            infile = sys.stdin
470        else :   
471            # normal file
472            self.infile = open(self.filename, "rb")
473            self.mustclose = 1
474            return
475           
476        # Use a temporary file, always seekable contrary to standard input.
477        self.infile = tempfile.TemporaryFile(mode="w+b")
478        while 1 :
479            data = infile.read(MEGABYTE) 
480            if not data :
481                break
482            self.infile.write(data)
483        self.infile.flush()   
484        self.infile.seek(0)
485           
486    def closeFile(self) :       
487        """Closes the job's data stream if we can close it."""
488        if self.mustclose :
489            self.infile.close()   
490        else :   
491            # if we don't have to close the file, then
492            # ensure the file pointer is reset to the
493            # start of the file in case the process wants
494            # to read the file again.
495            try :
496                self.infile.seek(0)
497            except :   
498                pass    # probably stdin, which is not seekable
499       
500    def isPostScript(self, data) :   
501        """Returns 1 if data is PostScript, else 0."""
502        if data.startswith("%!") or \
503           data.startswith("\004%!") or \
504           data.startswith("\033%-12345X%!PS") or \
505           ((data[:128].find("\033%-12345X") != -1) and \
506             ((data.find("LANGUAGE=POSTSCRIPT") != -1) or \
507              (data.find("LANGUAGE = POSTSCRIPT") != -1) or \
508              (data.find("LANGUAGE = Postscript") != -1))) or \
509              (data.find("%!PS-Adobe") != -1) :
510            return 1
511        else :   
512            return 0
513       
514    def isPDF(self, data) :   
515        """Returns 1 if data is PDF, else 0."""
516        if data.startswith("%PDF-") or \
517           data.startswith("\033%-12345X%PDF-") or \
518           ((data[:128].find("\033%-12345X") != -1) and (data.upper().find("LANGUAGE=PDF") != -1)) or \
519           (data.find("%PDF-") != -1) :
520            return 1
521        else :   
522            return 0
523       
524    def isPCL(self, data) :   
525        """Returns 1 if data is PCL, else 0."""
526        if data.startswith("\033E\033") or \
527           ((data[:128].find("\033%-12345X") != -1) and \
528             ((data.find("LANGUAGE=PCL") != -1) or \
529              (data.find("LANGUAGE = PCL") != -1) or \
530              (data.find("LANGUAGE = Pcl") != -1))) :
531            return 1
532        else :   
533            return 0
534       
535    def isPCLXL(self, data) :   
536        """Returns 1 if data is PCLXL aka PCL6, else 0."""
537        if ((data[:128].find("\033%-12345X") != -1) and \
538             (data.find(" HP-PCL XL;") != -1) and \
539             ((data.find("LANGUAGE=PCLXL") != -1) or \
540              (data.find("LANGUAGE = PCLXL") != -1))) :
541            return 1
542        else :   
543            return 0
544           
545    def detectPDLHandler(self) :   
546        """Tries to autodetect the document format.
547       
548           Returns the correct PDL handler class or None if format is unknown
549        """   
550        # Try to detect file type by reading first block of datas   
551        self.infile.seek(0)
552        firstblock = self.infile.read(KILOBYTE)
553        self.infile.seek(0)
554        if self.isPostScript(firstblock) :
555            return PostScriptAnalyzer
556        elif self.isPCLXL(firstblock) :   
557            return PCLXLAnalyzer
558        elif self.isPCL(firstblock) :   
559            return PCLAnalyzer
560        elif self.isPDF(firstblock) :   
561            return PDFAnalyzer
562        else :   
563            raise PDLAnalyzerError, "Analysis of first data block failed."
564           
565def main() :   
566    """Entry point for PDL Analyzer."""
567    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
568        sys.argv.append("-")
569       
570    totalsize = 0   
571    for arg in sys.argv[1:] :
572        try :
573            parser = PDLAnalyzer(arg)
574            totalsize += parser.getJobSize()
575        except PDLAnalyzerError, msg :   
576            sys.stderr.write("ERROR: %s\n" % msg)
577            sys.stderr.flush()
578    print "%s" % totalsize
579   
580if __name__ == "__main__" :   
581    main()       
Note: See TracBrowser for help on using the browser.