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

Revision 202, 13.2 kB (checked in by jerome, 19 years ago)

Seems to work fine now

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