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

Revision 393, 34.0 kB (checked in by jerome, 18 years ago)

Code cleanup.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
RevLine 
[392]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
[393]34FORMFEED = chr(12)
[392]35ESCAPE = chr(27)
36
37class Parser(pdlparser.PDLParser) :
38    """A parser for PCL3, PCL4, PCL5 documents."""
39    totiffcommand = 'pcl6 -sDEVICE=pdfwrite -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -sOutputFile=- - | gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r%(dpi)i -sOutputFile="%(fname)s" -'
40    mediasizes = {  # ESC&l####A
41                    0 : "Default",
42                    1 : "Executive",
43                    2 : "Letter",
44                    3 : "Legal",
45                    6 : "Ledger", 
46                    25 : "A5",
47                    26 : "A4",
48                    27 : "A3",
49                    45 : "JB5",
50                    46 : "JB4",
51                    71 : "HagakiPostcard",
52                    72 : "OufukuHagakiPostcard",
53                    80 : "MonarchEnvelope",
54                    81 : "COM10Envelope",
55                    90 : "DLEnvelope",
56                    91 : "C5Envelope",
57                    100 : "B5Envelope",
58                    101 : "Custom",
59                 }   
60                 
61    mediasources = { # ESC&l####H
62                     0 : "Default",
63                     1 : "Main",
64                     2 : "Manual",
65                     3 : "ManualEnvelope",
66                     4 : "Alternate",
67                     5 : "OptionalLarge",
68                     6 : "EnvelopeFeeder",
69                     7 : "Auto",
70                     8 : "Tray1",
71                   }
72                   
73    orientations = { # ESC&l####O
74                     0 : "Portrait",
75                     1 : "Landscape",
76                     2 : "ReversePortrait",
77                     3 : "ReverseLandscape",
78                   }
79                   
80    mediatypes = { # ESC&l####M
81                     0 : "Plain",
82                     1 : "Bond",
83                     2 : "Special",
84                     3 : "Glossy",
85                     4 : "Transparent",
86                   }
87       
88    def isValid(self) :   
89        """Returns True if data is PCL3/4/5, else False."""
90        if self.firstblock.startswith("\033E\033") or \
91           (self.firstblock.startswith("\033*rbC") and (not self.lastblock[-3:] == "\f\033@")) or \
92           self.firstblock.startswith("\033%8\033") or \
93           (self.firstblock.find("\033%-12345X") != -1) or \
94           (self.firstblock.find("@PJL ENTER LANGUAGE=PCL\012\015\033") != -1) or \
95           (self.firstblock.startswith(chr(0xcd)+chr(0xca)) and self.firstblock.find("\033E\033")) :
96            self.logdebug("DEBUG: Input file is in the PCL3/4/5 format.")
97            return True
98        else :   
99            return False
100       
101    def setPageDict(self, pages, number, attribute, value) :
102        """Initializes a page dictionnary."""
103        dic = pages.setdefault(number, { "copies" : 1, "mediasource" : "Main", "mediasize" : "Default", "mediatype" : "Plain", "orientation" : "Portrait", "escaped" : "", "duplex": 0})
104        dic[attribute] = value
105       
106    def endPage(self) :   
107        """Handle the FF marker."""
108        self.pagecount += 1
109        self.logdebug("ENDPAGE %i" % self.pagecount)
110       
111    def escPercent(self) :   
112        """Handles the ESC% sequence."""
113        if self.minfile[self.pos : self.pos+7] == r"-12345X" :
114            self.logdebug("Generic ESCAPE sequence at %08x" % self.pos)
115            self.pos += 7
116       
117    def handleTag(self, tagtable) :   
118        """Handles tags."""
119        tag = ord(self.minfile[self.pos])
120        self.pos += 1
121        tagtable[tag]()
122       
123    def escape(self) :   
124        """Handles the ESC character."""
125        self.logdebug("ESCAPE")
126        self.handleTag(self.esctags)
127       
128    def escAmp(self) :   
129        """Handles the ESC& sequence."""
130        self.logdebug("AMP")
131        self.handleTag(self.escamptags)
132       
133    def escStar(self) :   
134        """Handles the ESC* sequence."""
135        self.logdebug("STAR")
136        self.handleTag(self.escstartags)
137       
138    def escLeftPar(self) :   
139        """Handles the ESC( sequence."""
140        self.logdebug("LEFTPAR")
141        self.handleTag(self.escleftpartags)
142       
143    def escRightPar(self) :   
144        """Handles the ESC( sequence."""
145        self.logdebug("RIGHTPAR")
146        self.handleTag(self.escrightpartags)
147       
148    def escE(self) :   
149        """Handles the ESCE sequence."""
150        self.logdebug("RESET")
151        self.resets += 1
152       
153    def escAmpl(self) :   
154        """Handles the ESC&l sequence."""
155        self.logdebug("l")
156        while 1 :
157            (value, end) = self.getInteger()
158            if value is None :
159                return
160            if end in ('h', 'H') :
161                mediasource = self.mediasources.get(value, str(value))
162                self.mediasourcesvalues.append(mediasource)
163                self.logdebug("MEDIASOURCE %s" % mediasource)
164            elif end in ('a', 'A') :
165                mediasize = self.mediasizes.get(value, str(value))
166                self.mediasizesvalues.append(mediasize)
167                self.logdebug("MEDIASIZE %s" % mediasize)
168            elif end in ('o', 'O') :
169                orientation = self.orientations.get(value, str(value))
170                self.orientationsvalues.append(orientation)
171                self.logdebug("ORIENTATION %s" % orientation)
172            elif end in ('m', 'M') :
173                mediatype = self.mediatypes.get(value, str(value))
174                self.mediatypesvalues.append(mediatype)
175                self.logdebug("MEDIATYPE %s" % mediatype)
176            elif end == 'X' :
177                self.copies.append(value)
178                self.logdebug("COPIES %i" % value)
179            elif end == 'L' :   
180                self.logdebug("ESC&l%iL" % value)
181               
182    def escStarb(self) :   
183        """Handles the ESC*b sequence."""
184        self.logdebug("b")
185        while 1 :
186            (value, end) = self.getInteger()
187            self.logdebug("%s === %s" % (value, end))
188            if (end is None) and (value is None) :
189                return
190            if end in ('V', 'W', 'v', 'w') :   
191                self.pos += (value or 0)
192                self.logdebug("SKIPTO %08x" % self.pos)
193               
194    def escStaro(self) :   
195        """Handles the ESC*o sequence."""
196        self.logdebug("o")
197        while 1 :
198            (value, end) = self.getInteger()
199            if value is None :
200                return
201            if end == 'M' :
202                self.logdebug("ESC*o%iM" % value)
203               
204    def escStarp(self) :   
205        """Handles the ESC*p sequence."""
206        self.logdebug("p")
207        while 1 :
208            (value, end) = self.getInteger()
209            if value is None :
210                return
211            if end in ('X', 'Y') :   
212                self.logdebug("ESC*p%i%s" % (value, end))
213               
214    def escStarr(self) :   
215        """Handles the ESC*r sequence."""
216        self.logdebug("r")
217        while 1 :
218            (value, end) = self.getInteger()
219            if value is None :
220                if end is None :
221                    return
222                elif end == 'b' :
223                    if self.minfile[self.pos] == 'C' :
224                        self.logdebug("Looks like it's PCL3.")
225                        self.ispcl3 = True
226                        self.pos += 1
227                elif end == 'C' :       
228                    self.logdebug("EndGFX")
229                    if not self.startgfx :
230                        self.logdebug("EndGFX found before StartGFX, ignored.")
231                    else :   
232                        self.endgfx.append(1)
233            if end == 'A' and (0 <= value <= 3) :
234                self.logdebug("StartGFX %i" % value)
235                self.startgfx.append(value)
236            elif end == 'U' :   
237                self.logdebug("ESC*r%iU" % value)
238            elif end == 'S' :   
239                self.logdebug("ESC*r%iS" % value)
240               
241    def escStart(self) :   
242        """Handles the ESC*t sequence."""
243        self.logdebug("t")
244        while 1 :
245            (value, end) = self.getInteger()
246            if value is None :
247                return
248            if end == 'R' :   
249                self.logdebug("ESC*t%iR" % value)
250               
251    def escAmpu(self) :   
252        """Handles the ESC&u sequence."""
253        self.logdebug("u")
254        while 1 :
255            (value, end) = self.getInteger()
256            if value is None :
257                return
258            if end == 'D' :   
259                self.logdebug("ESC&u%iD" % value)
260               
261       
262    def getInteger(self) :   
263        """Returns an integer value and the end character."""
264        sign = 1
265        value = None
266        while 1 :
267            char = self.minfile[self.pos]
268            if char == ESCAPE :
269                return (None, None)
270            self.pos += 1
271            if char == '-' :
272                sign = -1
273            elif not char.isdigit() :
274                if value is not None :
275                    return (sign*value, char)
276                else :
277                    return (value, char)
278            else :   
279                value = ((value or 0) * 10) + int(char)   
280       
281    def getJobSize(self) :     
282        """Count pages in a PCL5 document.
283         
284           Should also work for PCL3 and PCL4 documents.
285           
286           Algorithm from pclcount
287           (c) 2003, by Eduardo Gielamo Oliveira & Rodolfo Broco Manin
288           published under the terms of the GNU General Public Licence v2.
289         
290           Backported from C to Python by Jerome Alet, then enhanced
291           with more PCL tags detected. I think all the necessary PCL tags
292           are recognized to correctly handle PCL5 files wrt their number
293           of pages. The documentation used for this was :
294         
295           HP PCL/PJL Reference Set
296           PCL5 Printer Language Technical Quick Reference Guide
297           http://h20000.www2.hp.com/bc/docs/support/SupportManual/bpl13205/bpl13205.pdf
298        """
299        infileno = self.infile.fileno()
300        self.minfile = minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
301        self.ispcl3 = False
302        self.pagecount = 0
303        self.resets = 0
304        self.copies = []
305        self.mediasourcesvalues = []
306        self.mediasizesvalues = []
307        self.orientationsvalues = []
308        self.mediatypesvalues = []
309        self.startgfx = []
310        self.endgfx = []
311       
312        tags = [ lambda : None] * 256
[393]313        tags[FORMFEED] = self.endPage
314        tags[ESCAPE] = self.escape
[392]315       
316        self.esctags = [ lambda : None ] * 256
317        self.esctags[ord('%')] = self.escPercent
318        self.esctags[ord('*')] = self.escStar
319        self.esctags[ord('&')] = self.escAmp
320        self.esctags[ord('(')] = self.escLeftPar
321        self.esctags[ord(')')] = self.escRightPar
322        self.esctags[ord('E')] = self.escE
323       
324        self.escamptags = [lambda : None ] * 256
325        self.escamptags[ord('l')] = self.escAmpl
326        self.escamptags[ord('u')] = self.escAmpu
327       
328        self.escstartags = [ lambda : None ] * 256
329        self.escstartags[ord('b')] = self.escStarb
330        self.escstartags[ord('o')] = self.escStaro
331        self.escstartags[ord('p')] = self.escStarp
332        self.escstartags[ord('r')] = self.escStarr
333        self.escstartags[ord('t')] = self.escStart
334       
335        self.pos = 0
336        try :
337            try :
338                while 1 :
339                    tag = ord(minfile[self.pos])
340                    self.logdebug("%08x ===> %02x" % (self.pos, tag))
341                    self.pos += 1
342                    tags[tag]()
343            except IndexError : # EOF ?           
344                pass
345        finally :
346            self.minfile.close()
347       
348            self.logdebug("Pagecount : \t\t%i" % self.pagecount)
349            self.logdebug("Resets : \t\t%i" % self.resets)
350            self.logdebug("Copies : \t\t%s" % self.copies)
351            self.logdebug("MediaTypes : \t\t%s" % self.mediatypesvalues)
352            self.logdebug("MediaSizes : \t\t%s" % self.mediasizesvalues)
353            self.logdebug("MediaSources : \t\t%s" % self.mediasourcesvalues)
354            self.logdebug("Orientations : \t\t%s" % self.orientationsvalues)
355            self.logdebug("StartGfx : \t\t%s" % len(self.startgfx))
356            self.logdebug("EndGfx : \t\t%s" % len(self.endgfx))
357       
358        return self.pagecount
359       
360       
361       
362        """
363        tagsends = { "&n" : "W",
364                     "&b" : "W",
365                     "*i" : "W",
366                     "*l" : "W",
367                     "*m" : "W",
368                     "*v" : "W",
369                     "*c" : "W",
370                     "(f" : "W",
371                     "(s" : "W",
372                     ")s" : "W",
373                     "&p" : "X",
374                     # "&l" : "XHAOM",  # treated specially
375                     "&a" : "G", # TODO : 0 means next side, 1 front side, 2 back side
376                     "*g" : "W",
377                     "*r" : "sbABC",
378                     "*t" : "R",
379                     # "*b" : "VW", # treated specially because it occurs very often
380                   } 
381        irmarker = chr(0xcd) + chr(0xca) # Marker for Canon ImageRunner printers
382        irmarker2 = chr(0x10) + chr(0x02)
383        wasirmarker = 0
384        hasirmarker = (minfile[:2] == (irmarker))
385        pagecount = resets = ejects = backsides = startgfx = endgfx = 0
386        starb = ampl = ispcl3 = escstart = 0
387        mediasourcecount = mediasizecount = orientationcount = mediatypecount = 0
388        tag = None
389        endmark = chr(0x1b) + chr(0x0c) + chr(0x00)
390        asciilimit = chr(0x80)
391        pages = {}
392        pos = 0
393        try :
394            try :
395                while 1 :
396                    if hasirmarker and (minfile[pos:pos+2] == irmarker) :
397                        codop = minfile[pos+2:pos+4]
398                        # self.logdebug("Marker at 0x%08x     (%s)" % (pos, wasirmarker))
399                        length = unpack(">H", minfile[pos+8:pos+10])[0]
400                        pos += 20
401                        if codop != irmarker2 :
402                            pos += length
403                        wasirmarker = 1   
404                    else :       
405                        wasirmarker = 0
406                        elif char == "\033" :   
407                            starb = ampl = 0
408                            if minfile[pos : pos+8] == r"%-12345X" :
409                                endpos = pos + 9
410                                quotes = 0
411                                while (minfile[endpos] not in endmark) and \
412                                      ((minfile[endpos] < asciilimit) or (quotes % 2)) :
413                                    if minfile[endpos] == '"' :
414                                        quotes += 1
415                                    endpos += 1
416                                self.setPageDict(pages, pagecount, "escaped", minfile[pos : endpos])
417                                pos += (endpos - pos)
418                            else :
419                                #
420                                #     <ESC>*b###y#m###v###w... -> PCL3 raster graphics
421                                #     <ESC>*b###W -> Start of a raster data row/block
422                                #     <ESC>*b###V -> Start of a raster data plane
423                                #     <ESC>*c###W -> Start of a user defined pattern
424                                #     <ESC>*i###W -> Start of a viewing illuminant block
425                                #     <ESC>*l###W -> Start of a color lookup table
426                                #     <ESC>*m###W -> Start of a download dither matrix block
427                                #     <ESC>*v###W -> Start of a configure image data block
428                                #     <ESC>*r1A -> Start Gfx
429                                #     <ESC>(s###W -> Start of a characters description block
430                                #     <ESC>)s###W -> Start of a fonts description block
431                                #     <ESC>(f###W -> Start of a symbol set block
432                                #     <ESC>&b###W -> Start of configuration data block
433                                #     <ESC>&l###X -> Number of copies for current page
434                                #     <ESC>&n###W -> Starts an alphanumeric string ID block
435                                #     <ESC>&p###X -> Start of a non printable characters block
436                                #     <ESC>&a2G -> Back side when duplex mode as generated by rastertohp
437                                #     <ESC>*g###W -> Needed for planes in PCL3 output
438                                #     <ESC>&l###H (or only 0 ?) -> Eject if NumPlanes > 1, as generated by rastertohp. Also defines mediasource
439                                #     <ESC>&l###A -> mediasize
440                                #     <ESC>&l###O -> orientation
441                                #     <ESC>&l###M -> mediatype
442                                #     <ESC>*t###R -> gfx resolution
443                                #
444                                tagstart = minfile[pos] ; pos += 1
445                                if tagstart in "E9=YZ" : # one byte PCL tag
446                                    if tagstart == "E" :
447                                        resets += 1
448                                    continue             # skip to next tag
449                                tag = tagstart + minfile[pos] ; pos += 1
450                                if tag == "*b" :
451                                    starb = 1
452                                    tagend = "VW"
453                                elif tag == "&l" :   
454                                    ampl = 1
455                                    tagend = "XHAOM"
456                                else :   
457                                    try :
458                                        tagend = tagsends[tag]
459                                    except KeyError :   
460                                        continue # Unsupported PCL tag
461                                # Now read the numeric argument
462                                size = 0
463                                while 1 :
464                                    char = minfile[pos] ; pos += 1
465                                    if not char.isdigit() :
466                                        break
467                                    size = (size * 10) + int(char)   
468                                if char in tagend :   
469                                    if tag == "&l" :
470                                        if char == "X" :
471                                            self.setPageDict(pages, pagecount, "copies", size)
472                                        elif char == "H" :
473                                            self.setPageDict(pages, pagecount, "mediasource", self.mediasources.get(size, str(size)))
474                                            mediasourcecount += 1
475                                            ejects += 1
476                                        elif char == "A" :
477                                            self.setPageDict(pages, pagecount, "mediasize", self.mediasizes.get(size, str(size)))
478                                            mediasizecount += 1
479                                        elif char == "O" :
480                                            self.setPageDict(pages, pagecount, "orientation", self.orientations.get(size, str(size)))
481                                            orientationcount += 1
482                                        elif char == "M" :
483                                            self.setPageDict(pages, pagecount, "mediatype", self.mediatypes.get(size, str(size)))
484                                            mediatypecount += 1
485                                    elif tag == "*r" :
486                                        # Special tests for PCL3
487                                        if (char == "s") and size :
488                                            while 1 :
489                                                char = minfile[pos] ; pos += 1
490                                                if char == "A" :
491                                                    break
492                                        elif (char == "b") and (minfile[pos] == "C") and not size :
493                                            ispcl3 = 1 # Certainely a PCL3 file
494                                        startgfx += (char == "A") and (minfile[pos - 2] in ("0", "1", "2", "3")) # Start Gfx
495                                        endgfx += (not size) and (char in ("C", "B")) # End Gfx
496                                    elif tag == "*t" :   
497                                        escstart += 1
498                                    elif (tag == "&a") and (size == 2) :
499                                        # We are on the backside, so mark current page as duplex
500                                        self.setPageDict(pages, pagecount, "duplex", 1)
501                                        backsides += 1      # Back side in duplex mode
502                                    else :   
503                                        # we just ignore the block.
504                                        if tag == "&n" :
505                                            # we have to take care of the operation id byte
506                                            # which is before the string itself
507                                            size += 1
508                                        pos += size   
509                        else :                           
510                            if starb :
511                                # special handling of PCL3 in which
512                                # *b introduces combined ESCape sequences
513                                size = 0
514                                while 1 :
515                                    char = minfile[pos] ; pos += 1
516                                    if not char.isdigit() :
517                                        break
518                                    size = (size * 10) + int(char)   
519                                if char in ("w", "v") :   
520                                    ispcl3 = 1  # certainely a PCL3 document
521                                    pos += size - 1
522                                elif char in ("y", "m") :   
523                                    ispcl3 = 1  # certainely a PCL3 document
524                                    pos -= 1    # fix position : we were ahead
525                            elif ampl :       
526                                # special handling of PCL3 in which
527                                # &l introduces combined ESCape sequences
528                                size = 0
529                                while 1 :
530                                    char = minfile[pos] ; pos += 1
531                                    if not char.isdigit() :
532                                        break
533                                    size = (size * 10) + int(char)   
534                                if char in ("a", "o", "h", "m") :   
535                                    ispcl3 = 1  # certainely a PCL3 document
536                                    pos -= 1    # fix position : we were ahead
537                                    if char == "h" :
538                                        self.setPageDict(pages, pagecount, "mediasource", self.mediasources.get(size, str(size)))
539                                        mediasourcecount += 1
540                                    elif char == "a" :
541                                        self.setPageDict(pages, pagecount, "mediasize", self.mediasizes.get(size, str(size)))
542                                        mediasizecount += 1
543                                    elif char == "o" :
544                                        self.setPageDict(pages, pagecount, "orientation", self.orientations.get(size, str(size)))
545                                        orientationcount += 1
546                                    elif char == "m" :
547                                        self.setPageDict(pages, pagecount, "mediatype", self.mediatypes.get(size, str(size)))
548                                        mediatypecount += 1
549            except IndexError : # EOF ?
550                pass
551        finally :
552            minfile.close()
553                           
554        # if pagecount is still 0, we will use the number
555        # of resets instead of the number of form feed characters.
556        # but the number of resets is always at least 2 with a valid
557        # pcl file : one at the very start and one at the very end
558        # of the job's data. So we substract 2 from the number of
559        # resets. And since on our test data we needed to substract
560        # 1 more, we finally substract 3, and will test several
561        # PCL files with this. If resets < 2, then the file is
562        # probably not a valid PCL file, so we use 0
563       
564        if self.debug :
565            sys.stderr.write("pagecount : %s\n" % pagecount)
566            sys.stderr.write("resets : %s\n" % resets)
567            sys.stderr.write("ejects : %s\n" % ejects)
568            sys.stderr.write("backsides : %s\n" % backsides)
569            sys.stderr.write("startgfx : %s\n" % startgfx)
570            sys.stderr.write("endgfx : %s\n" % endgfx)
571            sys.stderr.write("mediasourcecount : %s\n" % mediasourcecount)
572            sys.stderr.write("mediasizecount : %s\n" % mediasizecount)
573            sys.stderr.write("orientationcount : %s\n" % orientationcount)
574            sys.stderr.write("mediatypecount : %s\n" % mediatypecount)
575            sys.stderr.write("escstart : %s\n" % escstart)
576            sys.stderr.write("hasirmarker : %s\n" % hasirmarker)
577       
578        if hasirmarker :
579            self.logdebug("Rule #20 (probably a Canon ImageRunner)")
580            pagecount += 1
581        elif (orientationcount == (pagecount - 1)) and (resets == 1) :
582            if resets == ejects == startgfx == mediasourcecount == escstart == 1 :
583                self.logdebug("Rule #19")
584            else :   
585                self.logdebug("Rule #1")
586                pagecount -= 1
587        elif pagecount and (pagecount == orientationcount) :
588            self.logdebug("Rule #2")
589        elif resets == ejects == mediasourcecount == mediasizecount == escstart == 1 :
590            #if ((startgfx and endgfx) and (startgfx != endgfx)) or (startgfx == endgfx == 0) :
591            if (startgfx and endgfx) or (startgfx == endgfx == 0) :
592                self.logdebug("Rule #3")
593                pagecount = orientationcount
594            elif (endgfx and not startgfx) and (pagecount > orientationcount) :   
595                self.logdebug("Rule #4")
596                pagecount = orientationcount
597            else :     
598                self.logdebug("Rule #5")
599                pagecount += 1
600        elif (ejects == mediasourcecount == orientationcount) and (startgfx == endgfx) :     
601            if (resets == 2) and (orientationcount == (pagecount - 1)) and (orientationcount > 1) :
602                self.logdebug("Rule #6")
603                pagecount = orientationcount
604        elif pagecount == mediasourcecount == escstart :
605            self.logdebug("Rule #7")
606        elif resets == startgfx == endgfx == mediasizecount == orientationcount == escstart == 1 :     
607            self.logdebug("Rule #8")
608        elif resets == startgfx == endgfx == (pagecount - 1) :   
609            self.logdebug("Rule #9")
610        elif (not startgfx) and (not endgfx) :
611            self.logdebug("Rule #10")
612        elif (resets == 2) and (startgfx == endgfx) and (mediasourcecount == 1) :
613            if orientationcount == (pagecount - 1) :
614                self.logdebug("Rule #11")
615                pagecount = orientationcount
616            elif not pagecount :   
617                self.logdebug("Rule #17")
618                pagecount = ejects
619        elif (resets == 1) and (startgfx == endgfx) and (mediasourcecount == 0) :
620            if (startgfx > 1) and (startgfx != (pagecount - 1)) :
621                self.logdebug("Rule #12")
622                pagecount -= 1
623            else :   
624                self.logdebug("Rule #18")
625        elif startgfx == endgfx :   
626            self.logdebug("Rule #13")
627            pagecount = startgfx
628        elif startgfx == (endgfx - 1) :   
629            self.logdebug("Rule #14")
630            pagecount = startgfx
631        elif (startgfx == 1) and not endgfx :   
632            self.logdebug("Rule #15")
633            pass
634        else :   
635            self.logdebug("Rule #16")
636            pagecount = abs(startgfx - endgfx)
637           
638        defaultpjlcopies = 1   
639        defaultduplexmode = "Simplex"
640        defaultpapersize = ""
641        oldpjlcopies = -1
642        oldduplexmode = ""
643        oldpapersize = ""
644        for pnum in range(pagecount) :
645            # if no number of copies defined, take the preceding one else the one set before any page else 1.
646            page = pages.get(pnum, pages.get(pnum - 1, pages.get(0, { "copies" : 1, "mediasource" : "Main", "mediasize" : "Default", "mediatype" : "Plain", "orientation" : "Portrait", "escaped" : "", "duplex": 0})))
647            pjlstuff = page["escaped"]
648            if pjlstuff :
649                pjlparser = pjl.PJLParser(pjlstuff)
650                nbdefaultcopies = int(pjlparser.default_variables.get("COPIES", -1))
651                nbcopies = int(pjlparser.environment_variables.get("COPIES", -1))
652                nbdefaultqty = int(pjlparser.default_variables.get("QTY", -1))
653                nbqty = int(pjlparser.environment_variables.get("QTY", -1))
654                if nbdefaultcopies > -1 :
655                    defaultpjlcopies = nbdefaultcopies
656                if nbdefaultqty > -1 :
657                    defaultpjlcopies = nbdefaultqty
658                if nbcopies > -1 :
659                    pjlcopies = nbcopies
660                elif nbqty > -1 :
661                    pjlcopies = nbqty
662                else :
663                    if oldpjlcopies == -1 :   
664                        pjlcopies = defaultpjlcopies
665                    else :   
666                        pjlcopies = oldpjlcopies   
667                if page["duplex"] :       
668                    duplexmode = "Duplex"
669                else :   
670                    defaultdm = pjlparser.default_variables.get("DUPLEX", "")
671                    if defaultdm :
672                        if defaultdm.upper() == "ON" :
673                            defaultduplexmode = "Duplex"
674                        else :   
675                            defaultduplexmode = "Simplex"
676                    envdm = pjlparser.environment_variables.get("DUPLEX", "")
677                    if envdm :
678                        if envdm.upper() == "ON" :
679                            duplexmode = "Duplex"
680                        else :   
681                            duplexmode = "Simplex"
682                    else :       
683                        duplexmode = oldduplexmode or defaultduplexmode
684                defaultps = pjlparser.default_variables.get("PAPER", "")
685                if defaultps :
686                    defaultpapersize = defaultps
687                envps = pjlparser.environment_variables.get("PAPER", "")
688                if envps :
689                    papersize = envps
690                else :   
691                    if not oldpapersize :
692                        papersize = defaultpapersize
693                    else :   
694                        papersize = oldpapersize
695            else :       
696                if oldpjlcopies == -1 :
697                    pjlcopies = defaultpjlcopies
698                else :   
699                    pjlcopies = oldpjlcopies
700               
701                duplexmode = (page["duplex"] and "Duplex") or oldduplexmode or defaultduplexmode
702                if not oldpapersize :   
703                    papersize = defaultpapersize
704                else :   
705                    papersize = oldpapersize
706                papersize = oldpapersize or page["mediasize"]
707            if page["mediasize"] != "Default" :
708                papersize = page["mediasize"]
709            if not duplexmode :   
710                duplexmode = oldduplexmode or defaultduplexmode
711            oldpjlcopies = pjlcopies   
712            oldduplexmode = duplexmode
713            oldpapersize = papersize
714            copies = pjlcopies * page["copies"]       
715            pagecount += (copies - 1)
716            self.logdebug("%s*%s*%s*%s*%s*%s*BW" % (copies, \
717                                              page["mediatype"], \
718                                              papersize, \
719                                              page["orientation"], \
720                                              page["mediasource"], \
721                                              duplexmode))
722               
723        return pagecount
724        """
725       
726def test() :       
727    """Test function."""
728    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
729        sys.argv.append("-")
730    totalsize = 0   
731    for arg in sys.argv[1:] :
732        if arg == "-" :
733            infile = sys.stdin
734            mustclose = 0
735        else :   
736            infile = open(arg, "rb")
737            mustclose = 1
738        try :
739            parser = Parser(infile, debug=1)
740            totalsize += parser.getJobSize()
741        except pdlparser.PDLParserError, msg :   
742            sys.stderr.write("ERROR: %s\n" % msg)
743            sys.stderr.flush()
744        if mustclose :   
745            infile.close()
746    print "%s" % totalsize
747   
748if __name__ == "__main__" :   
749    test()
Note: See TracBrowser for help on using the browser.