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
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota - Print Quotas for CUPS and LPRng
5#
6# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20#
21# $Id$
22#
23# $Log$
24# Revision 1.34  2004/08/27 09:08:22  jalet
25# Improvement in PostScript parser to avoid being fooled by clever "students"
26#
27# Revision 1.33  2004/08/27 09:02:34  jalet
28# Forgot to remove some special debugging code...
29#
30# Revision 1.32  2004/08/27 08:58:50  jalet
31# Relax checks for PCL5 header to accomodate strange printer drivers
32#
33# Revision 1.31  2004/08/22 08:25:33  jalet
34# Improved ESC/P2 miniparser thanks to Paulo Silva
35#
36# Revision 1.30  2004/08/21 23:16:57  jalet
37# First draft of ESC/P2 (mini-)parser.
38#
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#
43# Revision 1.28  2004/08/10 23:01:49  jalet
44# Fixed number of copies in PCL5 parser
45#
46# Revision 1.27  2004/08/09 18:14:22  jalet
47# Added workaround for number of copies and some PostScript drivers
48#
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#
54# Revision 1.25  2004/07/10 14:06:36  jalet
55# Fix for Python2.1 incompatibilities
56#
57# Revision 1.24  2004/07/05 21:00:39  jalet
58# Fix for number of copies for each page in PCLXL parser
59#
60# Revision 1.23  2004/07/03 08:21:59  jalet
61# Testsuite for PDL Analyzer added
62#
63# Revision 1.22  2004/06/29 14:21:41  jalet
64# Smallish optimization
65#
66# Revision 1.21  2004/06/28 23:11:26  jalet
67# Code de-factorization in PCLXL parser
68#
69# Revision 1.20  2004/06/28 22:38:41  jalet
70# Increased speed by a factor of 2 in PCLXL parser
71#
72# Revision 1.19  2004/06/28 21:20:30  jalet
73# PCLXL support now works !
74#
75# Revision 1.18  2004/06/27 22:59:37  jalet
76# More work on PCLXL parser
77#
78# Revision 1.17  2004/06/26 23:20:01  jalet
79# Additionnal speedup for GhostScript generated PCL5 files
80#
81# Revision 1.16  2004/06/26 15:31:00  jalet
82# mmap reintroduced in PCL5 parser
83#
84# Revision 1.15  2004/06/26 14:14:31  jalet
85# Now uses Psyco if it is available
86#
87# Revision 1.14  2004/06/25 09:50:28  jalet
88# More debug info in PCLXL parser
89#
90# Revision 1.13  2004/06/25 08:10:08  jalet
91# Another fix for PCL5 parser
92#
93# Revision 1.12  2004/06/24 23:09:53  jalet
94# Fix for number of copies in PCL5 parser
95#
96# Revision 1.11  2004/06/23 22:07:50  jalet
97# Fixed PCL5 parser according to the sources of rastertohp
98#
99# Revision 1.10  2004/06/18 22:24:03  jalet
100# Removed old comments
101#
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#
107# Revision 1.8  2004/06/18 20:49:46  jalet
108# "ERROR:" prefix added
109#
110# Revision 1.7  2004/06/18 17:48:04  jalet
111# Added native fast PDF parsing method
112#
113# Revision 1.6  2004/06/18 14:00:16  jalet
114# Added PDF support in smart PDL analyzer (through GhostScript for now)
115#
116# Revision 1.5  2004/06/18 10:09:05  jalet
117# Resets file pointer to start of file in all cases
118#
119# Revision 1.4  2004/06/18 06:16:14  jalet
120# Fixes PostScript detection code for incorrect drivers
121#
122# Revision 1.3  2004/05/21 20:40:08  jalet
123# All the code for pkpgcounter is now in pdlanalyzer.py
124#
125# Revision 1.2  2004/05/19 19:09:36  jalet
126# Speed improvement
127#
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
135import os
136import re
137from struct import unpack
138import tempfile
139import mmap
140import popen2
141   
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   
154class PostScriptAnalyzer :
155    def __init__(self, infile) :
156        """Initialize PostScript Analyzer."""
157        self.infile = infile
158        self.copies = 1
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()
181       
182        try :
183            retcode = child.wait()
184        except OSError, msg :   
185            raise PDLAnalyzerError, "Problem during analysis of Binary PostScript document."
186        return pagecount * self.copies
187       
188    def natively(self) :
189        """Count pages in a DSC compliant PostScript document."""
190        self.infile.seek(0)
191        pagecount = 0
192        for line in self.infile.xreadlines() : 
193            if line.startswith("%%Page: ") :
194                pagecount += 1
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 :   
202                    if number > self.copies :
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 :   
211                    if number > self.copies :
212                        self.copies = number
213        return pagecount * self.copies
214       
215    def getJobSize(self) :   
216        """Count pages in PostScript document."""
217        return self.natively() or self.throughGhostScript()
218       
219class PDFAnalyzer :
220    def __init__(self, infile) :
221        """Initialize PDF Analyzer."""
222        self.infile = infile
223               
224    def getJobSize(self) :   
225        """Counts pages in a PDF document."""
226        regexp = re.compile(r"(/Type) ?(/Page)[/ \t\r\n]")
227        pagecount = 0
228        for line in self.infile.xreadlines() : 
229            pagecount += len(regexp.findall(line))
230        return pagecount   
231       
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."""
239        # with GhostScript, at least, for each page there
240        # are two Reset Printer sequences (ESC + @)
241        marker = "\033@"
242        pagecount = 0
243        for line in self.infile.xreadlines() : 
244            pagecount += line.count(marker)
245        return int(pagecount / 2)       
246       
247class PCLAnalyzer :
248    def __init__(self, infile) :
249        """Initialize PCL Analyzer."""
250        self.infile = infile
251       
252    def getJobSize(self) :     
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        """
270        infileno = self.infile.fileno()
271        minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
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", 
283                     "&l" : "XH",
284                     "&a" : "G",
285                     # "*b" : "VW", # treated specially because it occurs very often
286                   } 
287        pagecount = resets = ejects = backsides = 0
288        tag = None
289        copies = {}
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
321                    if tag == "*b" : 
322                        tagend = "VW"
323                    else :   
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   
349        except IndexError : # EOF ?
350            minfile.close() # reached EOF
351                           
352        # if pagecount is still 0, we will use the number
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
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
367       
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) :
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)))
373            pagecount += (nb - 1)
374        return pagecount
375       
376class PCLXLAnalyzer :
377    def __init__(self, infile) :
378        """Initialize PCLXL Analyzer."""
379        self.infile = infile
380        self.endianness = None
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
388                endian = ord(line[0])
389                if endian == 0x29 :
390                    self.littleEndian()
391                elif endian == 0x28 :   
392                    self.bigEndian()
393                # elif endian == 0x27 : TODO : What can we do here ?   
394                #
395                else :   
396                    raise PDLAnalyzerError, "Unknown endianness marker 0x%02x at start !" % endian
397        if not found :
398            raise PDLAnalyzerError, "This file doesn't seem to be PCLXL (aka PCL6)"
399        else :   
400            # Initialize table of tags
401            self.tags = [ 0 ] * 256   
402           
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
407           
408            self.tags[0x43] = self.beginPage    # BeginPage
409            self.tags[0x44] = self.endPage      # EndPage
410           
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
417           
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           
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
431           
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
438           
439            self.tags[0xf8] = 1 # attr_ubyte
440            self.tags[0xf9] = 2 # attr_uint16
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
448        return 0
449       
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       
462    def array_8(self) :   
463        """Handles byte arrays."""
464        pos = self.pos
465        datatype = self.minfile[pos]
466        pos += 1
467        length = self.tags[ord(datatype)]
468        if callable(length) :
469            self.pos = pos
470            length = length()
471            pos = self.pos
472        posl = pos + length
473        self.pos = posl
474        if length == 1 :   
475            return unpack("B", self.minfile[pos:posl])[0]
476        elif length == 2 :   
477            return unpack(self.endianness + "H", self.minfile[pos:posl])[0]
478        elif length == 4 :   
479            return unpack(self.endianness + "I", self.minfile[pos:posl])[0]
480        else :   
481            raise PDLAnalyzerError, "Error on array size at %s" % self.pos
482       
483    def array_16(self) :   
484        """Handles byte arrays."""
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 :   
496            return 2 * unpack("B", self.minfile[pos:posl])[0]
497        elif length == 2 :   
498            return 2 * unpack(self.endianness + "H", self.minfile[pos:posl])[0]
499        elif length == 4 :   
500            return 2 * unpack(self.endianness + "I", self.minfile[pos:posl])[0]
501        else :   
502            raise PDLAnalyzerError, "Error on array size at %s" % self.pos
503       
504    def array_32(self) :   
505        """Handles byte arrays."""
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 :   
517            return 4 * unpack("B", self.minfile[pos:posl])[0]
518        elif length == 2 :   
519            return 4 * unpack(self.endianness + "H", self.minfile[pos:posl])[0]
520        elif length == 4 :   
521            return 4 * unpack(self.endianness + "I", self.minfile[pos:posl])[0]
522        else :   
523            raise PDLAnalyzerError, "Error on array size at %s" % self.pos
524       
525    def embeddedDataSmall(self) :
526        """Handle small amounts of data."""
527        pos = self.pos
528        length = ord(self.minfile[pos])
529        self.pos = pos + 1
530        return length
531       
532    def embeddedData(self) :
533        """Handle normal amounts of data."""
534        pos = self.pos
535        pos4 = pos + 4
536        self.pos = pos4
537        return unpack(self.endianness + "I", self.minfile[pos:pos4])[0]
538       
539    def littleEndian(self) :       
540        """Toggles to little endianness."""
541        self.endianness = "<" # little endian
542        return 0
543       
544    def bigEndian(self) :   
545        """Toggles to big endianness."""
546        self.endianness = ">" # big endian
547        return 0
548   
549    def getJobSize(self) :
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        """
560        infileno = self.infile.fileno()
561        self.copies = {}
562        self.minfile = minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
563        tags = self.tags
564        self.pagecount = 0
565        self.pos = pos = self.infile.tell()
566        try :
567            while 1 :
568                char = minfile[pos]
569                pos += 1
570                length = tags[ord(char)]
571                if not length :
572                    continue
573                if callable(length) :   
574                    self.pos = pos
575                    length = length()
576                    pos = self.pos
577                pos += length   
578        except IndexError : # EOF ?
579            self.minfile.close() # reached EOF
580           
581        # now handle number of copies for each page (may differ).
582        for pnum in range(1, self.pagecount + 1) :
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           
590        return self.pagecount
591       
592class PDLAnalyzer :   
593    """Generic PDL Analyzer class."""
594    def __init__(self, filename) :
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        """
601        self.filename = filename
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)
617       
618    def getJobSize(self) :   
619        """Returns the job's size."""
620        self.openFile()
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 :
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."""
635        self.mustclose = 0  # by default we don't want to close the file when finished
636        if hasattr(self.filename, "read") and hasattr(self.filename, "seek") :
637            # filename is in fact a file-like object
638            infile = self.filename
639        elif self.filename == "-" :
640            # we must read from stdin
641            infile = sys.stdin
642        else :   
643            # normal file
644            self.infile = open(self.filename, "rb")
645            self.mustclose = 1
646            return
647           
648        # Use a temporary file, always seekable contrary to standard input.
649        self.infile = tempfile.TemporaryFile(mode="w+b")
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           
658    def closeFile(self) :       
659        """Closes the job's data stream if we can close it."""
660        if self.mustclose :
661            self.infile.close()   
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
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 \
680              (data.find("LANGUAGE = Postscript") != -1))) or \
681              (data.find("%!PS-Adobe") != -1) :
682            return 1
683        else :   
684            return 0
685       
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       
696    def isPCL(self, data) :   
697        """Returns 1 if data is PCL, else 0."""
698        if data.startswith("\033E\033") or \
699           (data[:128].find("\033%-12345X") != -1) :
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           
714    def isESCP2(self, data) :       
715        """Returns 1 if data is ESC/P2, else 0."""
716        if data.startswith("\033@") or \
717           data.startswith("\n\033@") :
718            #data.startswith("\033*") or
719            return 1
720        else :   
721            return 0
722   
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)
730        firstblock = self.infile.read(KILOBYTE)
731        self.infile.seek(0)
732        if self.isPostScript(firstblock) :
733            return PostScriptAnalyzer
734        elif self.isPCLXL(firstblock) :   
735            return PCLXLAnalyzer
736        elif self.isPDF(firstblock) :   
737            return PDFAnalyzer
738        elif self.isPCL(firstblock) :   
739            return PCLAnalyzer
740        elif self.isESCP2(firstblock) :   
741            return ESCP2Analyzer
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 :   
756            sys.stderr.write("ERROR: %s\n" % msg)
757            sys.stderr.flush()
758    print "%s" % totalsize
759   
760if __name__ == "__main__" :   
761    main()
Note: See TracBrowser for help on using the browser.