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

Revision 1912, 41.4 kB (checked in by jalet, 20 years ago)

Heavy work done on PCL3/4/5 and PCLXL job analyzis

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