root / pkpgcounter / trunk / pdlanalyzer / pclxl.py @ 207

Revision 207, 14.3 kB (checked in by jerome, 19 years ago)

Improved readability

  • 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20#
21# $Id$
22#
23
24import sys
25import os
26import mmap
27from struct import unpack
28
29from pdlanalyzer import pdlparser
30
31class PCLXLParser(pdlparser.PDLParser) :
32    """A parser for PCLXL (aka PCL6) documents."""
33    mediasizes = { 
34                    0 : "Letter",
35                    1 : "Legal",
36                    2 : "A4",
37                    3 : "Executive",
38                    4 : "Ledger",
39                    5 : "A3",
40                    6 : "COM10Envelope",
41                    7 : "MonarchEnvelope",
42                    8 : "C5Envelope",
43                    9 : "DLEnvelope",
44                    10 : "JB4",
45                    11 : "JB5",
46                    12 : "B5Envelope",
47                    14 : "JPostcard",
48                    15 : "JDoublePostcard",
49                    16 : "A5",
50                    17 : "A6",
51                    18 : "JB6",
52                 }   
53                 
54    mediasources = {             
55                     0 : "Default",
56                     1 : "Auto",
57                     2 : "Manual",
58                     3 : "MultiPurpose",
59                     4 : "UpperCassette",
60                     5 : "LowerCassette",
61                     6 : "EnvelopeTray",
62                     7 : "ThirdCassette",
63                   }
64                   
65    orientations = {               
66                     0 : "Portrait",
67                     1 : "Landscape",
68                     2 : "ReversePortrait",
69                     3 : "ReverseLandscape",
70                   }
71           
72    def beginPage(self) :
73        """Indicates the beginning of a new page, and extracts media information."""
74        self.pagecount += 1
75       
76        # Default values
77        mediatypelabel = "Plain"
78        mediasourcelabel = "Main"
79        mediasizelabel = "Default"
80        orientationlabel = "Portrait"
81       
82        # Now go upstream to decode media type, size, source, and orientation
83        # this saves time because we don't need a complete parser !
84        minfile = self.minfile
85        pos = self.pos - 2
86        while pos > 0 : # safety check : don't go back to far !
87            val = ord(minfile[pos])
88            if val in (0x44, 0x48, 0x41) : # if previous endPage or openDataSource or beginSession (first page)
89                break
90            if val == 0x26 :   
91                mediasource = ord(minfile[pos - 2])
92                mediasourcelabel = self.mediasources.get(mediasource, str(mediasource))
93                pos = pos - 4
94            elif val == 0x25 :
95                mediasize = ord(minfile[pos - 2])
96                mediasizelabel = self.mediasizes.get(mediasize, str(mediasize))
97                pos = pos - 4
98            elif val == 0x28 :   
99                orientation = ord(minfile[pos - 2])
100                orienationlabel = self.orientations.get(orientation, str(orientation))
101                pos = pos - 4
102            elif val == 0x27 :   
103                savepos = pos
104                pos = pos - 1
105                while pos > 0 : # safety check : don't go back to far !
106                    val = ord(minfile[pos])
107                    pos -= 1   
108                    if val == 0xc8 :
109                        break
110                mediatypelabel = minfile[pos:savepos] # TODO : INCORRECT, WE HAVE TO STRIP OUT THE UBYTE ARRAY'S LENGTH !!!
111            # else : TODO : CUSTOM MEDIA SIZE AND UNIT !
112            else :   
113                pos = pos - 2   # ignored
114        self.pages[self.pagecount] = { "copies" : 1, 
115                                       "orientation" : orientationlabel, 
116                                       "mediatype" : mediatypelabel, 
117                                       "mediasize" : mediasizelabel,
118                                       "mediasource" : mediasourcelabel,
119                                     } 
120        return 0
121       
122    def endPage(self) :   
123        """Indicates the end of a page."""
124        pos = self.pos
125        pos3 = pos - 3
126        minfile = self.minfile
127        if minfile[pos3:pos-1] == self.setNumberOfCopies :
128            # The EndPage operator may be preceded by a PageCopies attribute
129            # So set number of copies for current page.
130            # From what I read in PCLXL documentation, the number
131            # of copies is an unsigned 16 bits integer
132            self.pages[self.pagecount]["copies"] = unpack(self.endianness + "H", minfile[pos-5:pos3])[0]
133        return 0
134       
135    def setColorSpace(self) :   
136        """Changes the color space."""
137        if self.minfile[self.pos-4:self.pos-1] == self.RGBColorSpace :
138            self.iscolor = 1
139        return 0
140           
141    def array_8(self) :   
142        """Handles byte arrays."""
143        pos = self.pos
144        datatype = self.minfile[pos]
145        pos += 1
146        length = self.tags[ord(datatype)]
147        if callable(length) :
148            self.pos = pos
149            length = length()
150            pos = self.pos
151        posl = pos + length
152        self.pos = posl
153        if length == 1 :   
154            return unpack("B", self.minfile[pos:posl])[0]
155        elif length == 2 :   
156            return unpack(self.endianness + "H", self.minfile[pos:posl])[0]
157        elif length == 4 :   
158            return unpack(self.endianness + "I", self.minfile[pos:posl])[0]
159        else :   
160            raise pdlparser.PDLParserError, "Error on array size at %s" % self.pos
161       
162    def array_16(self) :   
163        """Handles byte arrays."""
164        pos = self.pos
165        datatype = self.minfile[pos]
166        pos += 1
167        length = self.tags[ord(datatype)]
168        if callable(length) :
169            self.pos = pos
170            length = length()
171            pos = self.pos
172        posl = pos + length
173        self.pos = posl
174        if length == 1 :   
175            return 2 * unpack("B", self.minfile[pos:posl])[0]
176        elif length == 2 :   
177            return 2 * unpack(self.endianness + "H", self.minfile[pos:posl])[0]
178        elif length == 4 :   
179            return 2 * unpack(self.endianness + "I", self.minfile[pos:posl])[0]
180        else :   
181            raise pdlparser.PDLParserError, "Error on array size at %s" % self.pos
182       
183    def array_32(self) :   
184        """Handles byte arrays."""
185        pos = self.pos
186        datatype = self.minfile[pos]
187        pos += 1
188        length = self.tags[ord(datatype)]
189        if callable(length) :
190            self.pos = pos
191            length = length()
192            pos = self.pos
193        posl = pos + length
194        self.pos = posl
195        if length == 1 :   
196            return 4 * unpack("B", self.minfile[pos:posl])[0]
197        elif length == 2 :   
198            return 4 * unpack(self.endianness + "H", self.minfile[pos:posl])[0]
199        elif length == 4 :   
200            return 4 * unpack(self.endianness + "I", self.minfile[pos:posl])[0]
201        else :   
202            raise pdlparser.PDLParserError, "Error on array size at %s" % self.pos
203       
204    def embeddedDataSmall(self) :
205        """Handle small amounts of data."""
206        pos = self.pos
207        length = ord(self.minfile[pos])
208        self.pos = pos + 1
209        return length
210       
211    def embeddedData(self) :
212        """Handle normal amounts of data."""
213        pos = self.pos
214        pos4 = pos + 4
215        self.pos = pos4
216        return unpack(self.endianness + "I", self.minfile[pos:pos4])[0]
217       
218    def littleEndian(self) :       
219        """Toggles to little endianness."""
220        self.endianness = "<" # little endian
221        return 0
222       
223    def bigEndian(self) :   
224        """Toggles to big endianness."""
225        self.endianness = ">" # big endian
226        return 0
227   
228    def getJobSize(self) :
229        """Counts pages in a PCLXL (PCL6) document.
230       
231           Algorithm by Jerome Alet.
232           
233           The documentation used for this was :
234         
235           HP PCL XL Feature Reference
236           Protocol Class 2.0
237           http://www.hpdevelopersolutions.com/downloads/64/358/xl_ref20r22.pdf
238        """
239        self.iscolor = None
240        self.endianness = None
241        found = 0
242        while not found :
243            line = self.infile.readline()
244            if not line :
245                break
246            if line[1:12] == " HP-PCL XL;" :
247                found = 1
248                endian = ord(line[0])
249                if endian == 0x29 :
250                    self.littleEndian()
251                elif endian == 0x28 :   
252                    self.bigEndian()
253                # elif endian == 0x27 : # TODO : This is the ESC code : parse it for PJL statements !
254                #
255                else :   
256                    raise pdlparser.PDLParserError, "Unknown endianness marker 0x%02x at start !" % endian
257        if not found :
258            raise pdlparser.PDLParserError, "This file doesn't seem to be PCLXL (aka PCL6)"
259           
260        # Initialize table of tags
261        self.tags = [ 0 ] * 256   
262       
263        # GhostScript's sources tell us that HP printers
264        # only accept little endianness, but we can handle both.
265        self.tags[0x28] = self.bigEndian    # BigEndian
266        self.tags[0x29] = self.littleEndian # LittleEndian
267       
268        self.tags[0x43] = self.beginPage    # BeginPage
269        self.tags[0x44] = self.endPage      # EndPage
270       
271        self.tags[0x6a] = self.setColorSpace    # to detect color/b&w mode
272       
273        self.tags[0xc0] = 1 # ubyte
274        self.tags[0xc1] = 2 # uint16
275        self.tags[0xc2] = 4 # uint32
276        self.tags[0xc3] = 2 # sint16
277        self.tags[0xc4] = 4 # sint32
278        self.tags[0xc5] = 4 # real32
279       
280        self.tags[0xc8] = self.array_8  # ubyte_array
281        self.tags[0xc9] = self.array_16 # uint16_array
282        self.tags[0xca] = self.array_32 # uint32_array
283        self.tags[0xcb] = self.array_16 # sint16_array
284        self.tags[0xcc] = self.array_32 # sint32_array
285        self.tags[0xcd] = self.array_32 # real32_array
286       
287        self.tags[0xd0] = 2 # ubyte_xy
288        self.tags[0xd1] = 4 # uint16_xy
289        self.tags[0xd2] = 8 # uint32_xy
290        self.tags[0xd3] = 4 # sint16_xy
291        self.tags[0xd4] = 8 # sint32_xy
292        self.tags[0xd5] = 8 # real32_xy
293       
294        self.tags[0xe0] = 4  # ubyte_box
295        self.tags[0xe1] = 8  # uint16_box
296        self.tags[0xe2] = 16 # uint32_box
297        self.tags[0xe3] = 8  # sint16_box
298        self.tags[0xe4] = 16 # sint32_box
299        self.tags[0xe5] = 16 # real32_box
300       
301        self.tags[0xf8] = 1 # attr_ubyte
302        self.tags[0xf9] = 2 # attr_uint16
303       
304        self.tags[0xfa] = self.embeddedData      # dataLength
305        self.tags[0xfb] = self.embeddedDataSmall # dataLengthByte
306           
307        # color spaces   
308        self.BWColorSpace = "".join([chr(0x00), chr(0xf8), chr(0x03)])
309        self.GrayColorSpace = "".join([chr(0x01), chr(0xf8), chr(0x03)])
310        self.RGBColorSpace = "".join([chr(0x02), chr(0xf8), chr(0x03)])
311       
312        # set number of copies
313        self.setNumberOfCopies = "".join([chr(0xf8), chr(0x31)]) 
314       
315        infileno = self.infile.fileno()
316        self.pages = {}
317        self.minfile = minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
318        tags = self.tags
319        self.pagecount = 0
320        self.pos = pos = self.infile.tell()
321        try :
322            while 1 :
323                char = minfile[pos]
324                pos += 1
325                length = tags[ord(char)]
326                if not length :
327                    continue
328                if callable(length) :   
329                    self.pos = pos
330                    length = length()
331                    pos = self.pos
332                pos += length   
333        except IndexError : # EOF ?
334            self.minfile.close() # reached EOF
335           
336        # now handle number of copies for each page (may differ).
337        if self.iscolor :
338            colormode = "Color"
339        else :   
340            colormode = "Black"
341        for pnum in range(1, self.pagecount + 1) :
342            # if no number of copies defined, take 1, as explained
343            # in PCLXL documentation.
344            # NB : is number of copies is 0, the page won't be output
345            # but the formula below is still correct : we want
346            # to decrease the total number of pages in this case.
347            page = self.pages.get(pnum, 1)
348            copies = page["copies"]
349            self.pagecount += (copies - 1)
350            if self.debug :
351                sys.stderr.write("%s*%s*%s*%s*%s*%s\n" % (copies, 
352                                                          page["mediatype"], 
353                                                          page["mediasize"], 
354                                                          page["orientation"], 
355                                                          page["mediasource"], 
356                                                          colormode))
357           
358        return self.pagecount
359       
360def test() :       
361    """Test function."""
362    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
363        sys.argv.append("-")
364    totalsize = 0   
365    for arg in sys.argv[1:] :
366        if arg == "-" :
367            infile = sys.stdin
368            mustclose = 0
369        else :   
370            infile = open(arg, "rb")
371            mustclose = 1
372        try :
373            parser = PCLXLParser(infile, debug=1)
374            totalsize += parser.getJobSize()
375        except pdlparser.PDLParserError, msg :   
376            sys.stderr.write("ERROR: %s\n" % msg)
377            sys.stderr.flush()
378        if mustclose :   
379            infile.close()
380    print "%s" % totalsize
381   
382if __name__ == "__main__" :   
383    test()
Note: See TracBrowser for help on using the browser.