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

Revision 1987, 43.5 kB (checked in by jalet, 19 years ago)

Added some debugging code to PCL3/4/5 parser

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