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

Revision 1681, 28.4 kB (checked in by jalet, 20 years ago)

Relax checks for PCL5 header to accomodate strange printer drivers

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