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

Revision 235, 17.2 kB (checked in by jerome, 19 years ago)

Finished to move files around.
Removed any unneeded reference to the library's name.

  • 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
29
30class Parser(pdlparser.PDLParser) :
31    """A parser for PCL3, PCL4, PCL5 documents."""
32    mediasizes = {  # ESC&l####A
33                    0 : "Default",
34                    1 : "Executive",
35                    2 : "Letter",
36                    3 : "Legal",
37                    6 : "Ledger", 
38                    25 : "A5",
39                    26 : "A4",
40                    27 : "A3",
41                    45 : "JB5",
42                    46 : "JB4",
43                    71 : "HagakiPostcard",
44                    72 : "OufukuHagakiPostcard",
45                    80 : "MonarchEnvelope",
46                    81 : "COM10Envelope",
47                    90 : "DLEnvelope",
48                    91 : "C5Envelope",
49                    100 : "B5Envelope",
50                    101 : "Custom",
51                 }   
52                 
53    mediasources = { # ESC&l####H
54                     0 : "Default",
55                     1 : "Main",
56                     2 : "Manual",
57                     3 : "ManualEnvelope",
58                     4 : "Alternate",
59                     5 : "OptionalLarge",
60                     6 : "EnvelopeFeeder",
61                     7 : "Auto",
62                     8 : "Tray1",
63                   }
64                   
65    orientations = { # ESC&l####O
66                     0 : "Portrait",
67                     1 : "Landscape",
68                     2 : "ReversePortrait",
69                     3 : "ReverseLandscape",
70                   }
71                   
72    mediatypes = { # ESC&l####M
73                     0 : "Plain",
74                     1 : "Bond",
75                     2 : "Special",
76                     3 : "Glossy",
77                     4 : "Transparent",
78                   }
79       
80    def isValid(self) :   
81        """Returns 1 if data is PCL, else 0."""
82        if self.firstblock.startswith("\033E\033") or \
83           (self.firstblock.startswith("\033*rbC") and (not self.lastblock[-3:] == "\f\033@")) or \
84           self.firstblock.startswith("\033%8\033") or \
85           (self.firstblock.find("\033%-12345X") != -1) :
86            if self.debug : 
87                sys.stderr.write("DEBUG: Input file is in the PCL3/4/5 format.\n")
88            return 1
89        else :   
90            return 0
91       
92    def setPageDict(self, pages, number, attribute, value) :
93        """Initializes a page dictionnary."""
94        dict = pages.setdefault(number, { "copies" : 1, "mediasource" : "Main", "mediasize" : "Default", "mediatype" : "Plain", "orientation" : "Portrait"})
95        dict[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        pages = {}
140        pos = 0
141        try :
142            while 1 :
143                char = minfile[pos] ; pos += 1
144                if char == "\014" :   
145                    pagecount += 1
146                elif char == "\033" :   
147                    starb = ampl = 0
148                    #
149                    #     <ESC>*b###y#m###v###w... -> PCL3 raster graphics
150                    #     <ESC>*b###W -> Start of a raster data row/block
151                    #     <ESC>*b###V -> Start of a raster data plane
152                    #     <ESC>*c###W -> Start of a user defined pattern
153                    #     <ESC>*i###W -> Start of a viewing illuminant block
154                    #     <ESC>*l###W -> Start of a color lookup table
155                    #     <ESC>*m###W -> Start of a download dither matrix block
156                    #     <ESC>*v###W -> Start of a configure image data block
157                    #     <ESC>*r1A -> Start Gfx
158                    #     <ESC>(s###W -> Start of a characters description block
159                    #     <ESC>)s###W -> Start of a fonts description block
160                    #     <ESC>(f###W -> Start of a symbol set block
161                    #     <ESC>&b###W -> Start of configuration data block
162                    #     <ESC>&l###X -> Number of copies for current page
163                    #     <ESC>&n###W -> Starts an alphanumeric string ID block
164                    #     <ESC>&p###X -> Start of a non printable characters block
165                    #     <ESC>&a2G -> Back side when duplex mode as generated by rastertohp
166                    #     <ESC>*g###W -> Needed for planes in PCL3 output
167                    #     <ESC>&l###H (or only 0 ?) -> Eject if NumPlanes > 1, as generated by rastertohp. Also defines mediasource
168                    #     <ESC>&l###A -> mediasize
169                    #     <ESC>&l###O -> orientation
170                    #     <ESC>&l###M -> mediatype
171                    #     <ESC>*t###R -> gfx resolution
172                    #
173                    tagstart = minfile[pos] ; pos += 1
174                    if tagstart in "E9=YZ" : # one byte PCL tag
175                        if tagstart == "E" :
176                            resets += 1
177                        continue             # skip to next tag
178                    tag = tagstart + minfile[pos] ; pos += 1
179                    if tag == "*b" : 
180                        starb = 1
181                        tagend = "VW"
182                    elif tag == "&l" :   
183                        ampl = 1
184                        tagend = "XHAOM"
185                    else :   
186                        try :
187                            tagend = tagsends[tag]
188                        except KeyError :   
189                            continue # Unsupported PCL tag
190                    # Now read the numeric argument
191                    size = 0
192                    while 1 :
193                        char = minfile[pos] ; pos += 1
194                        if not char.isdigit() :
195                            break
196                        size = (size * 10) + int(char)   
197                    if char in tagend :   
198                        if tag == "&l" :
199                            if char == "X" : 
200                                self.setPageDict(pages, pagecount, "copies", size)
201                            elif char == "H" :
202                                self.setPageDict(pages, pagecount, "mediasource", self.mediasources.get(size, str(size)))
203                                mediasourcecount += 1
204                                ejects += 1 
205                            elif char == "A" :
206                                self.setPageDict(pages, pagecount, "mediasize", self.mediasizes.get(size, str(size)))
207                                mediasizecount += 1
208                            elif char == "O" :
209                                self.setPageDict(pages, pagecount, "orientation", self.orientations.get(size, str(size)))
210                                orientationcount += 1
211                            elif char == "M" :
212                                self.setPageDict(pages, pagecount, "mediatype", self.mediatypes.get(size, str(size)))
213                                mediatypecount += 1
214                        elif tag == "*r" :
215                            # Special tests for PCL3
216                            if (char == "s") and size :
217                                while 1 :
218                                    char = minfile[pos] ; pos += 1
219                                    if char == "A" :
220                                        break
221                            elif (char == "b") and (minfile[pos] == "C") and not size :
222                                ispcl3 = 1 # Certainely a PCL3 file
223                            startgfx += (char == "A") and (minfile[pos - 2] in ("0", "1", "2", "3")) # Start Gfx
224                            endgfx += (not size) and (char in ("C", "B")) # End Gfx
225                        elif tag == "*t" :   
226                            escstart += 1
227                        elif (tag == "&a") and (size == 2) :
228                            backsides += 1      # Back side in duplex mode
229                        else :   
230                            # we just ignore the block.
231                            if tag == "&n" : 
232                                # we have to take care of the operation id byte
233                                # which is before the string itself
234                                size += 1
235                            pos += size   
236                else :                           
237                    if starb :
238                        # special handling of PCL3 in which
239                        # *b introduces combined ESCape sequences
240                        size = 0
241                        while 1 :
242                            char = minfile[pos] ; pos += 1
243                            if not char.isdigit() :
244                                break
245                            size = (size * 10) + int(char)   
246                        if char in ("w", "v") :   
247                            ispcl3 = 1  # certainely a PCL3 document
248                            pos += size - 1
249                        elif char in ("y", "m") :   
250                            ispcl3 = 1  # certainely a PCL3 document
251                            pos -= 1    # fix position : we were ahead
252                    elif ampl :       
253                        # special handling of PCL3 in which
254                        # &l introduces combined ESCape sequences
255                        size = 0
256                        while 1 :
257                            char = minfile[pos] ; pos += 1
258                            if not char.isdigit() :
259                                break
260                            size = (size * 10) + int(char)   
261                        if char in ("a", "o", "h", "m") :   
262                            ispcl3 = 1  # certainely a PCL3 document
263                            pos -= 1    # fix position : we were ahead
264                            if char == "h" :
265                                self.setPageDict(pages, pagecount, "mediasource", self.mediasources.get(size, str(size)))
266                                mediasourcecount += 1
267                            elif char == "a" :
268                                self.setPageDict(pages, pagecount, "mediasize", self.mediasizes.get(size, str(size)))
269                                mediasizecount += 1
270                            elif char == "o" :
271                                self.setPageDict(pages, pagecount, "orientation", self.orientations.get(size, str(size)))
272                                orientationcount += 1
273                            elif char == "m" :
274                                self.setPageDict(pages, pagecount, "mediatype", self.mediatypes.get(size, str(size)))
275                                mediatypecount += 1
276        except IndexError : # EOF ?
277            minfile.close() # reached EOF
278                           
279        # if pagecount is still 0, we will use the number
280        # of resets instead of the number of form feed characters.
281        # but the number of resets is always at least 2 with a valid
282        # pcl file : one at the very start and one at the very end
283        # of the job's data. So we substract 2 from the number of
284        # resets. And since on our test data we needed to substract
285        # 1 more, we finally substract 3, and will test several
286        # PCL files with this. If resets < 2, then the file is
287        # probably not a valid PCL file, so we use 0
288       
289        if self.debug :
290            sys.stderr.write("pagecount : %s\n" % pagecount)
291            sys.stderr.write("resets : %s\n" % resets)
292            sys.stderr.write("ejects : %s\n" % ejects)
293            sys.stderr.write("backsides : %s\n" % backsides)
294            sys.stderr.write("startgfx : %s\n" % startgfx)
295            sys.stderr.write("endgfx : %s\n" % endgfx)
296            sys.stderr.write("mediasourcecount : %s\n" % mediasourcecount)
297            sys.stderr.write("mediasizecount : %s\n" % mediasizecount)
298            sys.stderr.write("orientationcount : %s\n" % orientationcount)
299            sys.stderr.write("mediatypecount : %s\n" % mediatypecount)
300            sys.stderr.write("escstart : %s\n" % escstart)
301       
302#        if not pagecount :
303#            pagecount = (pagecount or ((resets - 3) * (resets > 2)))
304#        else :   
305#            # here we add counters for other ways new pages may have
306#            # been printed and ejected by the printer
307#            pagecount += ejects + backsides
308#       
309#        # now handle number of copies for each page (may differ).
310#        # in duplex mode, number of copies may be sent only once.
311#        for pnum in range(pagecount) :
312#            # if no number of copies defined, take the preceding one else the one set before any page else 1.
313#            page = pages.get(pnum, pages.get(pnum - 1, pages.get(0, { "copies" : 1 })))
314#            pagecount += (page["copies"] - 1)
315#           
316#        # in PCL3 files, there's one Start Gfx tag per page
317#        if ispcl3 :
318#            if endgfx == int(startgfx / 2) : # special case for cdj1600
319#                pagecount = endgfx
320#            elif startgfx :
321#                pagecount = startgfx
322#            elif endgfx :   
323#                pagecount = endgfx
324               
325           
326        if pagecount == mediasourcecount == escstart : 
327            pass        # should be OK.
328        elif (not startgfx) and (not endgfx) :
329            pagecount = ejects or pagecount
330        elif startgfx == endgfx :   
331            pagecount = startgfx
332        elif startgfx == (endgfx - 1) :   
333            pagecount = startgfx
334        elif (startgfx == 1) and not endgfx :   
335            pass
336        else :   
337            pagecount = abs(startgfx - endgfx)
338           
339        if self.debug :       
340            for pnum in range(pagecount) :
341                # if no number of copies defined, take the preceding one else the one set before any page else 1.
342                page = pages.get(pnum, pages.get(pnum - 1, pages.get(0, { "copies" : 1, "mediasource" : "Main", "mediasize" : "Default", "mediatype" : "Plain", "orientation" : "Portrait"})))
343                sys.stderr.write("%s*%s*%s*%s*%s\n" % (page["copies"], page["mediatype"], page["mediasize"], page["orientation"], page["mediasource"]))
344               
345        return pagecount
346       
347def test() :       
348    """Test function."""
349    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
350        sys.argv.append("-")
351    totalsize = 0   
352    for arg in sys.argv[1:] :
353        if arg == "-" :
354            infile = sys.stdin
355            mustclose = 0
356        else :   
357            infile = open(arg, "rb")
358            mustclose = 1
359        try :
360            parser = Parser(infile, debug=1)
361            totalsize += parser.getJobSize()
362        except pdlparser.PDLParserError, msg :   
363            sys.stderr.write("ERROR: %s\n" % msg)
364            sys.stderr.flush()
365        if mustclose :   
366            infile.close()
367    print "%s" % totalsize
368   
369if __name__ == "__main__" :   
370    test()
Note: See TracBrowser for help on using the browser.