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

Revision 1599, 24.5 kB (checked in by jalet, 20 years ago)

Fix for Python2.1 incompatibilities

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