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

Revision 1674, 27.1 kB (checked in by jalet, 20 years ago)

Fixed number of copies in PCL5 parser

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