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

Revision 1743, 32.8 kB (checked in by jalet, 20 years ago)

Did a pass of PyChecker?

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