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

Revision 343, 25.4 kB (checked in by jerome, 18 years ago)

Fixed very important bug in file type autodetection code.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Auth Date Id Rev
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
24import sys
25import os
26import mmap
27from struct import unpack
28
29import pdlparser
30import pjl
31
32class Parser(pdlparser.PDLParser) :
33    """A parser for PCL3, PCL4, PCL5 documents."""
34    mediasizes = {  # ESC&l####A
35                    0 : "Default",
36                    1 : "Executive",
37                    2 : "Letter",
38                    3 : "Legal",
39                    6 : "Ledger", 
40                    25 : "A5",
41                    26 : "A4",
42                    27 : "A3",
43                    45 : "JB5",
44                    46 : "JB4",
45                    71 : "HagakiPostcard",
46                    72 : "OufukuHagakiPostcard",
47                    80 : "MonarchEnvelope",
48                    81 : "COM10Envelope",
49                    90 : "DLEnvelope",
50                    91 : "C5Envelope",
51                    100 : "B5Envelope",
52                    101 : "Custom",
53                 }   
54                 
55    mediasources = { # ESC&l####H
56                     0 : "Default",
57                     1 : "Main",
58                     2 : "Manual",
59                     3 : "ManualEnvelope",
60                     4 : "Alternate",
61                     5 : "OptionalLarge",
62                     6 : "EnvelopeFeeder",
63                     7 : "Auto",
64                     8 : "Tray1",
65                   }
66                   
67    orientations = { # ESC&l####O
68                     0 : "Portrait",
69                     1 : "Landscape",
70                     2 : "ReversePortrait",
71                     3 : "ReverseLandscape",
72                   }
73                   
74    mediatypes = { # ESC&l####M
75                     0 : "Plain",
76                     1 : "Bond",
77                     2 : "Special",
78                     3 : "Glossy",
79                     4 : "Transparent",
80                   }
81       
82    def isValid(self) :   
83        """Returns 1 if data is PCL, else 0."""
84        if self.firstblock.startswith("\033E\033") or \
85           (self.firstblock.startswith("\033*rbC") and (not self.lastblock[-3:] == "\f\033@")) or \
86           self.firstblock.startswith("\033%8\033") or \
87           (self.firstblock.find("\033%-12345X") != -1) or \
88           (self.firstblock.find("@PJL ENTER LANGUAGE=PCL\012\015\033") != -1) or \
89           (self.firstblock.startswith(chr(0xcd)+chr(0xca)) and self.firstblock.find("\033E\033")) :
90            self.logdebug("DEBUG: Input file is in the PCL3/4/5 format.")
91            return 1
92        else :   
93            return 0
94       
95    def setPageDict(self, pages, number, attribute, value) :
96        """Initializes a page dictionnary."""
97        dic = pages.setdefault(number, { "copies" : 1, "mediasource" : "Main", "mediasize" : "Default", "mediatype" : "Plain", "orientation" : "Portrait", "escaped" : "", "duplex": 0})
98        dic[attribute] = value
99       
100    def getJobSize(self) :     
101        """Count pages in a PCL5 document.
102         
103           Should also work for PCL3 and PCL4 documents.
104           
105           Algorithm from pclcount
106           (c) 2003, by Eduardo Gielamo Oliveira & Rodolfo Broco Manin
107           published under the terms of the GNU General Public Licence v2.
108         
109           Backported from C to Python by Jerome Alet, then enhanced
110           with more PCL tags detected. I think all the necessary PCL tags
111           are recognized to correctly handle PCL5 files wrt their number
112           of pages. The documentation used for this was :
113         
114           HP PCL/PJL Reference Set
115           PCL5 Printer Language Technical Quick Reference Guide
116           http://h20000.www2.hp.com/bc/docs/support/SupportManual/bpl13205/bpl13205.pdf
117        """
118        infileno = self.infile.fileno()
119        minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
120        tagsends = { "&n" : "W", 
121                     "&b" : "W", 
122                     "*i" : "W", 
123                     "*l" : "W", 
124                     "*m" : "W", 
125                     "*v" : "W", 
126                     "*c" : "W", 
127                     "(f" : "W", 
128                     "(s" : "W", 
129                     ")s" : "W", 
130                     "&p" : "X", 
131                     # "&l" : "XHAOM",  # treated specially
132                     "&a" : "G", # TODO : 0 means next side, 1 front side, 2 back side
133                     "*g" : "W",
134                     "*r" : "sbABC",
135                     "*t" : "R",
136                     # "*b" : "VW", # treated specially because it occurs very often
137                   } 
138        irmarker = chr(0xcd) + chr(0xca) # Marker for Canon ImageRunner printers
139        irmarker2 = chr(0x10) + chr(0x02)
140        wasirmarker = 0
141        hasirmarker = (minfile[:2] == (irmarker))
142        pagecount = resets = ejects = backsides = startgfx = endgfx = 0
143        starb = ampl = ispcl3 = escstart = 0
144        mediasourcecount = mediasizecount = orientationcount = mediatypecount = 0
145        tag = None
146        endmark = chr(0x1b) + chr(0x0c) + chr(0x00) 
147        asciilimit = chr(0x80)
148        pages = {}
149        pos = 0
150        try :
151            try :
152                while 1 :
153                    if hasirmarker and (minfile[pos:pos+2] == irmarker) :
154                        codop = minfile[pos+2:pos+4]
155                        # self.logdebug("Marker at 0x%08x     (%s)" % (pos, wasirmarker))
156                        length = unpack(">H", minfile[pos+8:pos+10])[0]
157                        pos += 20
158                        if codop != irmarker2 :
159                            pos += length
160                        wasirmarker = 1   
161                    else :       
162                        wasirmarker = 0
163                        char = minfile[pos] ; pos += 1
164                        if char == "\014" :   
165                            pagecount += 1
166                        elif char == "\033" :   
167                            starb = ampl = 0
168                            if minfile[pos : pos+8] == r"%-12345X" :
169                                endpos = pos + 9
170                                quotes = 0
171                                while (minfile[endpos] not in endmark) and \
172                                      ((minfile[endpos] < asciilimit) or (quotes % 2)) :
173                                    if minfile[endpos] == '"' :
174                                        quotes += 1
175                                    endpos += 1
176                                self.setPageDict(pages, pagecount, "escaped", minfile[pos : endpos])
177                                pos += (endpos - pos)
178                            else :
179                                #
180                                #     <ESC>*b###y#m###v###w... -> PCL3 raster graphics
181                                #     <ESC>*b###W -> Start of a raster data row/block
182                                #     <ESC>*b###V -> Start of a raster data plane
183                                #     <ESC>*c###W -> Start of a user defined pattern
184                                #     <ESC>*i###W -> Start of a viewing illuminant block
185                                #     <ESC>*l###W -> Start of a color lookup table
186                                #     <ESC>*m###W -> Start of a download dither matrix block
187                                #     <ESC>*v###W -> Start of a configure image data block
188                                #     <ESC>*r1A -> Start Gfx
189                                #     <ESC>(s###W -> Start of a characters description block
190                                #     <ESC>)s###W -> Start of a fonts description block
191                                #     <ESC>(f###W -> Start of a symbol set block
192                                #     <ESC>&b###W -> Start of configuration data block
193                                #     <ESC>&l###X -> Number of copies for current page
194                                #     <ESC>&n###W -> Starts an alphanumeric string ID block
195                                #     <ESC>&p###X -> Start of a non printable characters block
196                                #     <ESC>&a2G -> Back side when duplex mode as generated by rastertohp
197                                #     <ESC>*g###W -> Needed for planes in PCL3 output
198                                #     <ESC>&l###H (or only 0 ?) -> Eject if NumPlanes > 1, as generated by rastertohp. Also defines mediasource
199                                #     <ESC>&l###A -> mediasize
200                                #     <ESC>&l###O -> orientation
201                                #     <ESC>&l###M -> mediatype
202                                #     <ESC>*t###R -> gfx resolution
203                                #
204                                tagstart = minfile[pos] ; pos += 1
205                                if tagstart in "E9=YZ" : # one byte PCL tag
206                                    if tagstart == "E" :
207                                        resets += 1
208                                    continue             # skip to next tag
209                                tag = tagstart + minfile[pos] ; pos += 1
210                                if tag == "*b" : 
211                                    starb = 1
212                                    tagend = "VW"
213                                elif tag == "&l" :   
214                                    ampl = 1
215                                    tagend = "XHAOM"
216                                else :   
217                                    try :
218                                        tagend = tagsends[tag]
219                                    except KeyError :   
220                                        continue # Unsupported PCL tag
221                                # Now read the numeric argument
222                                size = 0
223                                while 1 :
224                                    char = minfile[pos] ; pos += 1
225                                    if not char.isdigit() :
226                                        break
227                                    size = (size * 10) + int(char)   
228                                if char in tagend :   
229                                    if tag == "&l" :
230                                        if char == "X" : 
231                                            self.setPageDict(pages, pagecount, "copies", size)
232                                        elif char == "H" :
233                                            self.setPageDict(pages, pagecount, "mediasource", self.mediasources.get(size, str(size)))
234                                            mediasourcecount += 1
235                                            ejects += 1 
236                                        elif char == "A" :
237                                            self.setPageDict(pages, pagecount, "mediasize", self.mediasizes.get(size, str(size)))
238                                            mediasizecount += 1
239                                        elif char == "O" :
240                                            self.setPageDict(pages, pagecount, "orientation", self.orientations.get(size, str(size)))
241                                            orientationcount += 1
242                                        elif char == "M" :
243                                            self.setPageDict(pages, pagecount, "mediatype", self.mediatypes.get(size, str(size)))
244                                            mediatypecount += 1
245                                    elif tag == "*r" :
246                                        # Special tests for PCL3
247                                        if (char == "s") and size :
248                                            while 1 :
249                                                char = minfile[pos] ; pos += 1
250                                                if char == "A" :
251                                                    break
252                                        elif (char == "b") and (minfile[pos] == "C") and not size :
253                                            ispcl3 = 1 # Certainely a PCL3 file
254                                        startgfx += (char == "A") and (minfile[pos - 2] in ("0", "1", "2", "3")) # Start Gfx
255                                        endgfx += (not size) and (char in ("C", "B")) # End Gfx
256                                    elif tag == "*t" :   
257                                        escstart += 1
258                                    elif (tag == "&a") and (size == 2) :
259                                        # We are on the backside, so mark current page as duplex
260                                        self.setPageDict(pages, pagecount, "duplex", 1)
261                                        backsides += 1      # Back side in duplex mode
262                                    else :   
263                                        # we just ignore the block.
264                                        if tag == "&n" : 
265                                            # we have to take care of the operation id byte
266                                            # which is before the string itself
267                                            size += 1
268                                        pos += size   
269                        else :                           
270                            if starb :
271                                # special handling of PCL3 in which
272                                # *b introduces combined ESCape sequences
273                                size = 0
274                                while 1 :
275                                    char = minfile[pos] ; pos += 1
276                                    if not char.isdigit() :
277                                        break
278                                    size = (size * 10) + int(char)   
279                                if char in ("w", "v") :   
280                                    ispcl3 = 1  # certainely a PCL3 document
281                                    pos += size - 1
282                                elif char in ("y", "m") :   
283                                    ispcl3 = 1  # certainely a PCL3 document
284                                    pos -= 1    # fix position : we were ahead
285                            elif ampl :       
286                                # special handling of PCL3 in which
287                                # &l introduces combined ESCape sequences
288                                size = 0
289                                while 1 :
290                                    char = minfile[pos] ; pos += 1
291                                    if not char.isdigit() :
292                                        break
293                                    size = (size * 10) + int(char)   
294                                if char in ("a", "o", "h", "m") :   
295                                    ispcl3 = 1  # certainely a PCL3 document
296                                    pos -= 1    # fix position : we were ahead
297                                    if char == "h" :
298                                        self.setPageDict(pages, pagecount, "mediasource", self.mediasources.get(size, str(size)))
299                                        mediasourcecount += 1
300                                    elif char == "a" :
301                                        self.setPageDict(pages, pagecount, "mediasize", self.mediasizes.get(size, str(size)))
302                                        mediasizecount += 1
303                                    elif char == "o" :
304                                        self.setPageDict(pages, pagecount, "orientation", self.orientations.get(size, str(size)))
305                                        orientationcount += 1
306                                    elif char == "m" :
307                                        self.setPageDict(pages, pagecount, "mediatype", self.mediatypes.get(size, str(size)))
308                                        mediatypecount += 1
309            except IndexError : # EOF ?
310                pass
311        finally :
312            minfile.close()
313                           
314        # if pagecount is still 0, we will use the number
315        # of resets instead of the number of form feed characters.
316        # but the number of resets is always at least 2 with a valid
317        # pcl file : one at the very start and one at the very end
318        # of the job's data. So we substract 2 from the number of
319        # resets. And since on our test data we needed to substract
320        # 1 more, we finally substract 3, and will test several
321        # PCL files with this. If resets < 2, then the file is
322        # probably not a valid PCL file, so we use 0
323       
324        if self.debug :
325            sys.stderr.write("pagecount : %s\n" % pagecount)
326            sys.stderr.write("resets : %s\n" % resets)
327            sys.stderr.write("ejects : %s\n" % ejects)
328            sys.stderr.write("backsides : %s\n" % backsides)
329            sys.stderr.write("startgfx : %s\n" % startgfx)
330            sys.stderr.write("endgfx : %s\n" % endgfx)
331            sys.stderr.write("mediasourcecount : %s\n" % mediasourcecount)
332            sys.stderr.write("mediasizecount : %s\n" % mediasizecount)
333            sys.stderr.write("orientationcount : %s\n" % orientationcount)
334            sys.stderr.write("mediatypecount : %s\n" % mediatypecount)
335            sys.stderr.write("escstart : %s\n" % escstart)
336            sys.stderr.write("hasirmarker : %s\n" % hasirmarker)
337       
338        if hasirmarker :
339            self.logdebug("Rule #20 (probably a Canon ImageRunner)")
340            pagecount += 1
341        elif (orientationcount == (pagecount - 1)) and (resets == 1) :
342            if resets == ejects == startgfx == mediasourcecount == escstart == 1 :
343                self.logdebug("Rule #19")
344            else :   
345                self.logdebug("Rule #1")
346                pagecount -= 1
347        elif pagecount and (pagecount == orientationcount) :
348            self.logdebug("Rule #2")
349        elif resets == ejects == mediasourcecount == mediasizecount == escstart == 1 :
350            #if ((startgfx and endgfx) and (startgfx != endgfx)) or (startgfx == endgfx == 0) :
351            if (startgfx and endgfx) or (startgfx == endgfx == 0) :
352                self.logdebug("Rule #3")
353                pagecount = orientationcount
354            elif (endgfx and not startgfx) and (pagecount > orientationcount) :   
355                self.logdebug("Rule #4")
356                pagecount = orientationcount
357            else :     
358                self.logdebug("Rule #5")
359                pagecount += 1
360        elif (ejects == mediasourcecount == orientationcount) and (startgfx == endgfx) :     
361            if (resets == 2) and (orientationcount == (pagecount - 1)) and (orientationcount > 1) :
362                self.logdebug("Rule #6")
363                pagecount = orientationcount
364        elif pagecount == mediasourcecount == escstart : 
365            self.logdebug("Rule #7")
366        elif resets == startgfx == endgfx == mediasizecount == orientationcount == escstart == 1 :     
367            self.logdebug("Rule #8")
368        elif resets == startgfx == endgfx == (pagecount - 1) :   
369            self.logdebug("Rule #9")
370        elif (not startgfx) and (not endgfx) :
371            self.logdebug("Rule #10")
372        elif (resets == 2) and (startgfx == endgfx) and (mediasourcecount == 1) :
373            if orientationcount == (pagecount - 1) :
374                self.logdebug("Rule #11")
375                pagecount = orientationcount
376            elif not pagecount :   
377                self.logdebug("Rule #17")
378                pagecount = ejects
379        elif (resets == 1) and (startgfx == endgfx) and (mediasourcecount == 0) :
380            if (startgfx > 1) and (startgfx != (pagecount - 1)) :
381                self.logdebug("Rule #12")
382                pagecount -= 1
383            else :   
384                self.logdebug("Rule #18")
385        elif startgfx == endgfx :   
386            self.logdebug("Rule #13")
387            pagecount = startgfx
388        elif startgfx == (endgfx - 1) :   
389            self.logdebug("Rule #14")
390            pagecount = startgfx
391        elif (startgfx == 1) and not endgfx :   
392            self.logdebug("Rule #15")
393            pass
394        else :   
395            self.logdebug("Rule #16")
396            pagecount = abs(startgfx - endgfx)
397           
398        defaultpjlcopies = 1   
399        defaultduplexmode = "Simplex"
400        defaultpapersize = ""
401        oldpjlcopies = -1
402        oldduplexmode = ""
403        oldpapersize = ""
404        for pnum in range(pagecount) :
405            # if no number of copies defined, take the preceding one else the one set before any page else 1.
406            page = pages.get(pnum, pages.get(pnum - 1, pages.get(0, { "copies" : 1, "mediasource" : "Main", "mediasize" : "Default", "mediatype" : "Plain", "orientation" : "Portrait", "escaped" : "", "duplex": 0})))
407            pjlstuff = page["escaped"]
408            if pjlstuff :
409                pjlparser = pjl.PJLParser(pjlstuff)
410                nbdefaultcopies = int(pjlparser.default_variables.get("COPIES", -1))
411                nbcopies = int(pjlparser.environment_variables.get("COPIES", -1))
412                nbdefaultqty = int(pjlparser.default_variables.get("QTY", -1))
413                nbqty = int(pjlparser.environment_variables.get("QTY", -1))
414                if nbdefaultcopies > -1 :
415                    defaultpjlcopies = nbdefaultcopies
416                if nbdefaultqty > -1 :
417                    defaultpjlcopies = nbdefaultqty
418                if nbcopies > -1 :
419                    pjlcopies = nbcopies
420                elif nbqty > -1 :
421                    pjlcopies = nbqty
422                else :
423                    if oldpjlcopies == -1 :   
424                        pjlcopies = defaultpjlcopies
425                    else :   
426                        pjlcopies = oldpjlcopies   
427                if page["duplex"] :       
428                    duplexmode = "Duplex"
429                else :   
430                    defaultdm = pjlparser.default_variables.get("DUPLEX", "")
431                    if defaultdm :
432                        if defaultdm.upper() == "ON" :
433                            defaultduplexmode = "Duplex"
434                        else :   
435                            defaultduplexmode = "Simplex"
436                    envdm = pjlparser.environment_variables.get("DUPLEX", "")
437                    if envdm :
438                        if envdm.upper() == "ON" :
439                            duplexmode = "Duplex"
440                        else :   
441                            duplexmode = "Simplex"
442                    else :       
443                        duplexmode = oldduplexmode or defaultduplexmode
444                defaultps = pjlparser.default_variables.get("PAPER", "")
445                if defaultps :
446                    defaultpapersize = defaultps
447                envps = pjlparser.environment_variables.get("PAPER", "")
448                if envps :
449                    papersize = envps
450                else :   
451                    if not oldpapersize :
452                        papersize = defaultpapersize
453                    else :   
454                        papersize = oldpapersize
455            else :       
456                if oldpjlcopies == -1 :
457                    pjlcopies = defaultpjlcopies
458                else :   
459                    pjlcopies = oldpjlcopies
460               
461                duplexmode = (page["duplex"] and "Duplex") or oldduplexmode or defaultduplexmode
462                if not oldpapersize :   
463                    papersize = defaultpapersize
464                else :   
465                    papersize = oldpapersize
466                papersize = oldpapersize or page["mediasize"]
467            if page["mediasize"] != "Default" :
468                papersize = page["mediasize"]
469            if not duplexmode :   
470                duplexmode = oldduplexmode or defaultduplexmode
471            oldpjlcopies = pjlcopies   
472            oldduplexmode = duplexmode
473            oldpapersize = papersize
474            copies = pjlcopies * page["copies"]       
475            pagecount += (copies - 1)
476            self.logdebug("%s*%s*%s*%s*%s*%s*BW" % (copies, \
477                                              page["mediatype"], \
478                                              papersize, \
479                                              page["orientation"], \
480                                              page["mediasource"], \
481                                              duplexmode))
482               
483        return pagecount
484       
485def test() :       
486    """Test function."""
487    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
488        sys.argv.append("-")
489    totalsize = 0   
490    for arg in sys.argv[1:] :
491        if arg == "-" :
492            infile = sys.stdin
493            mustclose = 0
494        else :   
495            infile = open(arg, "rb")
496            mustclose = 1
497        try :
498            parser = Parser(infile, debug=1)
499            totalsize += parser.getJobSize()
500        except pdlparser.PDLParserError, msg :   
501            sys.stderr.write("ERROR: %s\n" % msg)
502            sys.stderr.flush()
503        if mustclose :   
504            infile.close()
505    print "%s" % totalsize
506   
507if __name__ == "__main__" :   
508    test()
Note: See TracBrowser for help on using the browser.