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

Revision 205, 13.6 kB (checked in by jerome, 19 years ago)

PCLXL parser now seems to correctly detect color/gray mode

  • 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        minfile = self.minfile
126        if (ord(minfile[pos-3]) == 0xf8) and (ord(minfile[pos-2]) == 0x31) :
127            # The EndPage operator may be preceded by a PageCopies attribute
128            # So set number of copies for current page.
129            # From what I read in PCLXL documentation, the number
130            # of copies is an unsigned 16 bits integer
131            self.pages[self.pagecount]["copies"] = unpack(self.endianness + "H", minfile[pos-5:pos-3])[0]
132        return 0
133       
134    def setColorSpace(self) :   
135        """Changes the color space."""
136        if self.minfile[self.pos-4:self.pos-1] == (chr(0x02) + chr(0xf8) + chr(0x03)) : 
137            self.isColor = 1
138        return 0
139           
140    def array_8(self) :   
141        """Handles byte arrays."""
142        pos = self.pos
143        datatype = self.minfile[pos]
144        pos += 1
145        length = self.tags[ord(datatype)]
146        if callable(length) :
147            self.pos = pos
148            length = length()
149            pos = self.pos
150        posl = pos + length
151        self.pos = posl
152        if length == 1 :   
153            return unpack("B", self.minfile[pos:posl])[0]
154        elif length == 2 :   
155            return unpack(self.endianness + "H", self.minfile[pos:posl])[0]
156        elif length == 4 :   
157            return unpack(self.endianness + "I", self.minfile[pos:posl])[0]
158        else :   
159            raise pdlparser.PDLParserError, "Error on array size at %s" % self.pos
160       
161    def array_16(self) :   
162        """Handles byte arrays."""
163        pos = self.pos
164        datatype = self.minfile[pos]
165        pos += 1
166        length = self.tags[ord(datatype)]
167        if callable(length) :
168            self.pos = pos
169            length = length()
170            pos = self.pos
171        posl = pos + length
172        self.pos = posl
173        if length == 1 :   
174            return 2 * unpack("B", self.minfile[pos:posl])[0]
175        elif length == 2 :   
176            return 2 * unpack(self.endianness + "H", self.minfile[pos:posl])[0]
177        elif length == 4 :   
178            return 2 * unpack(self.endianness + "I", self.minfile[pos:posl])[0]
179        else :   
180            raise pdlparser.PDLParserError, "Error on array size at %s" % self.pos
181       
182    def array_32(self) :   
183        """Handles byte arrays."""
184        pos = self.pos
185        datatype = self.minfile[pos]
186        pos += 1
187        length = self.tags[ord(datatype)]
188        if callable(length) :
189            self.pos = pos
190            length = length()
191            pos = self.pos
192        posl = pos + length
193        self.pos = posl
194        if length == 1 :   
195            return 4 * unpack("B", self.minfile[pos:posl])[0]
196        elif length == 2 :   
197            return 4 * unpack(self.endianness + "H", self.minfile[pos:posl])[0]
198        elif length == 4 :   
199            return 4 * unpack(self.endianness + "I", self.minfile[pos:posl])[0]
200        else :   
201            raise pdlparser.PDLParserError, "Error on array size at %s" % self.pos
202       
203    def embeddedDataSmall(self) :
204        """Handle small amounts of data."""
205        pos = self.pos
206        length = ord(self.minfile[pos])
207        self.pos = pos + 1
208        return length
209       
210    def embeddedData(self) :
211        """Handle normal amounts of data."""
212        pos = self.pos
213        pos4 = pos + 4
214        self.pos = pos4
215        return unpack(self.endianness + "I", self.minfile[pos:pos4])[0]
216       
217    def littleEndian(self) :       
218        """Toggles to little endianness."""
219        self.endianness = "<" # little endian
220        return 0
221       
222    def bigEndian(self) :   
223        """Toggles to big endianness."""
224        self.endianness = ">" # big endian
225        return 0
226   
227    def getJobSize(self) :
228        """Counts pages in a PCLXL (PCL6) document.
229       
230           Algorithm by Jerome Alet.
231           
232           The documentation used for this was :
233         
234           HP PCL XL Feature Reference
235           Protocol Class 2.0
236           http://www.hpdevelopersolutions.com/downloads/64/358/xl_ref20r22.pdf
237        """
238        self.isColor = None
239        self.endianness = None
240        found = 0
241        while not found :
242            line = self.infile.readline()
243            if not line :
244                break
245            if line[1:12] == " HP-PCL XL;" :
246                found = 1
247                endian = ord(line[0])
248                if endian == 0x29 :
249                    self.littleEndian()
250                elif endian == 0x28 :   
251                    self.bigEndian()
252                # elif endian == 0x27 : # TODO : This is the ESC code : parse it for PJL statements !
253                #
254                else :   
255                    raise pdlparser.PDLParserError, "Unknown endianness marker 0x%02x at start !" % endian
256        if not found :
257            raise pdlparser.PDLParserError, "This file doesn't seem to be PCLXL (aka PCL6)"
258           
259        # Initialize table of tags
260        self.tags = [ 0 ] * 256   
261       
262        # GhostScript's sources tell us that HP printers
263        # only accept little endianness, but we can handle both.
264        self.tags[0x28] = self.bigEndian    # BigEndian
265        self.tags[0x29] = self.littleEndian # LittleEndian
266       
267        self.tags[0x43] = self.beginPage    # BeginPage
268        self.tags[0x44] = self.endPage      # EndPage
269       
270        self.tags[0x6a] = self.setColorSpace
271       
272        self.tags[0xc0] = 1 # ubyte
273        self.tags[0xc1] = 2 # uint16
274        self.tags[0xc2] = 4 # uint32
275        self.tags[0xc3] = 2 # sint16
276        self.tags[0xc4] = 4 # sint32
277        self.tags[0xc5] = 4 # real32
278       
279        self.tags[0xc8] = self.array_8  # ubyte_array
280        self.tags[0xc9] = self.array_16 # uint16_array
281        self.tags[0xca] = self.array_32 # uint32_array
282        self.tags[0xcb] = self.array_16 # sint16_array
283        self.tags[0xcc] = self.array_32 # sint32_array
284        self.tags[0xcd] = self.array_32 # real32_array
285       
286        self.tags[0xd0] = 2 # ubyte_xy
287        self.tags[0xd1] = 4 # uint16_xy
288        self.tags[0xd2] = 8 # uint32_xy
289        self.tags[0xd3] = 4 # sint16_xy
290        self.tags[0xd4] = 8 # sint32_xy
291        self.tags[0xd5] = 8 # real32_xy
292       
293        self.tags[0xe0] = 4  # ubyte_box
294        self.tags[0xe1] = 8  # uint16_box
295        self.tags[0xe2] = 16 # uint32_box
296        self.tags[0xe3] = 8  # sint16_box
297        self.tags[0xe4] = 16 # sint32_box
298        self.tags[0xe5] = 16 # real32_box
299       
300        self.tags[0xf8] = 1 # attr_ubyte
301        self.tags[0xf9] = 2 # attr_uint16
302       
303        self.tags[0xfa] = self.embeddedData      # dataLength
304        self.tags[0xfb] = self.embeddedDataSmall # dataLengthByte
305           
306        infileno = self.infile.fileno()
307        self.pages = {}
308        self.minfile = minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
309        tags = self.tags
310        self.pagecount = 0
311        self.pos = pos = self.infile.tell()
312        try :
313            while 1 :
314                char = minfile[pos]
315                pos += 1
316                length = tags[ord(char)]
317                if not length :
318                    continue
319                if callable(length) :   
320                    self.pos = pos
321                    length = length()
322                    pos = self.pos
323                pos += length   
324        except IndexError : # EOF ?
325            self.minfile.close() # reached EOF
326           
327        # now handle number of copies for each page (may differ).
328        if self.debug :
329            sys.stderr.write("Color mode : %s\n" % self.isColor)
330        for pnum in range(1, self.pagecount + 1) :
331            # if no number of copies defined, take 1, as explained
332            # in PCLXL documentation.
333            # NB : is number of copies is 0, the page won't be output
334            # but the formula below is still correct : we want
335            # to decrease the total number of pages in this case.
336            page = self.pages.get(pnum, 1)
337            copies = page["copies"]
338            self.pagecount += (copies - 1)
339            if self.debug :
340                sys.stderr.write("%s*%s*%s*%s*%s\n" % (copies, page["mediatype"], page["mediasize"], page["orientation"], page["mediasource"]))
341           
342        return self.pagecount
343       
344def test() :       
345    """Test function."""
346    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
347        sys.argv.append("-")
348    totalsize = 0   
349    for arg in sys.argv[1:] :
350        if arg == "-" :
351            infile = sys.stdin
352            mustclose = 0
353        else :   
354            infile = open(arg, "rb")
355            mustclose = 1
356        try :
357            parser = PCLXLParser(infile, debug=1)
358            totalsize += parser.getJobSize()
359        except pdlparser.PDLParserError, msg :   
360            sys.stderr.write("ERROR: %s\n" % msg)
361            sys.stderr.flush()
362        if mustclose :   
363            infile.close()
364    print "%s" % totalsize
365   
366if __name__ == "__main__" :   
367    test()
Note: See TracBrowser for help on using the browser.