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

Revision 1673, 27.0 kB (checked in by jalet, 20 years ago)

Added workaround for number of copies and some PostScript? drivers

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