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

Revision 1577, 22.9 kB (checked in by jalet, 20 years ago)

Code de-factorization in PCLXL parser

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