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

Revision 1701, 32.6 kB (checked in by jalet, 20 years ago)

Support for PCL3 (HP Deskjets) added to generic PDL parser

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
RevLine 
[1482]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$
[1701]24# Revision 1.40  2004/09/04 14:01:47  jalet
25# Support for PCL3 (HP Deskjets) added to generic PDL parser
26#
[1700]27# Revision 1.39  2004/09/02 23:30:05  jalet
28# Comments
29#
[1699]30# Revision 1.38  2004/09/02 22:08:37  jalet
31# First draft of PCL3GUI analyzer.
32#
[1698]33# Revision 1.37  2004/09/02 21:22:49  jalet
34# One more PCL tag
35#
[1690]36# Revision 1.36  2004/09/01 22:31:49  jalet
37# Some more work on ESC/P2 analyzer to avoid missing \r\n sequences. Not
38# exactly optimal though...
39#
[1686]40# Revision 1.35  2004/08/30 23:10:24  jalet
41# Improved the ESC/P2 analyzer so that more GhostScript devices are supported
42#
[1683]43# Revision 1.34  2004/08/27 09:08:22  jalet
44# Improvement in PostScript parser to avoid being fooled by clever "students"
45#
[1682]46# Revision 1.33  2004/08/27 09:02:34  jalet
47# Forgot to remove some special debugging code...
48#
[1681]49# Revision 1.32  2004/08/27 08:58:50  jalet
50# Relax checks for PCL5 header to accomodate strange printer drivers
51#
[1677]52# Revision 1.31  2004/08/22 08:25:33  jalet
53# Improved ESC/P2 miniparser thanks to Paulo Silva
54#
[1676]55# Revision 1.30  2004/08/21 23:16:57  jalet
56# First draft of ESC/P2 (mini-)parser.
57#
[1675]58# Revision 1.29  2004/08/11 16:25:38  jalet
59# Fixed index problem in PCLXL parser when retrieving number of copies for
60# each page
61#
[1674]62# Revision 1.28  2004/08/10 23:01:49  jalet
63# Fixed number of copies in PCL5 parser
64#
[1673]65# Revision 1.27  2004/08/09 18:14:22  jalet
66# Added workaround for number of copies and some PostScript drivers
67#
[1622]68# Revision 1.26  2004/07/22 13:49:51  jalet
69# Added support for binary PostScript through GhostScript if native DSC
70# compliant PostScript analyzer doesn't find any page. This is much
71# slower though, so native analyzer is tried first.
72#
[1599]73# Revision 1.25  2004/07/10 14:06:36  jalet
74# Fix for Python2.1 incompatibilities
75#
[1591]76# Revision 1.24  2004/07/05 21:00:39  jalet
77# Fix for number of copies for each page in PCLXL parser
78#
[1588]79# Revision 1.23  2004/07/03 08:21:59  jalet
80# Testsuite for PDL Analyzer added
81#
[1580]82# Revision 1.22  2004/06/29 14:21:41  jalet
83# Smallish optimization
84#
[1577]85# Revision 1.21  2004/06/28 23:11:26  jalet
86# Code de-factorization in PCLXL parser
87#
[1576]88# Revision 1.20  2004/06/28 22:38:41  jalet
89# Increased speed by a factor of 2 in PCLXL parser
90#
[1575]91# Revision 1.19  2004/06/28 21:20:30  jalet
92# PCLXL support now works !
93#
[1574]94# Revision 1.18  2004/06/27 22:59:37  jalet
95# More work on PCLXL parser
96#
[1573]97# Revision 1.17  2004/06/26 23:20:01  jalet
98# Additionnal speedup for GhostScript generated PCL5 files
99#
[1572]100# Revision 1.16  2004/06/26 15:31:00  jalet
101# mmap reintroduced in PCL5 parser
102#
[1570]103# Revision 1.15  2004/06/26 14:14:31  jalet
104# Now uses Psyco if it is available
105#
[1568]106# Revision 1.14  2004/06/25 09:50:28  jalet
107# More debug info in PCLXL parser
108#
[1567]109# Revision 1.13  2004/06/25 08:10:08  jalet
110# Another fix for PCL5 parser
111#
[1566]112# Revision 1.12  2004/06/24 23:09:53  jalet
113# Fix for number of copies in PCL5 parser
114#
[1564]115# Revision 1.11  2004/06/23 22:07:50  jalet
116# Fixed PCL5 parser according to the sources of rastertohp
117#
[1553]118# Revision 1.10  2004/06/18 22:24:03  jalet
119# Removed old comments
120#
[1552]121# Revision 1.9  2004/06/18 22:21:27  jalet
122# Native PDF parser greatly improved.
123# GhostScript based PDF parser completely removed because native code
124# is now portable across Python versions.
125#
[1551]126# Revision 1.8  2004/06/18 20:49:46  jalet
127# "ERROR:" prefix added
128#
[1550]129# Revision 1.7  2004/06/18 17:48:04  jalet
130# Added native fast PDF parsing method
131#
[1547]132# Revision 1.6  2004/06/18 14:00:16  jalet
133# Added PDF support in smart PDL analyzer (through GhostScript for now)
134#
[1544]135# Revision 1.5  2004/06/18 10:09:05  jalet
136# Resets file pointer to start of file in all cases
137#
[1543]138# Revision 1.4  2004/06/18 06:16:14  jalet
139# Fixes PostScript detection code for incorrect drivers
140#
[1487]141# Revision 1.3  2004/05/21 20:40:08  jalet
142# All the code for pkpgcounter is now in pdlanalyzer.py
143#
[1485]144# Revision 1.2  2004/05/19 19:09:36  jalet
145# Speed improvement
146#
[1482]147# Revision 1.1  2004/05/18 09:59:54  jalet
148# pkpgcounter is now just a wrapper around the PDLAnalyzer class
149#
150#
151#
152
153import sys
[1547]154import os
[1552]155import re
[1580]156from struct import unpack
[1482]157import tempfile
[1572]158import mmap
[1622]159import popen2
[1482]160   
[1487]161KILOBYTE = 1024   
162MEGABYTE = 1024 * KILOBYTE   
[1701]163LASTBLOCKSIZE = int(KILOBYTE / 4)
[1487]164
165class PDLAnalyzerError(Exception):
166    """An exception for PDL Analyzer related stuff."""
167    def __init__(self, message = ""):
168        self.message = message
169        Exception.__init__(self, message)
170    def __repr__(self):
171        return self.message
172    __str__ = __repr__
173   
[1482]174class PostScriptAnalyzer :
175    def __init__(self, infile) :
176        """Initialize PostScript Analyzer."""
177        self.infile = infile
[1673]178        self.copies = 1
[1622]179       
180    def throughGhostScript(self) :
181        """Get the count through GhostScript, useful for non-DSC compliant PS files."""
182        self.infile.seek(0)
183        command = 'gs -sDEVICE=bbox -dNOPAUSE -dBATCH -dQUIET - 2>&1 | grep -c "%%HiResBoundingBox:" 2>/dev/null'
184        child = popen2.Popen4(command)
185        try :
186            data = self.infile.read(MEGABYTE)   
187            while data :
188                child.tochild.write(data)
189                data = self.infile.read(MEGABYTE)
190            child.tochild.flush()
191            child.tochild.close()   
192        except (IOError, OSError), msg :   
193            raise PDLAnalyzerError, "Problem during analysis of Binary PostScript document."
194           
195        pagecount = 0
196        try :
197            pagecount = int(child.fromchild.readline().strip())
198        except (IOError, OSError, AttributeError, ValueError) :
199            raise PDLAnalyzerError, "Problem during analysis of Binary PostScript document."
200        child.fromchild.close()
[1482]201       
[1622]202        try :
203            retcode = child.wait()
204        except OSError, msg :   
205            raise PDLAnalyzerError, "Problem during analysis of Binary PostScript document."
[1673]206        return pagecount * self.copies
[1622]207       
208    def natively(self) :
[1482]209        """Count pages in a DSC compliant PostScript document."""
[1622]210        self.infile.seek(0)
[1482]211        pagecount = 0
[1552]212        for line in self.infile.xreadlines() : 
[1482]213            if line.startswith("%%Page: ") :
214                pagecount += 1
[1673]215            elif line.startswith("%%BeginNonPPDFeature: NumCopies ") :
216                # handle # of copies set by some Windows printer driver
217                try :
218                    number = int(line.strip().split()[2])
219                except :     
220                    pass
221                else :   
[1683]222                    if number > self.copies :
[1673]223                        self.copies = number
224            elif line.startswith("1 dict dup /NumCopies ") :
225                # handle # of copies set by mozilla/kprinter
226                try :
227                    number = int(line.strip().split()[4])
228                except :     
229                    pass
230                else :   
[1683]231                    if number > self.copies :
[1673]232                        self.copies = number
233        return pagecount * self.copies
[1482]234       
[1622]235    def getJobSize(self) :   
236        """Count pages in PostScript document."""
237        return self.natively() or self.throughGhostScript()
238       
[1547]239class PDFAnalyzer :
240    def __init__(self, infile) :
241        """Initialize PDF Analyzer."""
242        self.infile = infile
[1550]243               
[1552]244    def getJobSize(self) :   
245        """Counts pages in a PDF document."""
[1573]246        regexp = re.compile(r"(/Type) ?(/Page)[/ \t\r\n]")
[1550]247        pagecount = 0
[1552]248        for line in self.infile.xreadlines() : 
249            pagecount += len(regexp.findall(line))
[1550]250        return pagecount   
[1547]251       
[1676]252class ESCP2Analyzer :
253    def __init__(self, infile) :
254        """Initialize ESC/P2 Analyzer."""
255        self.infile = infile
256               
257    def getJobSize(self) :   
258        """Counts pages in an ESC/P2 document."""
[1686]259        # with Gimpprint, at least, for each page there
[1677]260        # are two Reset Printer sequences (ESC + @)
[1686]261        marker1 = "\033@"
262       
263        # with other software or printer driver, we
264        # may prefer to search for "\r\n\fESCAPE"
265        # or "\r\fESCAPE"
266        marker2r = "\r\f\033"
267        marker2rn = "\r\n\f\033"
268       
269        # and ghostscript's stcolor for example seems to
270        # output ESC + @ + \f for each page plus one
271        marker3 = "\033@\f"
272       
273        # while ghostscript's escp driver outputs instead
274        # \f + ESC + @
275        marker4 = "\f\033@"
276       
[1690]277        data = self.infile.read()
278        pagecount1 = data.count(marker1)
279        pagecount2 = max(data.count(marker2r), data.count(marker2rn))
280        pagecount3 = data.count(marker3)
281        pagecount4 = data.count(marker4)
[1686]282           
283        if pagecount2 :   
284            return pagecount2
285        elif pagecount3 > 1 :     
286            return pagecount3 - 1
287        elif pagecount4 :   
288            return pagecount4
289        else :   
290            return int(pagecount1 / 2)       
[1676]291       
[1482]292class PCLAnalyzer :
293    def __init__(self, infile) :
294        """Initialize PCL Analyzer."""
295        self.infile = infile
296       
297    def getJobSize(self) :     
[1591]298        """Count pages in a PCL5 document.
299         
300           Should also work for PCL3 and PCL4 documents.
301           
302           Algorithm from pclcount
303           (c) 2003, by Eduardo Gielamo Oliveira & Rodolfo Broco Manin
304           published under the terms of the GNU General Public Licence v2.
305         
306           Backported from C to Python by Jerome Alet, then enhanced
307           with more PCL tags detected. I think all the necessary PCL tags
308           are recognized to correctly handle PCL5 files wrt their number
309           of pages. The documentation used for this was :
310         
311           HP PCL/PJL Reference Set
312           PCL5 Printer Language Technical Quick Reference Guide
313           http://h20000.www2.hp.com/bc/docs/support/SupportManual/bpl13205/bpl13205.pdf
314        """
[1572]315        infileno = self.infile.fileno()
[1599]316        minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
[1482]317        tagsends = { "&n" : "W", 
318                     "&b" : "W", 
319                     "*i" : "W", 
320                     "*l" : "W", 
321                     "*m" : "W", 
322                     "*v" : "W", 
323                     "*c" : "W", 
324                     "(f" : "W", 
325                     "(s" : "W", 
326                     ")s" : "W", 
327                     "&p" : "X", 
[1564]328                     "&l" : "XH",
[1700]329                     "&a" : "G", # TODO : 0 means next side, 1 front side, 2 back side
[1698]330                     "*g" : "W",
[1701]331                     "*r" : "sbABC",
[1573]332                     # "*b" : "VW", # treated specially because it occurs very often
[1564]333                   } 
[1701]334        pagecount = resets = ejects = backsides = startgfx = endgfx = strangegfx = 0
335        starb = ispcl3 = 0
[1482]336        tag = None
[1566]337        copies = {}
[1572]338        pos = 0
339        try :
340            while 1 :
341                char = minfile[pos] ; pos += 1
342                if char == "\014" :   
343                    pagecount += 1
344                elif char == "\033" :   
[1701]345                    starb = 0
[1572]346                    #
[1701]347                    #     <ESC>*b###y#m###v###w... -> PCL3 raster graphics
[1572]348                    #     <ESC>*b###W -> Start of a raster data row/block
349                    #     <ESC>*b###V -> Start of a raster data plane
350                    #     <ESC>*c###W -> Start of a user defined pattern
351                    #     <ESC>*i###W -> Start of a viewing illuminant block
352                    #     <ESC>*l###W -> Start of a color lookup table
353                    #     <ESC>*m###W -> Start of a download dither matrix block
354                    #     <ESC>*v###W -> Start of a configure image data block
[1701]355                    #     <ESC>*r1A -> Start Gfx
[1572]356                    #     <ESC>(s###W -> Start of a characters description block
357                    #     <ESC>)s###W -> Start of a fonts description block
358                    #     <ESC>(f###W -> Start of a symbol set block
359                    #     <ESC>&b###W -> Start of configuration data block
360                    #     <ESC>&l###X -> Number of copies for current page
361                    #     <ESC>&n###W -> Starts an alphanumeric string ID block
362                    #     <ESC>&p###X -> Start of a non printable characters block
363                    #     <ESC>&a2G -> Back side when duplex mode as generated by rastertohp
[1698]364                    #     <ESC>*g###W -> Needed for planes in PCL3 output
[1572]365                    #     <ESC>&l0H -> Eject if NumPlanes > 1, as generated by rastertohp
366                    #
367                    tagstart = minfile[pos] ; pos += 1
368                    if tagstart in "E9=YZ" : # one byte PCL tag
369                        if tagstart == "E" :
370                            resets += 1
371                        continue             # skip to next tag
372                    tag = tagstart + minfile[pos] ; pos += 1
[1573]373                    if tag == "*b" : 
[1701]374                        starb = 1
[1573]375                        tagend = "VW"
[1572]376                    else :   
[1573]377                        try :
378                            tagend = tagsends[tag]
379                        except KeyError :   
380                            continue # Unsupported PCL tag
381                    # Now read the numeric argument
382                    size = 0
383                    while 1 :
384                        char = minfile[pos] ; pos += 1
385                        if not char.isdigit() :
386                            break
387                        size = (size * 10) + int(char)   
388                    if char in tagend :   
389                        if (tag == "&l") and (char == "X") : # copies for current page
390                            copies[pagecount] = size
391                        elif (tag == "&l") and (char == "H") and (size == 0) :   
392                            ejects += 1         # Eject
[1701]393                        elif (tag == "*r") :
394                            # Special tests for PCL3
395                            if (char == "s") and size :
396                                while 1 :
397                                    char = minfile[pos] ; pos += 1
398                                    if char == "A" :
399                                        break
400                            elif (char == "b") and (minfile[pos] == "C") and not size :
401                                ispcl3 = 1 # Certainely a PCL3 file
402                            startgfx += (char == "A") and (minfile[pos - 2] in ("0", "1", "2", "3")) # Start Gfx
403                            endgfx += (not size) and (char in ("C", "B")) # End Gfx
[1573]404                        elif (tag == "&a") and (size == 2) :
405                            backsides += 1      # Back side in duplex mode
406                        else :   
407                            # we just ignore the block.
408                            if tag == "&n" : 
409                                # we have to take care of the operation id byte
410                                # which is before the string itself
411                                size += 1
412                            pos += size   
[1701]413                else :                           
414                    if starb :
415                        # special handling of PCL3 in which
416                        # *b introduces combined ESCape sequences
417                        size = 0
418                        while 1 :
419                            char = minfile[pos] ; pos += 1
420                            if not char.isdigit() :
421                                break
422                            size = (size * 10) + int(char)   
423                        if char in ("w", "v") :   
424                            ispcl3 = 1  # certainely a PCL3 document
425                            pos += size - 1
426                        elif char in ("y", "m") :   
427                            ispcl3 = 1  # certainely a PCL3 document
428                            pos -= 1    # fix position : we were ahead
[1572]429        except IndexError : # EOF ?
430            minfile.close() # reached EOF
[1482]431                           
[1567]432        # if pagecount is still 0, we will use the number
[1482]433        # of resets instead of the number of form feed characters.
434        # but the number of resets is always at least 2 with a valid
435        # pcl file : one at the very start and one at the very end
436        # of the job's data. So we substract 2 from the number of
437        # resets. And since on our test data we needed to substract
438        # 1 more, we finally substract 3, and will test several
439        # PCL files with this. If resets < 2, then the file is
[1567]440        # probably not a valid PCL file, so we use 0
441        if not pagecount :
442            pagecount = (pagecount or ((resets - 3) * (resets > 2)))
443        else :   
444            # here we add counters for other ways new pages may have
445            # been printed and ejected by the printer
446            pagecount += ejects + backsides
[1482]447       
[1566]448        # now handle number of copies for each page (may differ).
449        # in duplex mode, number of copies may be sent only once.
450        for pnum in range(pagecount) :
[1674]451            # if no number of copies defined, take the preceding one else the one set before any page else 1.
452            nb = copies.get(pnum, copies.get(pnum-1, copies.get(0, 1)))
[1566]453            pagecount += (nb - 1)
[1701]454           
455        # in PCL3 files, there's one Start Gfx tag per page
456        if ispcl3 :
457            if endgfx == int(startgfx / 2) : # special case for cdj1600
458                pagecount = endgfx 
459            elif startgfx :
460                pagecount = startgfx
461            elif endgfx :   
462                pagecount = endgfx
463           
[1566]464        return pagecount
465       
[1482]466class PCLXLAnalyzer :
467    def __init__(self, infile) :
468        """Initialize PCLXL Analyzer."""
469        self.infile = infile
[1577]470        self.endianness = None
[1482]471        found = 0
472        while not found :
473            line = self.infile.readline()
474            if not line :
475                break
476            if line[1:12] == " HP-PCL XL;" :
477                found = 1
[1574]478                endian = ord(line[0])
479                if endian == 0x29 :
[1575]480                    self.littleEndian()
[1574]481                elif endian == 0x28 :   
[1575]482                    self.bigEndian()
483                # elif endian == 0x27 : TODO : What can we do here ?   
484                #
[1574]485                else :   
[1591]486                    raise PDLAnalyzerError, "Unknown endianness marker 0x%02x at start !" % endian
[1482]487        if not found :
[1487]488            raise PDLAnalyzerError, "This file doesn't seem to be PCLXL (aka PCL6)"
[1482]489        else :   
[1575]490            # Initialize table of tags
491            self.tags = [ 0 ] * 256   
[1574]492           
[1575]493            # GhostScript's sources tell us that HP printers
494            # only accept little endianness, but we can handle both.
495            self.tags[0x28] = self.bigEndian    # BigEndian
496            self.tags[0x29] = self.littleEndian # LittleEndian
[1574]497           
[1482]498            self.tags[0x43] = self.beginPage    # BeginPage
[1591]499            self.tags[0x44] = self.endPage      # EndPage
[1482]500           
[1575]501            self.tags[0xc0] = 1 # ubyte
502            self.tags[0xc1] = 2 # uint16
503            self.tags[0xc2] = 4 # uint32
504            self.tags[0xc3] = 2 # sint16
505            self.tags[0xc4] = 4 # sint32
506            self.tags[0xc5] = 4 # real32
[1574]507           
[1482]508            self.tags[0xc8] = self.array_8  # ubyte_array
509            self.tags[0xc9] = self.array_16 # uint16_array
510            self.tags[0xca] = self.array_32 # uint32_array
511            self.tags[0xcb] = self.array_16 # sint16_array
512            self.tags[0xcc] = self.array_32 # sint32_array
513            self.tags[0xcd] = self.array_32 # real32_array
514           
[1575]515            self.tags[0xd0] = 2 # ubyte_xy
516            self.tags[0xd1] = 4 # uint16_xy
517            self.tags[0xd2] = 8 # uint32_xy
518            self.tags[0xd3] = 4 # sint16_xy
519            self.tags[0xd4] = 8 # sint32_xy
520            self.tags[0xd5] = 8 # real32_xy
[1482]521           
[1575]522            self.tags[0xe0] = 4  # ubyte_box
523            self.tags[0xe1] = 8  # uint16_box
524            self.tags[0xe2] = 16 # uint32_box
525            self.tags[0xe3] = 8  # sint16_box
526            self.tags[0xe4] = 16 # sint32_box
527            self.tags[0xe5] = 16 # real32_box
[1482]528           
[1575]529            self.tags[0xf8] = 1 # attr_ubyte
530            self.tags[0xf9] = 2 # attr_uint16
[1482]531           
532            self.tags[0xfa] = self.embeddedData      # dataLength
533            self.tags[0xfb] = self.embeddedDataSmall # dataLengthByte
534           
535    def beginPage(self) :
536        """Indicates the beginning of a new page."""
537        self.pagecount += 1
[1575]538        return 0
[1482]539       
[1591]540    def endPage(self) :   
541        """Indicates the end of a page."""
542        pos = self.pos
543        minfile = self.minfile
544        if (ord(minfile[pos-3]) == 0xf8) and (ord(minfile[pos-2]) == 0x31) :
545            # The EndPage operator is preceded by a PageCopies attribute
546            # So set number of copies for current page.
547            # From what I read in PCLXL documentation, the number
548            # of copies is an unsigned 16 bits integer
549            self.copies[self.pagecount] = unpack(self.endianness + "H", minfile[pos-5:pos-3])[0]
550        return 0
551       
[1577]552    def array_8(self) :   
553        """Handles byte arrays."""
[1576]554        pos = self.pos
555        datatype = self.minfile[pos]
556        pos += 1
[1575]557        length = self.tags[ord(datatype)]
[1576]558        if callable(length) :
559            self.pos = pos
[1575]560            length = length()
[1576]561            pos = self.pos
[1575]562        posl = pos + length
563        self.pos = posl
564        if length == 1 :   
[1580]565            return unpack("B", self.minfile[pos:posl])[0]
[1575]566        elif length == 2 :   
[1580]567            return unpack(self.endianness + "H", self.minfile[pos:posl])[0]
[1575]568        elif length == 4 :   
[1580]569            return unpack(self.endianness + "I", self.minfile[pos:posl])[0]
[1575]570        else :   
571            raise PDLAnalyzerError, "Error on array size at %s" % self.pos
[1482]572       
573    def array_16(self) :   
574        """Handles byte arrays."""
[1577]575        pos = self.pos
576        datatype = self.minfile[pos]
577        pos += 1
578        length = self.tags[ord(datatype)]
579        if callable(length) :
580            self.pos = pos
581            length = length()
582            pos = self.pos
583        posl = pos + length
584        self.pos = posl
585        if length == 1 :   
[1580]586            return 2 * unpack("B", self.minfile[pos:posl])[0]
[1577]587        elif length == 2 :   
[1580]588            return 2 * unpack(self.endianness + "H", self.minfile[pos:posl])[0]
[1577]589        elif length == 4 :   
[1580]590            return 2 * unpack(self.endianness + "I", self.minfile[pos:posl])[0]
[1577]591        else :   
592            raise PDLAnalyzerError, "Error on array size at %s" % self.pos
[1482]593       
594    def array_32(self) :   
595        """Handles byte arrays."""
[1577]596        pos = self.pos
597        datatype = self.minfile[pos]
598        pos += 1
599        length = self.tags[ord(datatype)]
600        if callable(length) :
601            self.pos = pos
602            length = length()
603            pos = self.pos
604        posl = pos + length
605        self.pos = posl
606        if length == 1 :   
[1580]607            return 4 * unpack("B", self.minfile[pos:posl])[0]
[1577]608        elif length == 2 :   
[1580]609            return 4 * unpack(self.endianness + "H", self.minfile[pos:posl])[0]
[1577]610        elif length == 4 :   
[1580]611            return 4 * unpack(self.endianness + "I", self.minfile[pos:posl])[0]
[1577]612        else :   
613            raise PDLAnalyzerError, "Error on array size at %s" % self.pos
[1482]614       
615    def embeddedDataSmall(self) :
616        """Handle small amounts of data."""
[1576]617        pos = self.pos
618        length = ord(self.minfile[pos])
619        self.pos = pos + 1
[1575]620        return length
[1482]621       
622    def embeddedData(self) :
623        """Handle normal amounts of data."""
[1575]624        pos = self.pos
625        pos4 = pos + 4
626        self.pos = pos4
[1588]627        return unpack(self.endianness + "I", self.minfile[pos:pos4])[0]
[1482]628       
[1575]629    def littleEndian(self) :       
[1482]630        """Toggles to little endianness."""
[1577]631        self.endianness = "<" # little endian
[1575]632        return 0
[1482]633       
[1575]634    def bigEndian(self) :   
[1482]635        """Toggles to big endianness."""
[1577]636        self.endianness = ">" # big endian
[1575]637        return 0
[1482]638   
639    def getJobSize(self) :
[1591]640        """Counts pages in a PCLXL (PCL6) document.
641       
642           Algorithm by Jerome Alet.
643           
644           The documentation used for this was :
645         
646           HP PCL XL Feature Reference
647           Protocol Class 2.0
648           http://www.hpdevelopersolutions.com/downloads/64/358/xl_ref20r22.pdf
649        """
[1575]650        infileno = self.infile.fileno()
[1591]651        self.copies = {}
[1599]652        self.minfile = minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
[1576]653        tags = self.tags
[1482]654        self.pagecount = 0
[1576]655        self.pos = pos = self.infile.tell()
[1575]656        try :
657            while 1 :
[1576]658                char = minfile[pos]
659                pos += 1
660                length = tags[ord(char)]
661                if not length :
[1575]662                    continue
663                if callable(length) :   
[1576]664                    self.pos = pos
[1575]665                    length = length()
[1576]666                    pos = self.pos
667                pos += length   
[1575]668        except IndexError : # EOF ?
669            self.minfile.close() # reached EOF
[1591]670           
671        # now handle number of copies for each page (may differ).
[1675]672        for pnum in range(1, self.pagecount + 1) :
[1591]673            # if no number of copies defined, take 1, as explained
674            # in PCLXL documentation.
675            # NB : is number of copies is 0, the page won't be output
676            # but the formula below is still correct : we want
677            # to decrease the total number of pages in this case.
678            self.pagecount += (self.copies.get(pnum, 1) - 1)
679           
[1482]680        return self.pagecount
[1487]681       
[1482]682class PDLAnalyzer :   
683    """Generic PDL Analyzer class."""
684    def __init__(self, filename) :
[1487]685        """Initializes the PDL analyzer.
686       
687           filename is the name of the file or '-' for stdin.
688           filename can also be a file-like object which
689           supports read() and seek().
690        """
[1482]691        self.filename = filename
[1570]692        try :
693            import psyco 
694        except ImportError :   
695            pass # Psyco is not installed
696        else :   
697            # Psyco is installed, tell it to compile
698            # the CPU intensive methods : PCL and PCLXL
699            # parsing will greatly benefit from this,
700            # for PostScript and PDF the difference is
701            # barely noticeable since they are already
702            # almost optimal, and much more speedy anyway.
703            psyco.bind(PostScriptAnalyzer.getJobSize)
704            psyco.bind(PDFAnalyzer.getJobSize)
[1686]705            psyco.bind(ESCP2Analyzer.getJobSize)
[1570]706            psyco.bind(PCLAnalyzer.getJobSize)
707            psyco.bind(PCLXLAnalyzer.getJobSize)
[1482]708       
709    def getJobSize(self) :   
710        """Returns the job's size."""
711        self.openFile()
[1487]712        try :
713            pdlhandler = self.detectPDLHandler()
714        except PDLAnalyzerError, msg :   
715            self.closeFile()
716            raise PDLAnalyzerError, "ERROR : Unknown file format for %s (%s)" % (self.filename, msg)
717        else :
[1482]718            try :
719                size = pdlhandler(self.infile).getJobSize()
720            finally :   
721                self.closeFile()
722            return size
723       
724    def openFile(self) :   
725        """Opens the job's data stream for reading."""
[1550]726        self.mustclose = 0  # by default we don't want to close the file when finished
[1487]727        if hasattr(self.filename, "read") and hasattr(self.filename, "seek") :
728            # filename is in fact a file-like object
[1550]729            infile = self.filename
[1487]730        elif self.filename == "-" :
[1482]731            # we must read from stdin
[1550]732            infile = sys.stdin
[1482]733        else :   
734            # normal file
[1553]735            self.infile = open(self.filename, "rb")
[1550]736            self.mustclose = 1
737            return
[1482]738           
[1550]739        # Use a temporary file, always seekable contrary to standard input.
[1553]740        self.infile = tempfile.TemporaryFile(mode="w+b")
[1550]741        while 1 :
742            data = infile.read(MEGABYTE) 
743            if not data :
744                break
745            self.infile.write(data)
746        self.infile.flush()   
747        self.infile.seek(0)
748           
[1482]749    def closeFile(self) :       
[1487]750        """Closes the job's data stream if we can close it."""
751        if self.mustclose :
752            self.infile.close()   
[1544]753        else :   
754            # if we don't have to close the file, then
755            # ensure the file pointer is reset to the
756            # start of the file in case the process wants
757            # to read the file again.
758            try :
759                self.infile.seek(0)
760            except :   
761                pass    # probably stdin, which is not seekable
[1482]762       
[1701]763    def isPostScript(self, sdata, edata) :   
[1482]764        """Returns 1 if data is PostScript, else 0."""
[1701]765        if sdata.startswith("%!") or \
766           sdata.startswith("\004%!") or \
767           sdata.startswith("\033%-12345X%!PS") or \
768           ((sdata[:128].find("\033%-12345X") != -1) and \
769             ((sdata.find("LANGUAGE=POSTSCRIPT") != -1) or \
770              (sdata.find("LANGUAGE = POSTSCRIPT") != -1) or \
771              (sdata.find("LANGUAGE = Postscript") != -1))) or \
772              (sdata.find("%!PS-Adobe") != -1) :
[1482]773            return 1
774        else :   
775            return 0
776       
[1701]777    def isPDF(self, sdata, edata) :   
[1547]778        """Returns 1 if data is PDF, else 0."""
[1701]779        if sdata.startswith("%PDF-") or \
780           sdata.startswith("\033%-12345X%PDF-") or \
781           ((sdata[:128].find("\033%-12345X") != -1) and (sdata.upper().find("LANGUAGE=PDF") != -1)) or \
782           (sdata.find("%PDF-") != -1) :
[1547]783            return 1
784        else :   
785            return 0
786       
[1701]787    def isPCL(self, sdata, edata) :   
[1482]788        """Returns 1 if data is PCL, else 0."""
[1701]789        if sdata.startswith("\033E\033") or \
790           (sdata.startswith("\033*rbC") and (not edata[-3:] == "\f\033@")) or \
791           (sdata.find("\033%-12345X") != -1) :
[1482]792            return 1
793        else :   
794            return 0
795       
[1701]796    def isPCLXL(self, sdata, edata) :   
[1482]797        """Returns 1 if data is PCLXL aka PCL6, else 0."""
[1701]798        if ((sdata[:128].find("\033%-12345X") != -1) and \
799             (sdata.find(" HP-PCL XL;") != -1) and \
800             ((sdata.find("LANGUAGE=PCLXL") != -1) or \
801              (sdata.find("LANGUAGE = PCLXL") != -1))) :
[1482]802            return 1
803        else :   
804            return 0
805           
[1701]806    def isESCP2(self, sdata, edata) :       
[1676]807        """Returns 1 if data is ESC/P2, else 0."""
[1701]808        if sdata.startswith("\033@") or \
809           sdata.startswith("\033*") or \
810           sdata.startswith("\n\033@") :
[1676]811            return 1
812        else :   
813            return 0
814   
[1482]815    def detectPDLHandler(self) :   
816        """Tries to autodetect the document format.
817       
818           Returns the correct PDL handler class or None if format is unknown
819        """   
820        # Try to detect file type by reading first block of datas   
821        self.infile.seek(0)
[1699]822        firstblock = self.infile.read(4 * KILOBYTE)
[1701]823        try :
824            self.infile.seek(-LASTBLOCKSIZE, 2)
825        except IOError :   
826            lastblock = ""
827        else :   
828            lastblock = self.infile.read(LASTBLOCKSIZE)
[1482]829        self.infile.seek(0)
[1701]830        if self.isPostScript(firstblock, lastblock) :
[1482]831            return PostScriptAnalyzer
[1701]832        elif self.isPCLXL(firstblock, lastblock) :   
[1482]833            return PCLXLAnalyzer
[1701]834        elif self.isPDF(firstblock, lastblock) :   
[1681]835            return PDFAnalyzer
[1701]836        elif self.isPCL(firstblock, lastblock) :   
[1482]837            return PCLAnalyzer
[1701]838        elif self.isESCP2(firstblock, lastblock) :   
[1676]839            return ESCP2Analyzer
[1487]840        else :   
841            raise PDLAnalyzerError, "Analysis of first data block failed."
842           
843def main() :   
844    """Entry point for PDL Analyzer."""
845    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
846        sys.argv.append("-")
847       
848    totalsize = 0   
849    for arg in sys.argv[1:] :
850        try :
851            parser = PDLAnalyzer(arg)
852            totalsize += parser.getJobSize()
853        except PDLAnalyzerError, msg :   
[1551]854            sys.stderr.write("ERROR: %s\n" % msg)
[1487]855            sys.stderr.flush()
856    print "%s" % totalsize
857   
858if __name__ == "__main__" :   
[1577]859    main()
Note: See TracBrowser for help on using the browser.