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

Revision 1702, 32.7 kB (checked in by jalet, 20 years ago)

Support for more laserjet models added.

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