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