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

Revision 1686, 29.7 kB (checked in by jalet, 20 years ago)

Improved the ESC/P2 analyzer so that more GhostScript? devices are supported

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