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

Revision 1683, 28.5 kB (checked in by jalet, 20 years ago)

Improvement in PostScript? parser to avoid being fooled by clever "students"

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