root / pkpgcounter / trunk / pkpgpdls / pcl345.py @ 452

Revision 452, 23.8 kB (checked in by jerome, 17 years ago)

v2.16 is out with a fix for some line based PCL3/4/5 drivers.

  • 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, 2007 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)
35LINEFEED = chr(0x0a)
36FORMFEED = chr(0x0c)
37ESCAPE = chr(0x1b)
38ASCIILIMIT = chr(0x80)
39
40class Parser(pdlparser.PDLParser) :
41    """A parser for PCL3, PCL4, PCL5 documents."""
42    totiffcommands = [ 'pcl6 -sDEVICE=pdfwrite -r%(dpi)i -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -sOutputFile=- - | gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r%(dpi)i -sOutputFile="%(fname)s" -', 
43                       'pcl6 -sDEVICE=pswrite -r%(dpi)i -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -sOutputFile=- - | gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r%(dpi)i -sOutputFile="%(fname)s" -',
44                     ]
45    mediasizes = {  # ESC&l####A
46                    0 : "Default",
47                    1 : "Executive",
48                    2 : "Letter",
49                    3 : "Legal",
50                    6 : "Ledger", 
51                    25 : "A5",
52                    26 : "A4",
53                    27 : "A3",
54                    45 : "JB5",
55                    46 : "JB4",
56                    71 : "HagakiPostcard",
57                    72 : "OufukuHagakiPostcard",
58                    80 : "MonarchEnvelope",
59                    81 : "COM10Envelope",
60                    90 : "DLEnvelope",
61                    91 : "C5Envelope",
62                    100 : "B5Envelope",
63                    101 : "Custom",
64                 }   
65                 
66    mediasources = { # ESC&l####H
67                     0 : "Default",
68                     1 : "Main",
69                     2 : "Manual",
70                     3 : "ManualEnvelope",
71                     4 : "Alternate",
72                     5 : "OptionalLarge",
73                     6 : "EnvelopeFeeder",
74                     7 : "Auto",
75                     8 : "Tray1",
76                   }
77                   
78    orientations = { # ESC&l####O
79                     0 : "Portrait",
80                     1 : "Landscape",
81                     2 : "ReversePortrait",
82                     3 : "ReverseLandscape",
83                   }
84                   
85    mediatypes = { # ESC&l####M
86                     0 : "Plain",
87                     1 : "Bond",
88                     2 : "Special",
89                     3 : "Glossy",
90                     4 : "Transparent",
91                   }
92       
93    def isValid(self) :   
94        """Returns True if data is PCL3/4/5, else False."""
95        if self.firstblock.startswith("\033E\033") or \
96           (self.firstblock.startswith("\033*rbC") and (not self.lastblock[-3:] == "\f\033@")) or \
97           self.firstblock.startswith("\033%8\033") or \
98           (self.firstblock.find("\033%-12345X") != -1) or \
99           (self.firstblock.find("@PJL ENTER LANGUAGE=PCL\012\015\033") != -1) or \
100           (self.firstblock.startswith(chr(0xcd)+chr(0xca)) and self.firstblock.find("\033E\033")) :
101            self.logdebug("DEBUG: Input file is in the PCL3/4/5 format.")
102            return True
103        else :   
104            return False
105       
106    def setPageDict(self, attribute, value) :
107        """Initializes a page dictionnary."""
108        dic = self.pages.setdefault(self.pagecount, { "linescount" : 1,
109                                                      "copies" : 1, 
110                                                      "mediasource" : "Main", 
111                                                      "mediasize" : "Default", 
112                                                      "mediatype" : "Plain", 
113                                                      "orientation" : "Portrait", 
114                                                      "escaped" : "", 
115                                                      "duplex": 0 })
116        dic[attribute] = value
117       
118    def readByte(self) :   
119        """Reads a byte from the input stream."""
120        tag = ord(self.minfile[self.pos])
121        self.pos += 1
122        return tag
123       
124    def endPage(self) :   
125        """Handle the FF marker."""
126        #self.logdebug("FORMFEED %i at %08x" % (self.pagecount, self.pos-1))
127        if not self.hpgl2 :
128            # Increments page count only if we are not inside an HPGL2 block
129            self.pagecount += 1
130       
131    def escPercent(self) :   
132        """Handles the ESC% sequence."""
133        if self.minfile[self.pos : self.pos+7] == r"-12345X" :
134            #self.logdebug("Generic ESCAPE sequence at %08x" % self.pos)
135            self.pos += 7
136            buffer = []
137            quotes = 0
138            char = chr(self.readByte())
139            while ((char < ASCIILIMIT) or (quotes % 2)) and (char not in (FORMFEED, ESCAPE, NUL)) : 
140                buffer.append(char)
141                if char == '"' :
142                    quotes += 1
143                char = chr(self.readByte())
144            self.setPageDict("escaped", "".join(buffer))
145            #self.logdebug("ESCAPED : %s" % "".join(buffer))
146            self.pos -= 1   # Adjust position
147        else :   
148            while 1 :
149                (value, end) = self.getInteger()
150                if end == 'B' :
151                    self.enterHPGL2()
152                    while self.minfile[self.pos] != ESCAPE :
153                        self.pos += 1
154                    self.pos -= 1   
155                    return 
156                elif end == 'A' :   
157                    self.exitHPGL2()
158                    return
159                elif end is None :   
160                    return
161       
162    def enterHPGL2(self) :   
163        """Enters HPGL2 mode."""
164        #self.logdebug("ENTERHPGL2 %08x" % self.pos)
165        self.hpgl2 = True
166       
167    def exitHPGL2(self) :   
168        """Exits HPGL2 mode."""
169        #self.logdebug("EXITHPGL2 %08x" % self.pos)
170        self.hpgl2 = False
171       
172    def handleTag(self, tagtable) :   
173        """Handles tags."""
174        tagtable[self.readByte()]()
175       
176    def escape(self) :   
177        """Handles the ESC character."""
178        #self.logdebug("ESCAPE")
179        self.handleTag(self.esctags)
180       
181    def escAmp(self) :   
182        """Handles the ESC& sequence."""
183        #self.logdebug("AMP")
184        self.handleTag(self.escamptags)
185       
186    def escStar(self) :   
187        """Handles the ESC* sequence."""
188        #self.logdebug("STAR")
189        self.handleTag(self.escstartags)
190       
191    def escLeftPar(self) :   
192        """Handles the ESC( sequence."""
193        #self.logdebug("LEFTPAR")
194        self.handleTag(self.escleftpartags)
195       
196    def escRightPar(self) :   
197        """Handles the ESC( sequence."""
198        #self.logdebug("RIGHTPAR")
199        self.handleTag(self.escrightpartags)
200       
201    def escE(self) :   
202        """Handles the ESCE sequence."""
203        #self.logdebug("RESET")
204        self.resets += 1
205       
206    def escAmpl(self) :   
207        """Handles the ESC&l sequence."""
208        while 1 :
209            (value, end) = self.getInteger()
210            if value is None :
211                return
212            if end in ('h', 'H') :
213                mediasource = self.mediasources.get(value, str(value))
214                self.mediasourcesvalues.append(mediasource)
215                self.setPageDict("mediasource", mediasource)
216                #self.logdebug("MEDIASOURCE %s" % mediasource)
217            elif end in ('a', 'A') :
218                mediasize = self.mediasizes.get(value, str(value))
219                self.mediasizesvalues.append(mediasize)
220                self.setPageDict("mediasize", mediasize)
221                #self.logdebug("MEDIASIZE %s" % mediasize)
222            elif end in ('o', 'O') :
223                orientation = self.orientations.get(value, str(value))
224                self.orientationsvalues.append(orientation)
225                self.setPageDict("orientation", orientation)
226                #self.logdebug("ORIENTATION %s" % orientation)
227            elif end in ('m', 'M') :
228                mediatype = self.mediatypes.get(value, str(value))
229                self.mediatypesvalues.append(mediatype)
230                self.setPageDict("mediatype", mediatype)
231                #self.logdebug("MEDIATYPE %s" % mediatype)
232            elif end == 'X' :
233                self.copies.append(value)
234                self.setPageDict("copies", value)
235                #self.logdebug("COPIES %i" % value)
236            elif end == 'F' :   
237                self.linesperpagevalues.append(value)
238                self.linesperpage = value
239                #self.logdebug("LINES PER PAGE : %i" % self.linesperpage)
240            #else :
241            #    self.logdebug("Unexpected end <%s> and value <%s>" % (end, value))
242               
243    def escAmpa(self) :   
244        """Handles the ESC&a sequence."""
245        while 1 :
246            (value, end) = self.getInteger()
247            if value is None :
248                return
249            if end == 'G' :   
250                #self.logdebug("BACKSIDES %i" % value)
251                self.backsides.append(value)
252                self.setPageDict("duplex", value)
253               
254    def escAmpp(self) :   
255        """Handles the ESC&p sequence."""
256        while 1 :
257            (value, end) = self.getInteger()
258            if value is None :
259                return
260            if end == 'X' :   
261                self.pos += value
262                #self.logdebug("SKIPTO %08x" % self.pos)
263               
264    def escStarb(self) :   
265        """Handles the ESC*b sequence."""
266        while 1 :
267            (value, end) = self.getInteger()
268            if (end is None) and (value is None) :
269                return
270            if end in ('V', 'W', 'v', 'w') :   
271                self.pos += (value or 0)
272                #self.logdebug("SKIPTO %08x" % self.pos)
273               
274    def escStarr(self) :   
275        """Handles the ESC*r sequence."""
276        while 1 :
277            (value, end) = self.getInteger()
278            if value is None :
279                if end is None :
280                    return
281                elif end in ('B', 'C') :       
282                    #self.logdebug("EndGFX")
283                    if self.startgfx :
284                        self.endgfx.append(1)
285                    else :   
286                        #self.logdebug("EndGFX found before StartGFX, ignored.")
287                        pass
288            if end == 'A' and (0 <= value <= 3) :
289                #self.logdebug("StartGFX %i" % value)
290                self.startgfx.append(value)
291               
292    def escStaroptAmpu(self) :   
293        """Handles the ESC*o ESC*p ESC*t and ESC&u sequences."""
294        while 1 :
295            (value, end) = self.getInteger()
296            if value is None :
297                return
298       
299    def escSkipSomethingW(self) :   
300        """Handles the ESC???###W sequences."""
301        while 1 :
302            (value, end) = self.getInteger()
303            if value is None :
304                return
305            if end == 'W' :   
306                self.pos += value
307                #self.logdebug("SKIPTO %08x" % self.pos)
308               
309    def newLine(self) :           
310        """Handles new lines markers."""
311        if not self.hpgl2 :
312            dic = self.pages.get(self.pagecount, None)
313            if dic is None :
314                self.setPageDict("linescount", 1)                             
315                dic = self.pages.get(self.pagecount)
316            nblines = dic["linescount"]   
317            self.setPageDict("linescount", nblines + 1)                             
318            if (self.linesperpage is not None) \
319               and (dic["linescount"] > self.linesperpage) :
320                self.pagecount += 1
321       
322    def getInteger(self) :   
323        """Returns an integer value and the end character."""
324        sign = 1
325        value = None
326        while 1 :
327            char = chr(self.readByte())
328            if char in (NUL, ESCAPE, FORMFEED, ASCIILIMIT) :
329                self.pos -= 1 # Adjust position
330                return (None, None)
331            if char == '-' :
332                sign = -1
333            elif not char.isdigit() :
334                if value is not None :
335                    return (sign*value, char)
336                else :
337                    return (value, char)
338            else :   
339                value = ((value or 0) * 10) + int(char)   
340       
341    def skipByte(self) :   
342        """Skips a byte."""
343        #self.logdebug("SKIPBYTE %08x ===> %02x" % (self.pos, ord(self.minfile[self.pos])))
344        self.pos += 1
345       
346    def handleImageRunner(self) :   
347        """Handles Canon ImageRunner tags."""
348        tag = self.readByte()
349        if tag == ord(self.imagerunnermarker1[-1]) :
350            oldpos = self.pos-2
351            codop = self.minfile[self.pos:self.pos+2]
352            length = unpack(">H", minfile[pos+6:pos+8])[0]
353            self.pos += 18
354            if codop != self.imagerunnermarker2 :
355                self.pos += length
356            self.logdebug("IMAGERUNNERTAG SKIP %i AT %08x" % (self.pos-oldpos, self.pos))
357        else :
358            self.pos -= 1 # Adjust position
359               
360    def getJobSize(self) :     
361        """Count pages in a PCL5 document.
362         
363           Should also work for PCL3 and PCL4 documents.
364           
365           Algorithm from pclcount
366           (c) 2003, by Eduardo Gielamo Oliveira & Rodolfo Broco Manin
367           published under the terms of the GNU General Public Licence v2.
368         
369           Backported from C to Python by Jerome Alet, then enhanced
370           with more PCL tags detected. I think all the necessary PCL tags
371           are recognized to correctly handle PCL5 files wrt their number
372           of pages. The documentation used for this was :
373         
374           HP PCL/PJL Reference Set
375           PCL5 Printer Language Technical Quick Reference Guide
376           http://h20000.www2.hp.com/bc/docs/support/SupportManual/bpl13205/bpl13205.pdf
377        """
378        infileno = self.infile.fileno()
379        self.minfile = minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
380        self.pages = {}
381        self.pagecount = 0
382        self.resets = 0
383        self.backsides = []
384        self.copies = []
385        self.mediasourcesvalues = []
386        self.mediasizesvalues = []
387        self.orientationsvalues = []
388        self.mediatypesvalues = []
389        self.linesperpagevalues = []
390        self.linesperpage = None
391        self.startgfx = []
392        self.endgfx = []
393        self.hpgl2 = False
394        self.imagerunnermarker1 = chr(0xcd) + chr(0xca) # Markers for Canon ImageRunner printers
395        self.imagerunnermarker2 = chr(0x10) + chr(0x02)
396        self.isimagerunner = (minfile[:2] == self.imagerunnermarker1)
397       
398        tags = [ lambda : None] * 256
399        tags[ord(LINEFEED)] = self.newLine
400        tags[ord(FORMFEED)] = self.endPage
401        tags[ord(ESCAPE)] = self.escape
402        tags[ord(ASCIILIMIT)] = self.skipByte
403        tags[ord(self.imagerunnermarker1[0])] = self.handleImageRunner
404       
405        self.esctags = [ lambda : None ] * 256
406        self.esctags[ord('%')] = self.escPercent
407        self.esctags[ord('*')] = self.escStar
408        self.esctags[ord('&')] = self.escAmp
409        self.esctags[ord('(')] = self.escLeftPar
410        self.esctags[ord(')')] = self.escRightPar
411        self.esctags[ord('E')] = self.escE
412       
413        self.escamptags = [lambda : None ] * 256
414        self.escamptags[ord('a')] = self.escAmpa
415        self.escamptags[ord('l')] = self.escAmpl
416        self.escamptags[ord('p')] = self.escAmpp
417        self.escamptags[ord('b')] = self.escSkipSomethingW
418        self.escamptags[ord('n')] = self.escSkipSomethingW
419        self.escamptags[ord('u')] = self.escStaroptAmpu
420       
421        self.escstartags = [ lambda : None ] * 256
422        self.escstartags[ord('b')] = self.escStarb
423        self.escstartags[ord('r')] = self.escStarr
424        self.escstartags[ord('o')] = self.escStaroptAmpu
425        self.escstartags[ord('p')] = self.escStaroptAmpu
426        self.escstartags[ord('t')] = self.escStaroptAmpu
427        self.escstartags[ord('c')] = self.escSkipSomethingW
428        self.escstartags[ord('g')] = self.escSkipSomethingW
429        self.escstartags[ord('i')] = self.escSkipSomethingW
430        self.escstartags[ord('l')] = self.escSkipSomethingW
431        self.escstartags[ord('m')] = self.escSkipSomethingW
432        self.escstartags[ord('v')] = self.escSkipSomethingW
433       
434        self.escleftpartags = [ lambda : None ] * 256
435        self.escleftpartags[ord('s')] = self.escSkipSomethingW
436        self.escleftpartags[ord('f')] = self.escSkipSomethingW
437       
438        self.escrightpartags = [ lambda : None ] * 256
439        self.escrightpartags[ord('s')] = self.escSkipSomethingW
440       
441        self.pos = 0
442        try :
443            try :
444                while 1 :
445                    tags[self.readByte()]()
446            except IndexError : # EOF ?           
447                pass
448        finally :
449            self.minfile.close()
450       
451        self.logdebug("Pagecount : \t\t\t%i" % self.pagecount)
452        self.logdebug("Resets : \t\t\t%i" % self.resets)
453        self.logdebug("Copies : \t\t\t%s" % self.copies)
454        self.logdebug("NbCopiesMarks : \t\t%i" % len(self.copies))
455        self.logdebug("MediaTypes : \t\t\t%s" % self.mediatypesvalues)
456        self.logdebug("NbMediaTypes : \t\t\t%i" % len(self.mediatypesvalues))
457        self.logdebug("MediaSizes : \t\t\t%s" % self.mediasizesvalues)
458        self.logdebug("NbMediaSizes : \t\t\t%i" % len(self.mediasizesvalues))
459        self.logdebug("MediaSources : \t\t\t%s" % self.mediasourcesvalues)
460        nbmediasourcesdefault = len([m for m in self.mediasourcesvalues if m == 'Default'])
461        self.logdebug("MediaSourcesDefault : \t\t%i" % nbmediasourcesdefault)
462        self.logdebug("MediaSourcesNOTDefault : \t%i" % (len(self.mediasourcesvalues) - nbmediasourcesdefault))
463        self.logdebug("Orientations : \t\t\t%s" % self.orientationsvalues)
464        nborientations = len(self.orientationsvalues)
465        self.logdebug("NbOrientations : \t\t\t%i" % nborientations)
466        self.logdebug("StartGfx : \t\t\t%s" % len(self.startgfx))
467        self.logdebug("EndGfx : \t\t\t%s" % len(self.endgfx))
468        self.logdebug("BackSides : \t\t\t%s" % self.backsides)
469        self.logdebug("NbBackSides : \t\t\t%i" % len(self.backsides))
470        self.logdebug("IsImageRunner : \t\t\t%s" % self.isimagerunner)
471       
472        if self.isimagerunner :
473            self.pagecount += 1      # ImageRunner adjustment
474        elif self.linesperpage is not None :   
475            self.pagecount += 1      # Adjusts for incomplete last page
476        elif len(self.startgfx) == len(self.endgfx) == 0 :
477            if self.resets % 2 :
478                if nborientations == self.pagecount + 1 :
479                    self.logdebug("Adjusting PageCount : +1")
480                    self.pagecount += 1
481                elif nborientations == self.pagecount - 1 :
482                    self.logdebug("Adjusting PageCount : -1")
483                    self.pagecount -= 1
484                   
485        self.pagecount = self.pagecount or nbmediasourcesdefault
486       
487       
488        defaultpjlcopies = 1   
489        defaultduplexmode = "Simplex"
490        defaultpapersize = ""
491        oldpjlcopies = -1
492        oldduplexmode = ""
493        oldpapersize = ""
494        for pnum in range(self.pagecount) :
495            # if no number of copies defined, take the preceding one else the one set before any page else 1.
496            page = self.pages.get(pnum, self.pages.get(pnum - 1, self.pages.get(0, { "copies" : 1, "mediasource" : "Main", "mediasize" : "Default", "mediatype" : "Plain", "orientation" : "Portrait", "escaped" : "", "duplex": 0})))
497            pjlstuff = page["escaped"]
498            if pjlstuff :
499                pjlparser = pjl.PJLParser(pjlstuff)
500                nbdefaultcopies = int(pjlparser.default_variables.get("COPIES", -1))
501                nbcopies = int(pjlparser.environment_variables.get("COPIES", -1))
502                nbdefaultqty = int(pjlparser.default_variables.get("QTY", -1))
503                nbqty = int(pjlparser.environment_variables.get("QTY", -1))
504                if nbdefaultcopies > -1 :
505                    defaultpjlcopies = nbdefaultcopies
506                if nbdefaultqty > -1 :
507                    defaultpjlcopies = nbdefaultqty
508                if nbcopies > -1 :
509                    pjlcopies = nbcopies
510                elif nbqty > -1 :
511                    pjlcopies = nbqty
512                else :
513                    if oldpjlcopies == -1 :   
514                        pjlcopies = defaultpjlcopies
515                    else :   
516                        pjlcopies = oldpjlcopies   
517                if page["duplex"] :       
518                    duplexmode = "Duplex"
519                else :   
520                    defaultdm = pjlparser.default_variables.get("DUPLEX", "")
521                    if defaultdm :
522                        if defaultdm.upper() == "ON" :
523                            defaultduplexmode = "Duplex"
524                        else :   
525                            defaultduplexmode = "Simplex"
526                    envdm = pjlparser.environment_variables.get("DUPLEX", "")
527                    if envdm :
528                        if envdm.upper() == "ON" :
529                            duplexmode = "Duplex"
530                        else :   
531                            duplexmode = "Simplex"
532                    else :       
533                        duplexmode = oldduplexmode or defaultduplexmode
534                defaultps = pjlparser.default_variables.get("PAPER", "")
535                if defaultps :
536                    defaultpapersize = defaultps
537                envps = pjlparser.environment_variables.get("PAPER", "")
538                if envps :
539                    papersize = envps
540                else :   
541                    if not oldpapersize :
542                        papersize = defaultpapersize
543                    else :   
544                        papersize = oldpapersize
545            else :       
546                if oldpjlcopies == -1 :
547                    pjlcopies = defaultpjlcopies
548                else :   
549                    pjlcopies = oldpjlcopies
550               
551                duplexmode = (page["duplex"] and "Duplex") or oldduplexmode or defaultduplexmode
552                if not oldpapersize :   
553                    papersize = defaultpapersize
554                else :   
555                    papersize = oldpapersize
556                papersize = oldpapersize or page["mediasize"]
557            if page["mediasize"] != "Default" :
558                papersize = page["mediasize"]
559            if not duplexmode :   
560                duplexmode = oldduplexmode or defaultduplexmode
561            oldpjlcopies = pjlcopies   
562            oldduplexmode = duplexmode
563            oldpapersize = papersize
564            copies = pjlcopies * page["copies"]       
565            self.pagecount += (copies - 1)
566            self.logdebug("%s*%s*%s*%s*%s*%s*BW" % (copies, \
567                                              page["mediatype"], \
568                                              papersize, \
569                                              page["orientation"], \
570                                              page["mediasource"], \
571                                              duplexmode))
572       
573        return self.pagecount
574       
575if __name__ == "__main__" :   
576    pdlparser.test(Parser)
Note: See TracBrowser for help on using the browser.