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

Revision 255, 22.0 kB (checked in by jerome, 19 years ago)

Improved PCL3/4/5 parser.

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