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

Revision 1675, 27.3 kB (checked in by jalet, 20 years ago)

Fixed index problem in PCLXL parser when retrieving number of copies for
each page

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