root / pkpgcounter / trunk / pkpgcounter @ 186

Revision 186, 41.1 kB (checked in by jerome, 19 years ago)

Fixed a syntax error

  • Property svn:executable set to *
Line 
1#! /usr/bin/env python
2#
3# pkpgcounter
4# -*- coding: ISO-8859-15 -*-
5#
6# pkpgcounter : a generic Page Description Language parser
7#
8# (c) 2003,2004,2005 Jerome Alet <alet@librelogiciel.com>
9# This program is free software; you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation; either version 2 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program; if not, write to the Free Software
21# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
22#
23# $Id$
24#
25#
26
27import sys
28import os
29import re
30from struct import unpack
31import tempfile
32import mmap
33import popen2
34   
35__version__ = "1.00"
36
37KILOBYTE = 1024   
38MEGABYTE = 1024 * KILOBYTE   
39LASTBLOCKSIZE = int(KILOBYTE / 4)
40
41class PDLAnalyzerError(Exception):
42    """An exception for PDL Analyzer related stuff."""
43    def __init__(self, message = ""):
44        self.message = message
45        Exception.__init__(self, message)
46    def __repr__(self):
47        return self.message
48    __str__ = __repr__
49   
50class PostScriptAnalyzer :
51    """A class to parse PostScript documents."""
52    def __init__(self, infile, debug=0) :
53        """Initialize PostScript Analyzer."""
54        self.debug = debug
55        self.infile = infile
56        self.copies = 1
57       
58    def throughGhostScript(self) :
59        """Get the count through GhostScript, useful for non-DSC compliant PS files."""
60        if self.debug :
61            sys.stderr.write("Internal parser sucks, using GhostScript instead...\n")
62        self.infile.seek(0)
63        command = 'gs -sDEVICE=bbox -dNOPAUSE -dBATCH -dQUIET - 2>&1 | grep -c "%%HiResBoundingBox:" 2>/dev/null'
64        child = popen2.Popen4(command)
65        try :
66            data = self.infile.read(MEGABYTE)   
67            while data :
68                child.tochild.write(data)
69                data = self.infile.read(MEGABYTE)
70            child.tochild.flush()
71            child.tochild.close()   
72        except (IOError, OSError), msg :   
73            raise PDLAnalyzerError, "Problem during analysis of Binary PostScript document : %s" % msg
74           
75        pagecount = 0
76        try :
77            pagecount = int(child.fromchild.readline().strip())
78        except (IOError, OSError, AttributeError, ValueError), msg :
79            raise PDLAnalyzerError, "Problem during analysis of Binary PostScript document : %s" % msg
80        child.fromchild.close()
81       
82        try :
83            child.wait()
84        except OSError, msg :   
85            raise PDLAnalyzerError, "Problem during analysis of Binary PostScript document : %s" % msg
86        return pagecount * self.copies
87       
88    def natively(self) :
89        """Count pages in a DSC compliant PostScript document."""
90        self.infile.seek(0)
91        pagecount = 0
92        for line in self.infile.xreadlines() : 
93            if line.startswith("%%Page: ") :
94                pagecount += 1
95            elif line.startswith("%%Requirements: numcopies(") :   
96                try :
97                    number = int(line.strip().split('(')[1].split(')')[0])
98                except :     
99                    pass
100                else :   
101                    if number > self.copies :
102                        self.copies = number
103            elif line.startswith("%%BeginNonPPDFeature: NumCopies ") :
104                # handle # of copies set by some Windows printer driver
105                try :
106                    number = int(line.strip().split()[2])
107                except :     
108                    pass
109                else :   
110                    if number > self.copies :
111                        self.copies = number
112            elif line.startswith("1 dict dup /NumCopies ") :
113                # handle # of copies set by mozilla/kprinter
114                try :
115                    number = int(line.strip().split()[4])
116                except :     
117                    pass
118                else :   
119                    if number > self.copies :
120                        self.copies = number
121        return pagecount * self.copies
122       
123    def getJobSize(self) :   
124        """Count pages in PostScript document."""
125        return self.natively() or self.throughGhostScript()
126       
127class PDFAnalyzer :
128    """A class to parse PDF documents."""
129    def __init__(self, infile, debug=0) :
130        """Initialize PDF Analyzer."""
131        self.debug = debug
132        self.infile = infile
133               
134    def getJobSize(self) :   
135        """Counts pages in a PDF document."""
136        regexp = re.compile(r"(/Type) ?(/Page)[/ \t\r\n]")
137        pagecount = 0
138        for line in self.infile.xreadlines() : 
139            pagecount += len(regexp.findall(line))
140        return pagecount   
141       
142class ESCP2Analyzer :
143    """A class to parse ESC/P2 documents."""
144    def __init__(self, infile, debug=0) :
145        """Initialize ESC/P2 Analyzer."""
146        self.debug = debug
147        self.infile = infile
148               
149    def getJobSize(self) :   
150        """Counts pages in an ESC/P2 document."""
151        # with Gimpprint, at least, for each page there
152        # are two Reset Printer sequences (ESC + @)
153        marker1 = "\033@"
154       
155        # with other software or printer driver, we
156        # may prefer to search for "\r\n\fESCAPE"
157        # or "\r\fESCAPE"
158        marker2r = "\r\f\033"
159        marker2rn = "\r\n\f\033"
160       
161        # and ghostscript's stcolor for example seems to
162        # output ESC + @ + \f for each page plus one
163        marker3 = "\033@\f"
164       
165        # while ghostscript's escp driver outputs instead
166        # \f + ESC + @
167        marker4 = "\f\033@"
168       
169        data = self.infile.read()
170        pagecount1 = data.count(marker1)
171        pagecount2 = max(data.count(marker2r), data.count(marker2rn))
172        pagecount3 = data.count(marker3)
173        pagecount4 = data.count(marker4)
174           
175        if pagecount2 :   
176            return pagecount2
177        elif pagecount3 > 1 :     
178            return pagecount3 - 1
179        elif pagecount4 :   
180            return pagecount4
181        else :   
182            return int(pagecount1 / 2)       
183       
184class PCLAnalyzer :
185    """A class to parse PCL3, PCL4, PCL5 documents."""
186    mediasizes = {  # ESC&l####A
187                    0 : "Default",
188                    1 : "Executive",
189                    2 : "Letter",
190                    3 : "Legal",
191                    6 : "Ledger", 
192                    25 : "A5",
193                    26 : "A4",
194                    27 : "A3",
195                    45 : "JB5",
196                    46 : "JB4",
197                    71 : "HagakiPostcard",
198                    72 : "OufukuHagakiPostcard",
199                    80 : "MonarchEnvelope",
200                    81 : "COM10Envelope",
201                    90 : "DLEnvelope",
202                    91 : "C5Envelope",
203                    100 : "B5Envelope",
204                    101 : "Custom",
205                 }   
206                 
207    mediasources = { # ESC&l####H
208                     0 : "Default",
209                     1 : "Main",
210                     2 : "Manual",
211                     3 : "ManualEnvelope",
212                     4 : "Alternate",
213                     5 : "OptionalLarge",
214                     6 : "EnvelopeFeeder",
215                     7 : "Auto",
216                     8 : "Tray1",
217                   }
218                   
219    orientations = { # ESC&l####O
220                     0 : "Portrait",
221                     1 : "Landscape",
222                     2 : "ReversePortrait",
223                     3 : "ReverseLandscape",
224                   }
225                   
226    mediatypes = { # ESC&l####M
227                     0 : "Plain",
228                     1 : "Bond",
229                     2 : "Special",
230                     3 : "Glossy",
231                     4 : "Transparent",
232                   }
233                   
234                   
235    def __init__(self, infile, debug=0) :
236        """Initialize PCL Analyzer."""
237        self.debug = debug
238        self.infile = infile
239       
240    def setPageDict(self, pages, number, attribute, value) :
241        """Initializes a page dictionnary."""
242        dict = pages.setdefault(number, { "copies" : 1, "mediasource" : "Main", "mediasize" : "Default", "mediatype" : "Plain", "orientation" : "Portrait"})
243        dict[attribute] = value
244       
245    def getJobSize(self) :     
246        """Count pages in a PCL5 document.
247         
248           Should also work for PCL3 and PCL4 documents.
249           
250           Algorithm from pclcount
251           (c) 2003, by Eduardo Gielamo Oliveira & Rodolfo Broco Manin
252           published under the terms of the GNU General Public Licence v2.
253         
254           Backported from C to Python by Jerome Alet, then enhanced
255           with more PCL tags detected. I think all the necessary PCL tags
256           are recognized to correctly handle PCL5 files wrt their number
257           of pages. The documentation used for this was :
258         
259           HP PCL/PJL Reference Set
260           PCL5 Printer Language Technical Quick Reference Guide
261           http://h20000.www2.hp.com/bc/docs/support/SupportManual/bpl13205/bpl13205.pdf
262        """
263        infileno = self.infile.fileno()
264        minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
265        tagsends = { "&n" : "W", 
266                     "&b" : "W", 
267                     "*i" : "W", 
268                     "*l" : "W", 
269                     "*m" : "W", 
270                     "*v" : "W", 
271                     "*c" : "W", 
272                     "(f" : "W", 
273                     "(s" : "W", 
274                     ")s" : "W", 
275                     "&p" : "X", 
276                     # "&l" : "XHAOM",  # treated specially
277                     "&a" : "G", # TODO : 0 means next side, 1 front side, 2 back side
278                     "*g" : "W",
279                     "*r" : "sbABC",
280                     "*t" : "R",
281                     # "*b" : "VW", # treated specially because it occurs very often
282                   } 
283        pagecount = resets = ejects = backsides = startgfx = endgfx = 0
284        starb = ampl = ispcl3 = escstart = 0
285        mediasourcecount = mediasizecount = orientationcount = mediatypecount = 0
286        tag = None
287        pages = {}
288        pos = 0
289        try :
290            while 1 :
291                char = minfile[pos] ; pos += 1
292                if char == "\014" :   
293                    pagecount += 1
294                elif char == "\033" :   
295                    starb = ampl = 0
296                    #
297                    #     <ESC>*b###y#m###v###w... -> PCL3 raster graphics
298                    #     <ESC>*b###W -> Start of a raster data row/block
299                    #     <ESC>*b###V -> Start of a raster data plane
300                    #     <ESC>*c###W -> Start of a user defined pattern
301                    #     <ESC>*i###W -> Start of a viewing illuminant block
302                    #     <ESC>*l###W -> Start of a color lookup table
303                    #     <ESC>*m###W -> Start of a download dither matrix block
304                    #     <ESC>*v###W -> Start of a configure image data block
305                    #     <ESC>*r1A -> Start Gfx
306                    #     <ESC>(s###W -> Start of a characters description block
307                    #     <ESC>)s###W -> Start of a fonts description block
308                    #     <ESC>(f###W -> Start of a symbol set block
309                    #     <ESC>&b###W -> Start of configuration data block
310                    #     <ESC>&l###X -> Number of copies for current page
311                    #     <ESC>&n###W -> Starts an alphanumeric string ID block
312                    #     <ESC>&p###X -> Start of a non printable characters block
313                    #     <ESC>&a2G -> Back side when duplex mode as generated by rastertohp
314                    #     <ESC>*g###W -> Needed for planes in PCL3 output
315                    #     <ESC>&l###H (or only 0 ?) -> Eject if NumPlanes > 1, as generated by rastertohp. Also defines mediasource
316                    #     <ESC>&l###A -> mediasize
317                    #     <ESC>&l###O -> orientation
318                    #     <ESC>&l###M -> mediatype
319                    #     <ESC>*t###R -> gfx resolution
320                    #
321                    tagstart = minfile[pos] ; pos += 1
322                    if tagstart in "E9=YZ" : # one byte PCL tag
323                        if tagstart == "E" :
324                            resets += 1
325                        continue             # skip to next tag
326                    tag = tagstart + minfile[pos] ; pos += 1
327                    if tag == "*b" : 
328                        starb = 1
329                        tagend = "VW"
330                    elif tag == "&l" :   
331                        ampl = 1
332                        tagend = "XHAOM"
333                    else :   
334                        try :
335                            tagend = tagsends[tag]
336                        except KeyError :   
337                            continue # Unsupported PCL tag
338                    # Now read the numeric argument
339                    size = 0
340                    while 1 :
341                        char = minfile[pos] ; pos += 1
342                        if not char.isdigit() :
343                            break
344                        size = (size * 10) + int(char)   
345                    if char in tagend :   
346                        if tag == "&l" :
347                            if char == "X" : 
348                                self.setPageDict(pages, pagecount, "copies", size)
349                            elif char == "H" :
350                                self.setPageDict(pages, pagecount, "mediasource", self.mediasources.get(size, str(size)))
351                                mediasourcecount += 1
352                                ejects += 1 
353                            elif char == "A" :
354                                self.setPageDict(pages, pagecount, "mediasize", self.mediasizes.get(size, str(size)))
355                                mediasizecount += 1
356                            elif char == "O" :
357                                self.setPageDict(pages, pagecount, "orientation", self.orientations.get(size, str(size)))
358                                orientationcount += 1
359                            elif char == "M" :
360                                self.setPageDict(pages, pagecount, "mediatype", self.mediatypes.get(size, str(size)))
361                                mediatypecount += 1
362                        elif tag == "*r" :
363                            # Special tests for PCL3
364                            if (char == "s") and size :
365                                while 1 :
366                                    char = minfile[pos] ; pos += 1
367                                    if char == "A" :
368                                        break
369                            elif (char == "b") and (minfile[pos] == "C") and not size :
370                                ispcl3 = 1 # Certainely a PCL3 file
371                            startgfx += (char == "A") and (minfile[pos - 2] in ("0", "1", "2", "3")) # Start Gfx
372                            endgfx += (not size) and (char in ("C", "B")) # End Gfx
373                        elif tag == "*t" :   
374                            escstart += 1
375                        elif (tag == "&a") and (size == 2) :
376                            backsides += 1      # Back side in duplex mode
377                        else :   
378                            # we just ignore the block.
379                            if tag == "&n" : 
380                                # we have to take care of the operation id byte
381                                # which is before the string itself
382                                size += 1
383                            pos += size   
384                else :                           
385                    if starb :
386                        # special handling of PCL3 in which
387                        # *b introduces combined ESCape sequences
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 ("w", "v") :   
395                            ispcl3 = 1  # certainely a PCL3 document
396                            pos += size - 1
397                        elif char in ("y", "m") :   
398                            ispcl3 = 1  # certainely a PCL3 document
399                            pos -= 1    # fix position : we were ahead
400                    elif ampl :       
401                        # special handling of PCL3 in which
402                        # &l introduces combined ESCape sequences
403                        size = 0
404                        while 1 :
405                            char = minfile[pos] ; pos += 1
406                            if not char.isdigit() :
407                                break
408                            size = (size * 10) + int(char)   
409                        if char in ("a", "o", "h", "m") :   
410                            ispcl3 = 1  # certainely a PCL3 document
411                            pos -= 1    # fix position : we were ahead
412                            if char == "h" :
413                                self.setPageDict(pages, pagecount, "mediasource", self.mediasources.get(size, str(size)))
414                                mediasourcecount += 1
415                            elif char == "a" :
416                                self.setPageDict(pages, pagecount, "mediasize", self.mediasizes.get(size, str(size)))
417                                mediasizecount += 1
418                            elif char == "o" :
419                                self.setPageDict(pages, pagecount, "orientation", self.orientations.get(size, str(size)))
420                                orientationcount += 1
421                            elif char == "m" :
422                                self.setPageDict(pages, pagecount, "mediatype", self.mediatypes.get(size, str(size)))
423                                mediatypecount += 1
424        except IndexError : # EOF ?
425            minfile.close() # reached EOF
426                           
427        # if pagecount is still 0, we will use the number
428        # of resets instead of the number of form feed characters.
429        # but the number of resets is always at least 2 with a valid
430        # pcl file : one at the very start and one at the very end
431        # of the job's data. So we substract 2 from the number of
432        # resets. And since on our test data we needed to substract
433        # 1 more, we finally substract 3, and will test several
434        # PCL files with this. If resets < 2, then the file is
435        # probably not a valid PCL file, so we use 0
436       
437        if self.debug :
438            sys.stderr.write("pagecount : %s\n" % pagecount)
439            sys.stderr.write("resets : %s\n" % resets)
440            sys.stderr.write("ejects : %s\n" % ejects)
441            sys.stderr.write("backsides : %s\n" % backsides)
442            sys.stderr.write("startgfx : %s\n" % startgfx)
443            sys.stderr.write("endgfx : %s\n" % endgfx)
444            sys.stderr.write("mediasourcecount : %s\n" % mediasourcecount)
445            sys.stderr.write("mediasizecount : %s\n" % mediasizecount)
446            sys.stderr.write("orientationcount : %s\n" % orientationcount)
447            sys.stderr.write("mediatypecount : %s\n" % mediatypecount)
448            sys.stderr.write("escstart : %s\n" % escstart)
449       
450#        if not pagecount :
451#            pagecount = (pagecount or ((resets - 3) * (resets > 2)))
452#        else :   
453#            # here we add counters for other ways new pages may have
454#            # been printed and ejected by the printer
455#            pagecount += ejects + backsides
456#       
457#        # now handle number of copies for each page (may differ).
458#        # in duplex mode, number of copies may be sent only once.
459#        for pnum in range(pagecount) :
460#            # if no number of copies defined, take the preceding one else the one set before any page else 1.
461#            page = pages.get(pnum, pages.get(pnum - 1, pages.get(0, { "copies" : 1 })))
462#            pagecount += (page["copies"] - 1)
463#           
464#        # in PCL3 files, there's one Start Gfx tag per page
465#        if ispcl3 :
466#            if endgfx == int(startgfx / 2) : # special case for cdj1600
467#                pagecount = endgfx
468#            elif startgfx :
469#                pagecount = startgfx
470#            elif endgfx :   
471#                pagecount = endgfx
472               
473           
474        if pagecount == mediasourcecount == escstart : 
475            pass        # should be OK.
476        elif (not startgfx) and (not endgfx) :
477            pagecount = ejects or pagecount
478        elif startgfx == endgfx :   
479            pagecount = startgfx
480        elif startgfx == (endgfx - 1) :   
481            pagecount = startgfx
482        else :   
483            pagecount = abs(startgfx - endgfx)
484           
485        if self.debug :       
486            for pnum in range(pagecount) :
487                # if no number of copies defined, take the preceding one else the one set before any page else 1.
488                page = pages.get(pnum, pages.get(pnum - 1, pages.get(0, { "copies" : 1, "mediasource" : "Main", "mediasize" : "Default", "mediatype" : "Plain", "orientation" : "Portrait"})))
489                sys.stderr.write("%s*%s*%s*%s*%s\n" % (page["copies"], page["mediatype"], page["mediasize"], page["orientation"], page["mediasource"]))
490               
491        return pagecount
492       
493class PCLXLAnalyzer :
494    """A class to parse PCL6 (aka XL) documents."""
495    mediasizes = { 
496                    0 : "Letter",
497                    1 : "Legal",
498                    2 : "A4",
499                    3 : "Executive",
500                    4 : "Ledger",
501                    5 : "A3",
502                    6 : "COM10Envelope",
503                    7 : "MonarchEnvelope",
504                    8 : "C5Envelope",
505                    9 : "DLEnvelope",
506                    10 : "JB4",
507                    11 : "JB5",
508                    12 : "B5Envelope",
509                    14 : "JPostcard",
510                    15 : "JDoublePostcard",
511                    16 : "A5",
512                    17 : "A6",
513                    18 : "JB6",
514                 }   
515                 
516    mediasources = {             
517                     0 : "Default",
518                     1 : "Auto",
519                     2 : "Manual",
520                     3 : "MultiPurpose",
521                     4 : "UpperCassette",
522                     5 : "LowerCassette",
523                     6 : "EnvelopeTray",
524                     7 : "ThirdCassette",
525                   }
526                   
527    orientations = {               
528                     0 : "Portrait",
529                     1 : "Landscape",
530                     2 : "ReversePortrait",
531                     3 : "ReverseLandscape",
532                   }
533                   
534    def __init__(self, infile, debug=0) :
535        """Initialize PCLXL Analyzer."""
536        self.debug = debug
537        self.infile = infile
538        self.endianness = None
539        found = 0
540        while not found :
541            line = self.infile.readline()
542            if not line :
543                break
544            if line[1:12] == " HP-PCL XL;" :
545                found = 1
546                endian = ord(line[0])
547                if endian == 0x29 :
548                    self.littleEndian()
549                elif endian == 0x28 :   
550                    self.bigEndian()
551                # elif endian == 0x27 : # TODO : This is the ESC code : parse it for PJL statements !
552                #
553                else :   
554                    raise PDLAnalyzerError, "Unknown endianness marker 0x%02x at start !" % endian
555        if not found :
556            raise PDLAnalyzerError, "This file doesn't seem to be PCLXL (aka PCL6)"
557        else :   
558            # Initialize table of tags
559            self.tags = [ 0 ] * 256   
560           
561            # GhostScript's sources tell us that HP printers
562            # only accept little endianness, but we can handle both.
563            self.tags[0x28] = self.bigEndian    # BigEndian
564            self.tags[0x29] = self.littleEndian # LittleEndian
565           
566            self.tags[0x43] = self.beginPage    # BeginPage
567            self.tags[0x44] = self.endPage      # EndPage
568           
569            self.tags[0xc0] = 1 # ubyte
570            self.tags[0xc1] = 2 # uint16
571            self.tags[0xc2] = 4 # uint32
572            self.tags[0xc3] = 2 # sint16
573            self.tags[0xc4] = 4 # sint32
574            self.tags[0xc5] = 4 # real32
575           
576            self.tags[0xc8] = self.array_8  # ubyte_array
577            self.tags[0xc9] = self.array_16 # uint16_array
578            self.tags[0xca] = self.array_32 # uint32_array
579            self.tags[0xcb] = self.array_16 # sint16_array
580            self.tags[0xcc] = self.array_32 # sint32_array
581            self.tags[0xcd] = self.array_32 # real32_array
582           
583            self.tags[0xd0] = 2 # ubyte_xy
584            self.tags[0xd1] = 4 # uint16_xy
585            self.tags[0xd2] = 8 # uint32_xy
586            self.tags[0xd3] = 4 # sint16_xy
587            self.tags[0xd4] = 8 # sint32_xy
588            self.tags[0xd5] = 8 # real32_xy
589           
590            self.tags[0xe0] = 4  # ubyte_box
591            self.tags[0xe1] = 8  # uint16_box
592            self.tags[0xe2] = 16 # uint32_box
593            self.tags[0xe3] = 8  # sint16_box
594            self.tags[0xe4] = 16 # sint32_box
595            self.tags[0xe5] = 16 # real32_box
596           
597            self.tags[0xf8] = 1 # attr_ubyte
598            self.tags[0xf9] = 2 # attr_uint16
599           
600            self.tags[0xfa] = self.embeddedData      # dataLength
601            self.tags[0xfb] = self.embeddedDataSmall # dataLengthByte
602           
603    def beginPage(self) :
604        """Indicates the beginning of a new page, and extracts media information."""
605        self.pagecount += 1
606       
607        # Default values
608        mediatypelabel = "Plain"
609        mediasourcelabel = "Main"
610        mediasizelabel = "Default"
611        orientationlabel = "Portrait"
612       
613        # Now go upstream to decode media type, size, source, and orientation
614        # this saves time because we don't need a complete parser !
615        minfile = self.minfile
616        pos = self.pos - 2
617        while pos > 0 : # safety check : don't go back to far !
618            val = ord(minfile[pos])
619            if val in (0x44, 0x48, 0x41) : # if previous endPage or openDataSource or beginSession (first page)
620                break
621            if val == 0x26 :   
622                mediasource = ord(minfile[pos - 2])
623                mediasourcelabel = self.mediasources.get(mediasource, str(mediasource))
624                pos = pos - 4
625            elif val == 0x25 :
626                mediasize = ord(minfile[pos - 2])
627                mediasizelabel = self.mediasizes.get(mediasize, str(mediasize))
628                pos = pos - 4
629            elif val == 0x28 :   
630                orientation = ord(minfile[pos - 2])
631                orienationlabel = self.orientations.get(orientation, str(orientation))
632                pos = pos - 4
633            elif val == 0x27 :   
634                savepos = pos
635                pos = pos - 1
636                while pos > 0 : # safety check : don't go back to far !
637                    val = ord(minfile[pos])
638                    pos -= 1   
639                    if val == 0xc8 :
640                        break
641                mediatypelabel = minfile[pos:savepos] # TODO : INCORRECT, WE HAVE TO STRIP OUT THE UBYTE ARRAY'S LENGTH !!!
642            # else : TODO : CUSTOM MEDIA SIZE AND UNIT !
643            else :   
644                pos = pos - 2   # ignored
645        self.pages[self.pagecount] = { "copies" : 1, 
646                                       "orientation" : orientationlabel, 
647                                       "mediatype" : mediatypelabel, 
648                                       "mediasize" : mediasizelabel,
649                                       "mediasource" : mediasourcelabel,
650                                     } 
651        return 0
652       
653    def endPage(self) :   
654        """Indicates the end of a page."""
655        pos = self.pos
656        minfile = self.minfile
657        if (ord(minfile[pos-3]) == 0xf8) and (ord(minfile[pos-2]) == 0x31) :
658            # The EndPage operator may be preceded by a PageCopies attribute
659            # So set number of copies for current page.
660            # From what I read in PCLXL documentation, the number
661            # of copies is an unsigned 16 bits integer
662            self.pages[self.pagecount]["copies"] = unpack(self.endianness + "H", minfile[pos-5:pos-3])[0]
663        return 0
664       
665    def array_8(self) :   
666        """Handles byte arrays."""
667        pos = self.pos
668        datatype = self.minfile[pos]
669        pos += 1
670        length = self.tags[ord(datatype)]
671        if callable(length) :
672            self.pos = pos
673            length = length()
674            pos = self.pos
675        posl = pos + length
676        self.pos = posl
677        if length == 1 :   
678            return unpack("B", self.minfile[pos:posl])[0]
679        elif length == 2 :   
680            return unpack(self.endianness + "H", self.minfile[pos:posl])[0]
681        elif length == 4 :   
682            return unpack(self.endianness + "I", self.minfile[pos:posl])[0]
683        else :   
684            raise PDLAnalyzerError, "Error on array size at %s" % self.pos
685       
686    def array_16(self) :   
687        """Handles byte arrays."""
688        pos = self.pos
689        datatype = self.minfile[pos]
690        pos += 1
691        length = self.tags[ord(datatype)]
692        if callable(length) :
693            self.pos = pos
694            length = length()
695            pos = self.pos
696        posl = pos + length
697        self.pos = posl
698        if length == 1 :   
699            return 2 * unpack("B", self.minfile[pos:posl])[0]
700        elif length == 2 :   
701            return 2 * unpack(self.endianness + "H", self.minfile[pos:posl])[0]
702        elif length == 4 :   
703            return 2 * unpack(self.endianness + "I", self.minfile[pos:posl])[0]
704        else :   
705            raise PDLAnalyzerError, "Error on array size at %s" % self.pos
706       
707    def array_32(self) :   
708        """Handles byte arrays."""
709        pos = self.pos
710        datatype = self.minfile[pos]
711        pos += 1
712        length = self.tags[ord(datatype)]
713        if callable(length) :
714            self.pos = pos
715            length = length()
716            pos = self.pos
717        posl = pos + length
718        self.pos = posl
719        if length == 1 :   
720            return 4 * unpack("B", self.minfile[pos:posl])[0]
721        elif length == 2 :   
722            return 4 * unpack(self.endianness + "H", self.minfile[pos:posl])[0]
723        elif length == 4 :   
724            return 4 * unpack(self.endianness + "I", self.minfile[pos:posl])[0]
725        else :   
726            raise PDLAnalyzerError, "Error on array size at %s" % self.pos
727       
728    def embeddedDataSmall(self) :
729        """Handle small amounts of data."""
730        pos = self.pos
731        length = ord(self.minfile[pos])
732        self.pos = pos + 1
733        return length
734       
735    def embeddedData(self) :
736        """Handle normal amounts of data."""
737        pos = self.pos
738        pos4 = pos + 4
739        self.pos = pos4
740        return unpack(self.endianness + "I", self.minfile[pos:pos4])[0]
741       
742    def littleEndian(self) :       
743        """Toggles to little endianness."""
744        self.endianness = "<" # little endian
745        return 0
746       
747    def bigEndian(self) :   
748        """Toggles to big endianness."""
749        self.endianness = ">" # big endian
750        return 0
751   
752    def getJobSize(self) :
753        """Counts pages in a PCLXL (PCL6) document.
754       
755           Algorithm by Jerome Alet.
756           
757           The documentation used for this was :
758         
759           HP PCL XL Feature Reference
760           Protocol Class 2.0
761           http://www.hpdevelopersolutions.com/downloads/64/358/xl_ref20r22.pdf
762        """
763        infileno = self.infile.fileno()
764        self.pages = {}
765        self.minfile = minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
766        tags = self.tags
767        self.pagecount = 0
768        self.pos = pos = self.infile.tell()
769        try :
770            while 1 :
771                char = minfile[pos]
772                pos += 1
773                length = tags[ord(char)]
774                if not length :
775                    continue
776                if callable(length) :   
777                    self.pos = pos
778                    length = length()
779                    pos = self.pos
780                pos += length   
781        except IndexError : # EOF ?
782            self.minfile.close() # reached EOF
783           
784        # now handle number of copies for each page (may differ).
785        for pnum in range(1, self.pagecount + 1) :
786            # if no number of copies defined, take 1, as explained
787            # in PCLXL documentation.
788            # NB : is number of copies is 0, the page won't be output
789            # but the formula below is still correct : we want
790            # to decrease the total number of pages in this case.
791            page = self.pages.get(pnum, 1)
792            copies = page["copies"]
793            self.pagecount += (copies - 1)
794            if self.debug :
795                sys.stderr.write("%s*%s*%s*%s*%s\n" % (copies, page["mediatype"], page["mediasize"], page["orientation"], page["mediasource"]))
796           
797        return self.pagecount
798       
799class PDLAnalyzer :   
800    """Generic PDL Analyzer class."""
801    def __init__(self, filename, debug=0) :
802        """Initializes the PDL analyzer.
803       
804           filename is the name of the file or '-' for stdin.
805           filename can also be a file-like object which
806           supports read() and seek().
807        """
808        self.debug = debug
809        self.filename = filename
810        try :
811            import psyco 
812        except ImportError :   
813            sys.stderr.write("pkpgcounter : you should install psyco if possible, this would greatly speedup parsing.\n")
814            pass # Psyco is not installed
815        else :   
816            # Psyco is installed, tell it to compile
817            # the CPU intensive methods : PCL and PCLXL
818            # parsing will greatly benefit from this,
819            # for PostScript and PDF the difference is
820            # barely noticeable since they are already
821            # almost optimal, and much more speedy anyway.
822            psyco.bind(PostScriptAnalyzer.getJobSize)
823            psyco.bind(PDFAnalyzer.getJobSize)
824            psyco.bind(ESCP2Analyzer.getJobSize)
825            psyco.bind(PCLAnalyzer.getJobSize)
826            psyco.bind(PCLXLAnalyzer.getJobSize)
827       
828    def getJobSize(self) :   
829        """Returns the job's size."""
830        self.openFile()
831        try :
832            pdlhandler = self.detectPDLHandler()
833        except PDLAnalyzerError, msg :   
834            self.closeFile()
835            raise PDLAnalyzerError, "ERROR : Unknown file format for %s (%s)" % (self.filename, msg)
836        else :
837            try :
838                size = pdlhandler(self.infile, self.debug).getJobSize()
839            finally :   
840                self.closeFile()
841            return size
842       
843    def openFile(self) :   
844        """Opens the job's data stream for reading."""
845        self.mustclose = 0  # by default we don't want to close the file when finished
846        if hasattr(self.filename, "read") and hasattr(self.filename, "seek") :
847            # filename is in fact a file-like object
848            infile = self.filename
849        elif self.filename == "-" :
850            # we must read from stdin
851            infile = sys.stdin
852        else :   
853            # normal file
854            self.infile = open(self.filename, "rb")
855            self.mustclose = 1
856            return
857           
858        # Use a temporary file, always seekable contrary to standard input.
859        self.infile = tempfile.TemporaryFile(mode="w+b")
860        while 1 :
861            data = infile.read(MEGABYTE) 
862            if not data :
863                break
864            self.infile.write(data)
865        self.infile.flush()   
866        self.infile.seek(0)
867           
868    def closeFile(self) :       
869        """Closes the job's data stream if we can close it."""
870        if self.mustclose :
871            self.infile.close()   
872        else :   
873            # if we don't have to close the file, then
874            # ensure the file pointer is reset to the
875            # start of the file in case the process wants
876            # to read the file again.
877            try :
878                self.infile.seek(0)
879            except :   
880                pass    # probably stdin, which is not seekable
881       
882    def isPostScript(self, sdata, edata) :   
883        """Returns 1 if data is PostScript, else 0."""
884        if sdata.startswith("%!") or \
885           sdata.startswith("\004%!") or \
886           sdata.startswith("\033%-12345X%!PS") or \
887           ((sdata[:128].find("\033%-12345X") != -1) and \
888             ((sdata.find("LANGUAGE=POSTSCRIPT") != -1) or \
889              (sdata.find("LANGUAGE = POSTSCRIPT") != -1) or \
890              (sdata.find("LANGUAGE = Postscript") != -1))) or \
891              (sdata.find("%!PS-Adobe") != -1) :
892            if self.debug : 
893                sys.stderr.write("%s is a PostScript file\n" % str(self.filename))
894            return 1
895        else :   
896            return 0
897       
898    def isPDF(self, sdata, edata) :   
899        """Returns 1 if data is PDF, else 0."""
900        if sdata.startswith("%PDF-") or \
901           sdata.startswith("\033%-12345X%PDF-") or \
902           ((sdata[:128].find("\033%-12345X") != -1) and (sdata.upper().find("LANGUAGE=PDF") != -1)) or \
903           (sdata.find("%PDF-") != -1) :
904            if self.debug : 
905                sys.stderr.write("%s is a PDF file\n" % str(self.filename))
906            return 1
907        else :   
908            return 0
909       
910    def isPCL(self, sdata, edata) :   
911        """Returns 1 if data is PCL, else 0."""
912        if sdata.startswith("\033E\033") or \
913           (sdata.startswith("\033*rbC") and (not edata[-3:] == "\f\033@")) or \
914           sdata.startswith("\033%8\033") or \
915           (sdata.find("\033%-12345X") != -1) :
916            if self.debug : 
917                sys.stderr.write("%s is a PCL3/4/5 file\n" % str(self.filename))
918            return 1
919        else :   
920            return 0
921       
922    def isPCLXL(self, sdata, edata) :   
923        """Returns 1 if data is PCLXL aka PCL6, else 0."""
924        if ((sdata[:128].find("\033%-12345X") != -1) and \
925             (sdata.find(" HP-PCL XL;") != -1) and \
926             ((sdata.find("LANGUAGE=PCLXL") != -1) or \
927              (sdata.find("LANGUAGE = PCLXL") != -1))) :
928            if self.debug : 
929                sys.stderr.write("%s is a PCLXL (aka PCL6) file\n" % str(self.filename))
930            return 1
931        else :   
932            return 0
933           
934    def isESCP2(self, sdata, edata) :       
935        """Returns 1 if data is ESC/P2, else 0."""
936        if sdata.startswith("\033@") or \
937           sdata.startswith("\033*") or \
938           sdata.startswith("\n\033@") or \
939           sdata.startswith("\0\0\0\033\1@EJL") : # ESC/P Raster ??? Seen on Stylus Photo 1284
940            if self.debug : 
941                sys.stderr.write("%s is an ESC/P2 file\n" % str(self.filename))
942            return 1
943        else :   
944            return 0
945   
946    def detectPDLHandler(self) :   
947        """Tries to autodetect the document format.
948       
949           Returns the correct PDL handler class or None if format is unknown
950        """   
951        # Try to detect file type by reading first block of datas   
952        self.infile.seek(0)
953        firstblock = self.infile.read(4 * KILOBYTE)
954        try :
955            self.infile.seek(-LASTBLOCKSIZE, 2)
956            lastblock = self.infile.read(LASTBLOCKSIZE)
957        except IOError :   
958            lastblock = ""
959           
960        self.infile.seek(0)
961        if self.isPostScript(firstblock, lastblock) :
962            return PostScriptAnalyzer
963        elif self.isPCLXL(firstblock, lastblock) :   
964            return PCLXLAnalyzer
965        elif self.isPDF(firstblock, lastblock) :   
966            return PDFAnalyzer
967        elif self.isPCL(firstblock, lastblock) :   
968            return PCLAnalyzer
969        elif self.isESCP2(firstblock, lastblock) :   
970            return ESCP2Analyzer
971        else :   
972            raise PDLAnalyzerError, "Analysis of first data block failed."
973           
974def main() :   
975    """Entry point for PDL Analyzer."""
976    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
977        sys.argv.append("-")
978       
979    if ("-h" in sys.argv[1:]) or ("--help" in sys.argv[1:]) :
980        print "usage : pkpgcounter file1 file2 ... fileN"
981    elif ("-v" in sys.argv[1:]) or ("--version" in sys.argv[1:]) :
982        print "%s" % __version__
983    else :
984        totalsize = 0   
985        debug = 0
986        minindex = 1
987        if sys.argv[1] == "--debug" :
988            minindex = 2
989            debug = 1
990        for arg in sys.argv[minindex:] :
991            try :
992                parser = PDLAnalyzer(arg, debug)
993                totalsize += parser.getJobSize()
994            except PDLAnalyzerError, msg :   
995                sys.stderr.write("ERROR: %s\n" % msg)
996                sys.stderr.flush()
997        print "%s" % totalsize
998   
999if __name__ == "__main__" :   
1000    main()
Note: See TracBrowser for help on using the browser.