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

Revision 1698, 29.8 kB (checked in by jalet, 20 years ago)

One more PCL tag

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