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

Revision 426, 22.0 kB (checked in by jerome, 18 years ago)

Uses pswrite instead of pdfwrite to workaround some missing glyphs problems
which were reported.

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