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

Revision 1677, 28.3 kB (checked in by jalet, 20 years ago)

Improved ESC/P2 miniparser thanks to Paulo Silva

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