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

Revision 538, 24.2 kB (checked in by jerome, 16 years ago)

Improved detection of PCL3/4/5 datas.

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