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

Revision 1591, 24.4 kB (checked in by jalet, 20 years ago)

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