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

Revision 2003, 44.0 kB (checked in by jalet, 19 years ago)

Of course if I forget some files during the commits, the software doesn't
work as expected ;-)

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