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

Revision 541, 24.4 kB (checked in by jerome, 16 years ago)

Now the oce9050 ghostscript device should be correctly detected as PCL3/4/5.

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