root / pkpgcounter / trunk / pkpgpdls / newpcl345.py @ 396

Revision 396, 18.7 kB (checked in by jerome, 18 years ago)

Much improved parser, now skips HPGL2.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
Line 
1#! /usr/bin/env python
2# -*- coding: ISO-8859-15 -*-
3#
4# pkpgcounter : a generic Page Description Language parser
5#
6# (c) 2003, 2004, 2005, 2006 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20#
21# $Id$
22#
23
24"""This modules implements a page counter for PCL3/4/5 documents."""
25
26import sys
27import os
28import mmap
29from struct import unpack
30
31import pdlparser
32import pjl
33
34NUL = chr(0x00)
35FORMFEED = chr(0x0c)
36ESCAPE = chr(0x1b)
37ASCIILIMIT = chr(0x80)
38
39class Parser(pdlparser.PDLParser) :
40    """A parser for PCL3, PCL4, PCL5 documents."""
41    totiffcommand = 'pcl6 -sDEVICE=pdfwrite -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -sOutputFile=- - | gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r%(dpi)i -sOutputFile="%(fname)s" -'
42    mediasizes = {  # ESC&l####A
43                    0 : "Default",
44                    1 : "Executive",
45                    2 : "Letter",
46                    3 : "Legal",
47                    6 : "Ledger", 
48                    25 : "A5",
49                    26 : "A4",
50                    27 : "A3",
51                    45 : "JB5",
52                    46 : "JB4",
53                    71 : "HagakiPostcard",
54                    72 : "OufukuHagakiPostcard",
55                    80 : "MonarchEnvelope",
56                    81 : "COM10Envelope",
57                    90 : "DLEnvelope",
58                    91 : "C5Envelope",
59                    100 : "B5Envelope",
60                    101 : "Custom",
61                 }   
62                 
63    mediasources = { # ESC&l####H
64                     0 : "Default",
65                     1 : "Main",
66                     2 : "Manual",
67                     3 : "ManualEnvelope",
68                     4 : "Alternate",
69                     5 : "OptionalLarge",
70                     6 : "EnvelopeFeeder",
71                     7 : "Auto",
72                     8 : "Tray1",
73                   }
74                   
75    orientations = { # ESC&l####O
76                     0 : "Portrait",
77                     1 : "Landscape",
78                     2 : "ReversePortrait",
79                     3 : "ReverseLandscape",
80                   }
81                   
82    mediatypes = { # ESC&l####M
83                     0 : "Plain",
84                     1 : "Bond",
85                     2 : "Special",
86                     3 : "Glossy",
87                     4 : "Transparent",
88                   }
89       
90    def isValid(self) :   
91        """Returns True if data is PCL3/4/5, else False."""
92        if self.firstblock.startswith("\033E\033") or \
93           (self.firstblock.startswith("\033*rbC") and (not self.lastblock[-3:] == "\f\033@")) or \
94           self.firstblock.startswith("\033%8\033") or \
95           (self.firstblock.find("\033%-12345X") != -1) or \
96           (self.firstblock.find("@PJL ENTER LANGUAGE=PCL\012\015\033") != -1) or \
97           (self.firstblock.startswith(chr(0xcd)+chr(0xca)) and self.firstblock.find("\033E\033")) :
98            self.logdebug("DEBUG: Input file is in the PCL3/4/5 format.")
99            return True
100        else :   
101            return False
102       
103    def setPageDict(self, attribute, value) :
104        """Initializes a page dictionnary."""
105        dic = self.pages.setdefault(self.pagecount, { "copies" : 1, "mediasource" : "Main", "mediasize" : "Default", "mediatype" : "Plain", "orientation" : "Portrait", "escaped" : "", "duplex": 0})
106        dic[attribute] = value
107       
108    def readByte(self) :   
109        """Reads a byte from the input stream."""
110        tag = ord(self.minfile[self.pos])
111        if tag == 0x0c :
112            self.logdebug("%08x ====> %02x %02x %02x %02x" %
113                 (self.pos,
114                 ord(self.minfile[self.pos-2]),
115                 ord(self.minfile[self.pos-1]),
116                 ord(self.minfile[self.pos-0]),
117                 ord(self.minfile[self.pos+1])))
118        self.pos += 1
119        return tag
120       
121    def endPage(self) :   
122        """Handle the FF marker."""
123        self.logdebug("FORMFEED %i at %08x" % (self.pagecount, self.pos-1))
124        self.pagecount += 1
125       
126    def escPercent(self) :   
127        """Handles the ESC% sequence."""
128        if self.minfile[self.pos : self.pos+7] == r"-12345X" :
129            #self.logdebug("Generic ESCAPE sequence at %08x" % self.pos)
130            self.pos += 7
131            buffer = []
132            quotes = 0
133            char = chr(self.readByte())
134            while ((char < ASCIILIMIT) or (quotes % 2)) and (char not in (FORMFEED, ESCAPE, NUL)) : 
135                buffer.append(char)
136                if char == '"' :
137                    quotes += 1
138                char = chr(self.readByte())
139            self.setPageDict("escaped", "".join(buffer))
140            #self.logdebug("ESCAPED : %s" % "".join(buffer))
141            self.pos -= 1   # Adjust position
142        else :   
143            while 1 :
144                (value, end) = self.getInteger()
145                if end == 'B' :
146                    self.enterHPGL2()
147                    while self.minfile[self.pos] != ESCAPE :
148                        self.pos += 1
149                    self.pos -= 1   
150                    return 
151                elif end == 'A' :   
152                    self.exitHPGL2()
153                    return
154       
155    def enterHPGL2(self) :   
156        """Enters HPGL2 mode."""
157        self.logdebug("ENTERHPGL2 %08x" % self.pos)
158        self.hpgl2 = True
159       
160    def exitHPGL2(self) :   
161        """Exits HPGL2 mode."""
162        self.logdebug("EXITHPGL2 %08x" % self.pos)
163        self.hpgl2 = False
164       
165    def handleTag(self, tagtable) :   
166        """Handles tags."""
167        tagtable[self.readByte()]()
168       
169    def escape(self) :   
170        """Handles the ESC character."""
171        #self.logdebug("ESCAPE")
172        self.handleTag(self.esctags)
173       
174    def escAmp(self) :   
175        """Handles the ESC& sequence."""
176        #self.logdebug("AMP")
177        self.handleTag(self.escamptags)
178       
179    def escStar(self) :   
180        """Handles the ESC* sequence."""
181        #self.logdebug("STAR")
182        self.handleTag(self.escstartags)
183       
184    def escLeftPar(self) :   
185        """Handles the ESC( sequence."""
186        #self.logdebug("LEFTPAR")
187        self.handleTag(self.escleftpartags)
188       
189    def escRightPar(self) :   
190        """Handles the ESC( sequence."""
191        #self.logdebug("RIGHTPAR")
192        self.handleTag(self.escrightpartags)
193       
194    def escE(self) :   
195        """Handles the ESCE sequence."""
196        #self.logdebug("RESET")
197        self.resets += 1
198       
199    def escAmpl(self) :   
200        """Handles the ESC&l sequence."""
201        while 1 :
202            (value, end) = self.getInteger()
203            if value is None :
204                return
205            if end in ('h', 'H') :
206                mediasource = self.mediasources.get(value, str(value))
207                self.mediasourcesvalues.append(mediasource)
208                self.setPageDict("mediasource", mediasource)
209                #self.logdebug("MEDIASOURCE %s" % mediasource)
210            elif end in ('a', 'A') :
211                mediasize = self.mediasizes.get(value, str(value))
212                self.mediasizesvalues.append(mediasize)
213                self.setPageDict("mediasize", mediasize)
214                #self.logdebug("MEDIASIZE %s" % mediasize)
215            elif end in ('o', 'O') :
216                orientation = self.orientations.get(value, str(value))
217                self.orientationsvalues.append(orientation)
218                self.setPageDict("orientation", orientation)
219                #self.logdebug("ORIENTATION %s" % orientation)
220            elif end in ('m', 'M') :
221                mediatype = self.mediatypes.get(value, str(value))
222                self.mediatypesvalues.append(mediatype)
223                self.setPageDict("mediatype", mediatype)
224                #self.logdebug("MEDIATYPE %s" % mediatype)
225            elif end == 'X' :
226                self.copies.append(value)
227                self.setPageDict("copies", value)
228                #self.logdebug("COPIES %i" % value)
229               
230    def escAmpa(self) :   
231        """Handles the ESC&a sequence."""
232        while 1 :
233            (value, end) = self.getInteger()
234            if value is None :
235                return
236            if end == 'G' :   
237                #self.logdebug("BACKSIDES %i" % value)
238                self.backsides.append(value)
239                self.setPageDict("duplex", value)
240               
241    def escAmpb(self) :   
242        """Handles the ESC&b sequence."""
243        while 1 :
244            (value, end) = self.getInteger()
245            if value is None :
246                return
247            if end == 'W' :   
248                self.pos += value
249                #self.logdebug("SKIPTO %08x" % self.pos)
250               
251    def escAmpn(self) :   
252        """Handles the ESC&n sequence."""
253        while 1 :
254            (value, end) = self.getInteger()
255            if value is None :
256                return
257            if end == 'W' :   
258                self.pos += value
259                #self.logdebug("SKIPTO %08x" % self.pos)
260               
261    def escAmpp(self) :   
262        """Handles the ESC&p sequence."""
263        while 1 :
264            (value, end) = self.getInteger()
265            if value is None :
266                return
267            if end == 'X' :   
268                self.pos += value
269                #self.logdebug("SKIPTO %08x" % self.pos)
270               
271    def escAmpu(self) :   
272        """Handles the ESC&u sequence."""
273        while 1 :
274            (value, end) = self.getInteger()
275            if value is None :
276                return
277               
278    def escStarb(self) :   
279        """Handles the ESC*b sequence."""
280        while 1 :
281            (value, end) = self.getInteger()
282            if (end is None) and (value is None) :
283                return
284            if end in ('V', 'W', 'v', 'w') :   
285                self.pos += (value or 0)
286                #self.logdebug("SKIPTO %08x" % self.pos)
287               
288    def escStarcgilmv(self) :   
289        """Handles the ESC*c, ESC*g, ESC*i, ESC*l, ESC*m, ESC*v sequences."""
290        while 1 :
291            (value, end) = self.getInteger()
292            if value is None :
293                return
294            if end == 'W' :   
295                self.pos += value
296                #self.logdebug("SKIPTO %08x" % self.pos)
297               
298    def escStaro(self) :   
299        """Handles the ESC*o sequence."""
300        while 1 :
301            (value, end) = self.getInteger()
302            if value is None :
303                return
304               
305    def escStarp(self) :   
306        """Handles the ESC*p sequence."""
307        while 1 :
308            (value, end) = self.getInteger()
309            if value is None :
310                return
311               
312    def escStarr(self) :   
313        """Handles the ESC*r sequence."""
314        while 1 :
315            (value, end) = self.getInteger()
316            if value is None :
317                if end is None :
318                    return
319                elif end in ('B', 'C') :       
320                    #self.logdebug("EndGFX")
321                    if self.startgfx :
322                        self.endgfx.append(1)
323                    else :   
324                        #self.logdebug("EndGFX found before StartGFX, ignored.")
325                        pass
326            if end == 'A' and (0 <= value <= 3) :
327                #self.logdebug("StartGFX %i" % value)
328                self.startgfx.append(value)
329               
330    def escStart(self) :   
331        """Handles the ESC*t sequence."""
332        while 1 :
333            (value, end) = self.getInteger()
334            if value is None :
335                return
336       
337    def escRightorLeftParsf(self) :   
338        """Handles the ESC(s, ESC)s, ESC(f sequences."""
339        while 1 :
340            (value, end) = self.getInteger()
341            if value is None :
342                return
343            if end == 'W' :   
344                self.pos += value
345                #self.logdebug("SKIPTO %08x" % self.pos)
346               
347    def getInteger(self) :   
348        """Returns an integer value and the end character."""
349        sign = 1
350        value = None
351        while 1 :
352            char = chr(self.readByte())
353            if char in (NUL, ESCAPE, FORMFEED, ASCIILIMIT) :
354                self.pos -= 1 # Adjust position
355                return (None, None)
356            if char == '-' :
357                sign = -1
358            elif not char.isdigit() :
359                if value is not None :
360                    return (sign*value, char)
361                else :
362                    return (value, char)
363            else :   
364                value = ((value or 0) * 10) + int(char)   
365       
366    def skipByte(self) :   
367        """Skips a byte."""
368        #self.logdebug("SKIPBYTE %08x ===> %02x" % (self.pos, ord(self.minfile[self.pos])))
369        self.pos += 1
370       
371    def getJobSize(self) :     
372        """Count pages in a PCL5 document.
373         
374           Should also work for PCL3 and PCL4 documents.
375           
376           Algorithm from pclcount
377           (c) 2003, by Eduardo Gielamo Oliveira & Rodolfo Broco Manin
378           published under the terms of the GNU General Public Licence v2.
379         
380           Backported from C to Python by Jerome Alet, then enhanced
381           with more PCL tags detected. I think all the necessary PCL tags
382           are recognized to correctly handle PCL5 files wrt their number
383           of pages. The documentation used for this was :
384         
385           HP PCL/PJL Reference Set
386           PCL5 Printer Language Technical Quick Reference Guide
387           http://h20000.www2.hp.com/bc/docs/support/SupportManual/bpl13205/bpl13205.pdf
388        """
389        infileno = self.infile.fileno()
390        self.minfile = minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
391        self.pages = {}
392        self.pagecount = 0
393        self.resets = 0
394        self.backsides = []
395        self.copies = []
396        self.mediasourcesvalues = []
397        self.mediasizesvalues = []
398        self.orientationsvalues = []
399        self.mediatypesvalues = []
400        self.startgfx = []
401        self.endgfx = []
402        self.hpgl2 = False
403       
404        tags = [ lambda : None] * 256
405        tags[ord(FORMFEED)] = self.endPage
406        tags[ord(ESCAPE)] = self.escape
407        tags[ord(ASCIILIMIT)] = self.skipByte
408       
409        self.esctags = [ lambda : None ] * 256
410        self.esctags[ord('%')] = self.escPercent
411        self.esctags[ord('*')] = self.escStar
412        self.esctags[ord('&')] = self.escAmp
413        self.esctags[ord('(')] = self.escLeftPar
414        self.esctags[ord(')')] = self.escRightPar
415        self.esctags[ord('E')] = self.escE
416       
417        self.escamptags = [lambda : None ] * 256
418        self.escamptags[ord('a')] = self.escAmpa
419        self.escamptags[ord('b')] = self.escAmpb
420        self.escamptags[ord('l')] = self.escAmpl
421        self.escamptags[ord('n')] = self.escAmpn
422        self.escamptags[ord('p')] = self.escAmpp
423        self.escamptags[ord('u')] = self.escAmpu
424       
425        self.escstartags = [ lambda : None ] * 256
426        self.escstartags[ord('b')] = self.escStarb
427        self.escstartags[ord('o')] = self.escStaro
428        self.escstartags[ord('p')] = self.escStarp
429        self.escstartags[ord('r')] = self.escStarr
430        self.escstartags[ord('t')] = self.escStart
431        self.escstartags[ord('c')] = self.escStarcgilmv
432        self.escstartags[ord('g')] = self.escStarcgilmv
433        self.escstartags[ord('i')] = self.escStarcgilmv
434        self.escstartags[ord('l')] = self.escStarcgilmv
435        self.escstartags[ord('m')] = self.escStarcgilmv
436        self.escstartags[ord('v')] = self.escStarcgilmv
437       
438        self.escleftpartags = [ lambda : None ] * 256
439        self.escleftpartags[ord('s')] = self.escRightorLeftParsf
440        self.escleftpartags[ord('f')] = self.escRightorLeftParsf
441       
442        self.escrightpartags = [ lambda : None ] * 256
443        self.escrightpartags[ord('s')] = self.escRightorLeftParsf
444       
445        self.pos = 0
446        try :
447            try :
448                while 1 :
449                    tags[self.readByte()]()
450            except IndexError : # EOF ?           
451                pass
452        finally :
453            self.minfile.close()
454       
455        self.logdebug("Pagecount : \t\t\t%i" % self.pagecount)
456        self.logdebug("Resets : \t\t\t%i" % self.resets)
457        self.logdebug("Copies : \t\t\t%s" % self.copies)
458        self.logdebug("NbCopiesMarks : \t\t%i" % len(self.copies))
459        self.logdebug("MediaTypes : \t\t\t%s" % self.mediatypesvalues)
460        self.logdebug("NbMediaTypes : \t\t\t%i" % len(self.mediatypesvalues))
461        self.logdebug("MediaSizes : \t\t\t%s" % self.mediasizesvalues)
462        self.logdebug("NbMediaSizes : \t\t\t%i" % len(self.mediasizesvalues))
463        self.logdebug("MediaSources : \t\t\t%s" % self.mediasourcesvalues)
464        nbmediasourcesdefault = len([m for m in self.mediasourcesvalues if m == 'Default'])
465        self.logdebug("MediaSourcesDefault : \t\t%i" % nbmediasourcesdefault)
466        self.logdebug("MediaSourcesNOTDefault : \t%i" % (len(self.mediasourcesvalues) - nbmediasourcesdefault))
467        self.logdebug("Orientations : \t\t\t%s" % self.orientationsvalues)
468        self.logdebug("NbOrientations : \t\t\t%i" % len(self.orientationsvalues))
469        self.logdebug("StartGfx : \t\t\t%s" % len(self.startgfx))
470        self.logdebug("EndGfx : \t\t\t%s" % len(self.endgfx))
471        self.logdebug("BackSides : \t\t\t%s" % self.backsides)
472        self.logdebug("NbBackSides : \t\t\t%i" % len(self.backsides))
473       
474        return self.pagecount or nbmediasourcesdefault
475       
476def test() :       
477    """Test function."""
478    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
479        sys.argv.append("-")
480    totalsize = 0   
481    for arg in sys.argv[1:] :
482        if arg == "-" :
483            infile = sys.stdin
484            mustclose = 0
485        else :   
486            infile = open(arg, "rb")
487            mustclose = 1
488        try :
489            parser = Parser(infile, debug=1)
490            totalsize += parser.getJobSize()
491        except pdlparser.PDLParserError, msg :   
492            sys.stderr.write("ERROR: %s\n" % msg)
493            sys.stderr.flush()
494        if mustclose :   
495            infile.close()
496    print "%s" % totalsize
497   
498if __name__ == "__main__" :   
499    test()
Note: See TracBrowser for help on using the browser.