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

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

Forgot to remove some special debugging code...

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