[1482] | 1 | # PyKota |
---|
| 2 | # -*- coding: ISO-8859-15 -*- |
---|
| 3 | # |
---|
| 4 | # PyKota - Print Quotas for CUPS and LPRng |
---|
| 5 | # |
---|
| 6 | # (c) 2003-2004 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 | # $Log$ |
---|
[1568] | 24 | # Revision 1.14 2004/06/25 09:50:28 jalet |
---|
| 25 | # More debug info in PCLXL parser |
---|
| 26 | # |
---|
[1567] | 27 | # Revision 1.13 2004/06/25 08:10:08 jalet |
---|
| 28 | # Another fix for PCL5 parser |
---|
| 29 | # |
---|
[1566] | 30 | # Revision 1.12 2004/06/24 23:09:53 jalet |
---|
| 31 | # Fix for number of copies in PCL5 parser |
---|
| 32 | # |
---|
[1564] | 33 | # Revision 1.11 2004/06/23 22:07:50 jalet |
---|
| 34 | # Fixed PCL5 parser according to the sources of rastertohp |
---|
| 35 | # |
---|
[1553] | 36 | # Revision 1.10 2004/06/18 22:24:03 jalet |
---|
| 37 | # Removed old comments |
---|
| 38 | # |
---|
[1552] | 39 | # Revision 1.9 2004/06/18 22:21:27 jalet |
---|
| 40 | # Native PDF parser greatly improved. |
---|
| 41 | # GhostScript based PDF parser completely removed because native code |
---|
| 42 | # is now portable across Python versions. |
---|
| 43 | # |
---|
[1551] | 44 | # Revision 1.8 2004/06/18 20:49:46 jalet |
---|
| 45 | # "ERROR:" prefix added |
---|
| 46 | # |
---|
[1550] | 47 | # Revision 1.7 2004/06/18 17:48:04 jalet |
---|
| 48 | # Added native fast PDF parsing method |
---|
| 49 | # |
---|
[1547] | 50 | # Revision 1.6 2004/06/18 14:00:16 jalet |
---|
| 51 | # Added PDF support in smart PDL analyzer (through GhostScript for now) |
---|
| 52 | # |
---|
[1544] | 53 | # Revision 1.5 2004/06/18 10:09:05 jalet |
---|
| 54 | # Resets file pointer to start of file in all cases |
---|
| 55 | # |
---|
[1543] | 56 | # Revision 1.4 2004/06/18 06:16:14 jalet |
---|
| 57 | # Fixes PostScript detection code for incorrect drivers |
---|
| 58 | # |
---|
[1487] | 59 | # Revision 1.3 2004/05/21 20:40:08 jalet |
---|
| 60 | # All the code for pkpgcounter is now in pdlanalyzer.py |
---|
| 61 | # |
---|
[1485] | 62 | # Revision 1.2 2004/05/19 19:09:36 jalet |
---|
| 63 | # Speed improvement |
---|
| 64 | # |
---|
[1482] | 65 | # Revision 1.1 2004/05/18 09:59:54 jalet |
---|
| 66 | # pkpgcounter is now just a wrapper around the PDLAnalyzer class |
---|
| 67 | # |
---|
| 68 | # |
---|
| 69 | # |
---|
| 70 | |
---|
| 71 | import sys |
---|
[1547] | 72 | import os |
---|
[1552] | 73 | import re |
---|
[1482] | 74 | import struct |
---|
| 75 | import tempfile |
---|
[1547] | 76 | import popen2 |
---|
[1482] | 77 | |
---|
[1487] | 78 | KILOBYTE = 1024 |
---|
| 79 | MEGABYTE = 1024 * KILOBYTE |
---|
| 80 | |
---|
| 81 | class PDLAnalyzerError(Exception): |
---|
| 82 | """An exception for PDL Analyzer related stuff.""" |
---|
| 83 | def __init__(self, message = ""): |
---|
| 84 | self.message = message |
---|
| 85 | Exception.__init__(self, message) |
---|
| 86 | def __repr__(self): |
---|
| 87 | return self.message |
---|
| 88 | __str__ = __repr__ |
---|
| 89 | |
---|
[1482] | 90 | class PostScriptAnalyzer : |
---|
| 91 | def __init__(self, infile) : |
---|
| 92 | """Initialize PostScript Analyzer.""" |
---|
| 93 | self.infile = infile |
---|
| 94 | |
---|
| 95 | def getJobSize(self) : |
---|
| 96 | """Count pages in a DSC compliant PostScript document.""" |
---|
| 97 | pagecount = 0 |
---|
[1552] | 98 | for line in self.infile.xreadlines() : |
---|
[1482] | 99 | if line.startswith("%%Page: ") : |
---|
| 100 | pagecount += 1 |
---|
| 101 | return pagecount |
---|
| 102 | |
---|
[1547] | 103 | class PDFAnalyzer : |
---|
| 104 | def __init__(self, infile) : |
---|
| 105 | """Initialize PDF Analyzer.""" |
---|
| 106 | self.infile = infile |
---|
[1550] | 107 | |
---|
[1552] | 108 | def getJobSize(self) : |
---|
| 109 | """Counts pages in a PDF document.""" |
---|
| 110 | regexp = re.compile(r"(/Type) ?(/Page)[/ \r\n]") |
---|
[1550] | 111 | pagecount = 0 |
---|
[1552] | 112 | for line in self.infile.xreadlines() : |
---|
| 113 | pagecount += len(regexp.findall(line)) |
---|
[1550] | 114 | return pagecount |
---|
[1547] | 115 | |
---|
[1482] | 116 | class PCLAnalyzer : |
---|
| 117 | def __init__(self, infile) : |
---|
| 118 | """Initialize PCL Analyzer.""" |
---|
| 119 | self.infile = infile |
---|
| 120 | |
---|
[1485] | 121 | def skip(self, nb) : |
---|
| 122 | """Reads a new datablock.""" |
---|
| 123 | newpos = self.pos + nb |
---|
| 124 | if newpos >= self.len : |
---|
| 125 | oldlen = self.len |
---|
[1487] | 126 | self.data = self.infile.read(MEGABYTE) |
---|
[1485] | 127 | self.len = len(self.data) |
---|
| 128 | if not self.len : |
---|
| 129 | return |
---|
| 130 | self.pos = newpos - oldlen |
---|
| 131 | else : |
---|
| 132 | self.pos = newpos |
---|
| 133 | |
---|
| 134 | def readone(self) : |
---|
| 135 | """Reads a new byte.""" |
---|
| 136 | if self.pos < self.len : |
---|
| 137 | char = self.data[self.pos] |
---|
| 138 | else : |
---|
[1487] | 139 | self.data = self.infile.read(MEGABYTE) |
---|
[1485] | 140 | self.len = len(self.data) |
---|
| 141 | self.pos = 0 |
---|
| 142 | if not self.len : |
---|
| 143 | return |
---|
| 144 | char = self.data[0] |
---|
| 145 | self.pos += 1 |
---|
| 146 | return char |
---|
| 147 | |
---|
[1482] | 148 | def getJobSize(self) : |
---|
| 149 | """Count pages in a PCL5 document.""" |
---|
| 150 | # |
---|
| 151 | # Algorithm from pclcount |
---|
| 152 | # (c) 2003, by Eduardo Gielamo Oliveira & Rodolfo Broco Manin |
---|
| 153 | # published under the terms of the GNU General Public Licence v2. |
---|
| 154 | # |
---|
| 155 | # Backported from C to Python by Jerome Alet, then enhanced |
---|
| 156 | # with more PCL tags detected. I think all the necessary PCL tags |
---|
| 157 | # are recognized to correctly handle PCL5 files wrt their number |
---|
| 158 | # of pages. The documentation used for this was : |
---|
| 159 | # |
---|
| 160 | # HP PCL/PJL Reference Set |
---|
| 161 | # PCL5 Printer Language Technical Quick Reference Guide |
---|
| 162 | # http://h20000.www2.hp.com/bc/docs/support/SupportManual/bpl13205/bpl13205.pdf |
---|
| 163 | # |
---|
| 164 | tagsends = { "&n" : "W", |
---|
| 165 | "&b" : "W", |
---|
| 166 | "*i" : "W", |
---|
| 167 | "*l" : "W", |
---|
| 168 | "*m" : "W", |
---|
| 169 | "*v" : "W", |
---|
| 170 | "*c" : "W", |
---|
| 171 | "(f" : "W", |
---|
| 172 | "*b" : "VW", |
---|
| 173 | "(s" : "W", |
---|
| 174 | ")s" : "W", |
---|
| 175 | "&p" : "X", |
---|
[1564] | 176 | "&l" : "XH", |
---|
| 177 | "&a" : "G", |
---|
| 178 | } |
---|
[1485] | 179 | self.data = [] |
---|
| 180 | self.pos = self.len = 0 |
---|
[1567] | 181 | pagecount = resets = ejects = backsides = 0 |
---|
[1482] | 182 | tag = None |
---|
[1566] | 183 | copies = {} |
---|
[1482] | 184 | while 1 : |
---|
[1485] | 185 | char = self.readone() |
---|
[1482] | 186 | if not char : # EOF ? |
---|
| 187 | break |
---|
| 188 | if char == "\014" : |
---|
| 189 | pagecount += 1 |
---|
| 190 | elif char == "\033" : |
---|
| 191 | # |
---|
| 192 | # <ESC>*b###W -> Start of a raster data row/block |
---|
| 193 | # <ESC>*b###V -> Start of a raster data plane |
---|
| 194 | # <ESC>*c###W -> Start of a user defined pattern |
---|
| 195 | # <ESC>*i###W -> Start of a viewing illuminant block |
---|
| 196 | # <ESC>*l###W -> Start of a color lookup table |
---|
| 197 | # <ESC>*m###W -> Start of a download dither matrix block |
---|
| 198 | # <ESC>*v###W -> Start of a configure image data block |
---|
| 199 | # <ESC>(s###W -> Start of a characters description block |
---|
| 200 | # <ESC>)s###W -> Start of a fonts description block |
---|
| 201 | # <ESC>(f###W -> Start of a symbol set block |
---|
| 202 | # <ESC>&b###W -> Start of configuration data block |
---|
[1566] | 203 | # <ESC>&l###X -> Number of copies for current page |
---|
[1482] | 204 | # <ESC>&n###W -> Starts an alphanumeric string ID block |
---|
| 205 | # <ESC>&p###X -> Start of a non printable characters block |
---|
[1564] | 206 | # <ESC>&a2G -> Back side when duplex mode as generated by rastertohp |
---|
| 207 | # <ESC>&l0H -> Eject if NumPlanes > 1, as generated by rastertohp |
---|
[1482] | 208 | # |
---|
[1485] | 209 | tagstart = self.readone() |
---|
[1482] | 210 | if tagstart in "E9=YZ" : # one byte PCL tag |
---|
| 211 | if tagstart == "E" : |
---|
| 212 | resets += 1 |
---|
| 213 | continue # skip to next tag |
---|
[1485] | 214 | tag = tagstart + self.readone() |
---|
[1482] | 215 | try : |
---|
| 216 | tagend = tagsends[tag] |
---|
| 217 | except KeyError : |
---|
| 218 | pass # Unsupported PCL tag |
---|
| 219 | else : |
---|
| 220 | # Now read the numeric argument |
---|
| 221 | size = 0 |
---|
| 222 | while 1 : |
---|
[1485] | 223 | char = self.readone() |
---|
[1482] | 224 | if not char.isdigit() : |
---|
| 225 | break |
---|
| 226 | size = (size * 10) + int(char) |
---|
| 227 | if char in tagend : |
---|
[1566] | 228 | if (tag == "&l") and (char == "X") : # copies for current page |
---|
| 229 | copies[pagecount] = size |
---|
[1564] | 230 | elif (tag == "&l") and (char == "H") and (size == 0) : |
---|
[1567] | 231 | ejects += 1 # Eject |
---|
[1564] | 232 | elif (tag == "&a") and (size == 2) : |
---|
[1567] | 233 | backsides += 1 # Back side in duplex mode |
---|
[1482] | 234 | else : |
---|
| 235 | # doing a read will prevent the seek |
---|
| 236 | # for unseekable streams. |
---|
| 237 | # we just ignore the block anyway. |
---|
| 238 | if tag == "&n" : |
---|
| 239 | # we have to take care of the operation id byte |
---|
| 240 | # which is before the string itself |
---|
| 241 | size += 1 |
---|
[1485] | 242 | self.skip(size) |
---|
[1482] | 243 | |
---|
[1567] | 244 | # if pagecount is still 0, we will use the number |
---|
[1482] | 245 | # of resets instead of the number of form feed characters. |
---|
| 246 | # but the number of resets is always at least 2 with a valid |
---|
| 247 | # pcl file : one at the very start and one at the very end |
---|
| 248 | # of the job's data. So we substract 2 from the number of |
---|
| 249 | # resets. And since on our test data we needed to substract |
---|
| 250 | # 1 more, we finally substract 3, and will test several |
---|
| 251 | # PCL files with this. If resets < 2, then the file is |
---|
[1567] | 252 | # probably not a valid PCL file, so we use 0 |
---|
| 253 | if not pagecount : |
---|
| 254 | pagecount = (pagecount or ((resets - 3) * (resets > 2))) |
---|
| 255 | else : |
---|
| 256 | # here we add counters for other ways new pages may have |
---|
| 257 | # been printed and ejected by the printer |
---|
| 258 | pagecount += ejects + backsides |
---|
[1482] | 259 | |
---|
[1566] | 260 | # now handle number of copies for each page (may differ). |
---|
| 261 | # in duplex mode, number of copies may be sent only once. |
---|
| 262 | for pnum in range(pagecount) : |
---|
| 263 | # if no number of copies defined, take the preceding one else 1. |
---|
| 264 | nb = copies.get(pnum, copies.get(pnum-1, 1)) |
---|
| 265 | pagecount += (nb - 1) |
---|
| 266 | return pagecount |
---|
| 267 | |
---|
[1482] | 268 | class PCLXLAnalyzer : |
---|
| 269 | def __init__(self, infile) : |
---|
| 270 | """Initialize PCLXL Analyzer.""" |
---|
[1487] | 271 | raise PDLAnalyzerError, "PCLXL (aka PCL6) is not supported yet." |
---|
[1482] | 272 | self.infile = infile |
---|
| 273 | self.islittleendian = None |
---|
| 274 | found = 0 |
---|
| 275 | while not found : |
---|
| 276 | line = self.infile.readline() |
---|
| 277 | if not line : |
---|
| 278 | break |
---|
| 279 | if line[1:12] == " HP-PCL XL;" : |
---|
| 280 | found = 1 |
---|
| 281 | if line[0] == ")" : |
---|
| 282 | self.littleendian() |
---|
| 283 | elif line[0] == "(" : |
---|
| 284 | self.bigendian() |
---|
| 285 | if not found : |
---|
[1487] | 286 | raise PDLAnalyzerError, "This file doesn't seem to be PCLXL (aka PCL6)" |
---|
[1482] | 287 | else : |
---|
[1568] | 288 | self.tags = [ self.skipped ] * 256 |
---|
[1482] | 289 | self.tags[0x28] = self.bigendian # big endian |
---|
| 290 | self.tags[0x29] = self.littleendian # big endian |
---|
| 291 | self.tags[0x43] = self.beginPage # BeginPage |
---|
| 292 | self.tags[0x44] = self.endPage # EndPage |
---|
| 293 | |
---|
[1568] | 294 | self.tags[0xc0] = lambda: self.debug("%08x : ubyte" % self.infile.tell()) or 1 # ubyte |
---|
| 295 | self.tags[0xc1] = lambda: self.debug("%08x : uint16" % self.infile.tell()) or 2 # uint16 |
---|
| 296 | self.tags[0xc2] = lambda: self.debug("%08x : uint32" % self.infile.tell()) or 4 # uint32 |
---|
| 297 | self.tags[0xc3] = lambda: self.debug("%08x : sint16" % self.infile.tell()) or 2 # sint16 |
---|
| 298 | self.tags[0xc4] = lambda: self.debug("%08x : sint32" % self.infile.tell()) or 4 # sint32 |
---|
| 299 | self.tags[0xc5] = lambda: self.debug("%08x : real32" % self.infile.tell()) or 4 # real32 |
---|
[1482] | 300 | |
---|
| 301 | self.tags[0xc8] = self.array_8 # ubyte_array |
---|
| 302 | self.tags[0xc9] = self.array_16 # uint16_array |
---|
| 303 | self.tags[0xca] = self.array_32 # uint32_array |
---|
| 304 | self.tags[0xcb] = self.array_16 # sint16_array |
---|
| 305 | self.tags[0xcc] = self.array_32 # sint32_array |
---|
| 306 | self.tags[0xcd] = self.array_32 # real32_array |
---|
| 307 | |
---|
[1568] | 308 | self.tags[0xd0] = lambda: self.debug("%08x : ubyte_xy" % self.infile.tell()) or 2 # ubyte_xy |
---|
| 309 | self.tags[0xd1] = lambda: self.debug("%08x : uint16_xy" % self.infile.tell()) or 4 # uint16_xy |
---|
| 310 | self.tags[0xd2] = lambda: self.debug("%08x : uint32_xy" % self.infile.tell()) or 8 # uint32_xy |
---|
| 311 | self.tags[0xd3] = lambda: self.debug("%08x : sint16_xy" % self.infile.tell()) or 4 # sint16_xy |
---|
| 312 | self.tags[0xd4] = lambda: self.debug("%08x : sint32_xy" % self.infile.tell()) or 8 # sint32_xy |
---|
| 313 | self.tags[0xd5] = lambda: self.debug("%08x : real32_xy" % self.infile.tell()) or 8 # real32_xy |
---|
[1482] | 314 | |
---|
[1568] | 315 | self.tags[0xd0] = lambda: self.debug("%08x : ubyte_box" % self.infile.tell()) or 4 # ubyte_box |
---|
| 316 | self.tags[0xd1] = lambda: self.debug("%08x : uint16_box" % self.infile.tell()) or 8 # uint16_box |
---|
| 317 | self.tags[0xd2] = lambda: self.debug("%08x : uint32_box" % self.infile.tell()) or 16 # uint32_box |
---|
| 318 | self.tags[0xd3] = lambda: self.debug("%08x : sint16_box" % self.infile.tell()) or 8 # sint16_box |
---|
| 319 | self.tags[0xd4] = lambda: self.debug("%08x : sint32_box" % self.infile.tell()) or 16 # sint32_box |
---|
| 320 | self.tags[0xd5] = lambda: self.debug("%08x : real32_box" % self.infile.tell()) or 16 # real32_box |
---|
[1482] | 321 | |
---|
[1568] | 322 | self.tags[0xf8] = lambda: self.debug("%08x : attr_ubyte" % self.infile.tell()) or 1 # attr_ubyte |
---|
| 323 | self.tags[0xf9] = lambda: self.debug("%08x : attr_uint16" % self.infile.tell()) or 2 # attr_uint16 |
---|
[1482] | 324 | |
---|
| 325 | self.tags[0xfa] = self.embeddedData # dataLength |
---|
| 326 | self.tags[0xfb] = self.embeddedDataSmall # dataLengthByte |
---|
| 327 | |
---|
| 328 | def debug(self, msg) : |
---|
| 329 | """Outputs a debug message on stderr.""" |
---|
| 330 | sys.stderr.write("%s\n" % msg) |
---|
| 331 | sys.stderr.flush() |
---|
| 332 | |
---|
[1568] | 333 | def skipped(self) : |
---|
| 334 | """Skips a byte.""" |
---|
| 335 | self.debug("%08x : skip" % self.infile.tell()) |
---|
| 336 | |
---|
[1482] | 337 | def beginPage(self) : |
---|
| 338 | """Indicates the beginning of a new page.""" |
---|
| 339 | self.pagecount += 1 |
---|
[1568] | 340 | self.debug("%08x : beginPage (%i)" % (self.infile.tell(), self.pagecount)) |
---|
[1482] | 341 | |
---|
| 342 | def endPage(self) : |
---|
| 343 | """Indicates the end of a page.""" |
---|
[1568] | 344 | self.debug("%08x : endPage (%i)" % (self.infile.tell(), self.pagecount)) |
---|
[1482] | 345 | |
---|
| 346 | def handleArray(self, itemsize) : |
---|
| 347 | """Handles arrays.""" |
---|
[1487] | 348 | pos = self.infile.tell() |
---|
[1482] | 349 | datatype = self.infile.read(1) |
---|
[1568] | 350 | self.debug("%08x : Array of datatype 0x%02x" % (pos, ord(datatype))) |
---|
[1487] | 351 | length = self.tags[ord(datatype)]() |
---|
| 352 | if length is None : |
---|
| 353 | self.debug("Bogus array length at %s" % pos) |
---|
[1482] | 354 | else : |
---|
[1487] | 355 | sarraysize = self.infile.read(length) |
---|
| 356 | if self.islittleendian : |
---|
| 357 | fmt = "<" |
---|
| 358 | else : |
---|
| 359 | fmt = ">" |
---|
| 360 | if length == 1 : |
---|
| 361 | fmt += "B" |
---|
| 362 | elif length == 2 : |
---|
| 363 | fmt += "H" |
---|
| 364 | elif length == 4 : |
---|
| 365 | fmt += "I" |
---|
| 366 | else : |
---|
| 367 | raise PDLAnalyzerError, "Error on array size at %s" % self.infile.tell() |
---|
| 368 | arraysize = struct.unpack(fmt, sarraysize)[0] |
---|
[1568] | 369 | self.debug("itemsize %s * size %s = %s" % (itemsize, arraysize, itemsize*arraysize)) |
---|
[1487] | 370 | return arraysize * itemsize |
---|
[1482] | 371 | |
---|
| 372 | def array_8(self) : |
---|
| 373 | """Handles byte arrays.""" |
---|
[1568] | 374 | self.debug("%08x : array_8" % self.infile.tell()) |
---|
[1482] | 375 | return self.handleArray(1) |
---|
| 376 | |
---|
| 377 | def array_16(self) : |
---|
| 378 | """Handles byte arrays.""" |
---|
[1568] | 379 | self.debug("%08x : array_16" % self.infile.tell()) |
---|
[1482] | 380 | return self.handleArray(2) |
---|
| 381 | |
---|
| 382 | def array_32(self) : |
---|
| 383 | """Handles byte arrays.""" |
---|
[1568] | 384 | self.debug("%08x : array_32" % self.infile.tell()) |
---|
[1482] | 385 | return self.handleArray(4) |
---|
| 386 | |
---|
| 387 | def embeddedDataSmall(self) : |
---|
| 388 | """Handle small amounts of data.""" |
---|
[1568] | 389 | self.debug("%08x : small_datablock" % self.infile.tell()) |
---|
[1487] | 390 | pos = self.infile.tell() |
---|
| 391 | val = ord(self.infile.read(1)) |
---|
[1568] | 392 | self.debug("%08x : Small datablock length : 0x%02x" % (self.infile.tell()-1, val)) |
---|
[1487] | 393 | return val |
---|
[1482] | 394 | |
---|
| 395 | def embeddedData(self) : |
---|
| 396 | """Handle normal amounts of data.""" |
---|
[1568] | 397 | self.debug("%08x : large_datablock" % self.infile.tell()) |
---|
[1482] | 398 | if self.islittleendian : |
---|
| 399 | fmt = "<I" |
---|
| 400 | else : |
---|
| 401 | fmt = ">I" |
---|
[1487] | 402 | pos = self.infile.tell() |
---|
| 403 | val = struct.unpack(fmt, self.infile.read(4))[0] |
---|
[1568] | 404 | self.debug("%08x : Large datablock length : 0x%04x" % (self.infile.tell()-4, val)) |
---|
[1487] | 405 | return val |
---|
[1482] | 406 | |
---|
| 407 | def littleendian(self) : |
---|
| 408 | """Toggles to little endianness.""" |
---|
[1568] | 409 | self.debug("%08x : littleendian" % self.infile.tell()) |
---|
[1482] | 410 | self.islittleendian = 1 # little endian |
---|
| 411 | |
---|
| 412 | def bigendian(self) : |
---|
| 413 | """Toggles to big endianness.""" |
---|
[1568] | 414 | self.debug("%08x : bigendian" % self.infile.tell()) |
---|
[1482] | 415 | self.islittleendian = 0 # big endian |
---|
| 416 | |
---|
| 417 | def getJobSize(self) : |
---|
| 418 | """Counts pages in a PCLXL (PCL6) document.""" |
---|
| 419 | self.pagecount = 0 |
---|
| 420 | while 1 : |
---|
| 421 | char = self.infile.read(1) |
---|
| 422 | if not char : |
---|
| 423 | break |
---|
| 424 | index = ord(char) |
---|
[1487] | 425 | length = self.tags[index]() |
---|
| 426 | if length : |
---|
| 427 | self.infile.read(length) |
---|
[1482] | 428 | return self.pagecount |
---|
[1487] | 429 | |
---|
[1482] | 430 | class PDLAnalyzer : |
---|
| 431 | """Generic PDL Analyzer class.""" |
---|
| 432 | def __init__(self, filename) : |
---|
[1487] | 433 | """Initializes the PDL analyzer. |
---|
| 434 | |
---|
| 435 | filename is the name of the file or '-' for stdin. |
---|
| 436 | filename can also be a file-like object which |
---|
| 437 | supports read() and seek(). |
---|
| 438 | """ |
---|
[1482] | 439 | self.filename = filename |
---|
| 440 | |
---|
| 441 | def getJobSize(self) : |
---|
| 442 | """Returns the job's size.""" |
---|
| 443 | self.openFile() |
---|
[1487] | 444 | try : |
---|
| 445 | pdlhandler = self.detectPDLHandler() |
---|
| 446 | except PDLAnalyzerError, msg : |
---|
| 447 | self.closeFile() |
---|
| 448 | raise PDLAnalyzerError, "ERROR : Unknown file format for %s (%s)" % (self.filename, msg) |
---|
| 449 | else : |
---|
[1482] | 450 | try : |
---|
| 451 | size = pdlhandler(self.infile).getJobSize() |
---|
| 452 | finally : |
---|
| 453 | self.closeFile() |
---|
| 454 | return size |
---|
| 455 | |
---|
| 456 | def openFile(self) : |
---|
| 457 | """Opens the job's data stream for reading.""" |
---|
[1550] | 458 | self.mustclose = 0 # by default we don't want to close the file when finished |
---|
[1487] | 459 | if hasattr(self.filename, "read") and hasattr(self.filename, "seek") : |
---|
| 460 | # filename is in fact a file-like object |
---|
[1550] | 461 | infile = self.filename |
---|
[1487] | 462 | elif self.filename == "-" : |
---|
[1482] | 463 | # we must read from stdin |
---|
[1550] | 464 | infile = sys.stdin |
---|
[1482] | 465 | else : |
---|
| 466 | # normal file |
---|
[1553] | 467 | self.infile = open(self.filename, "rb") |
---|
[1550] | 468 | self.mustclose = 1 |
---|
| 469 | return |
---|
[1482] | 470 | |
---|
[1550] | 471 | # Use a temporary file, always seekable contrary to standard input. |
---|
[1553] | 472 | self.infile = tempfile.TemporaryFile(mode="w+b") |
---|
[1550] | 473 | while 1 : |
---|
| 474 | data = infile.read(MEGABYTE) |
---|
| 475 | if not data : |
---|
| 476 | break |
---|
| 477 | self.infile.write(data) |
---|
| 478 | self.infile.flush() |
---|
| 479 | self.infile.seek(0) |
---|
| 480 | |
---|
[1482] | 481 | def closeFile(self) : |
---|
[1487] | 482 | """Closes the job's data stream if we can close it.""" |
---|
| 483 | if self.mustclose : |
---|
| 484 | self.infile.close() |
---|
[1544] | 485 | else : |
---|
| 486 | # if we don't have to close the file, then |
---|
| 487 | # ensure the file pointer is reset to the |
---|
| 488 | # start of the file in case the process wants |
---|
| 489 | # to read the file again. |
---|
| 490 | try : |
---|
| 491 | self.infile.seek(0) |
---|
| 492 | except : |
---|
| 493 | pass # probably stdin, which is not seekable |
---|
[1482] | 494 | |
---|
| 495 | def isPostScript(self, data) : |
---|
| 496 | """Returns 1 if data is PostScript, else 0.""" |
---|
| 497 | if data.startswith("%!") or \ |
---|
| 498 | data.startswith("\004%!") or \ |
---|
| 499 | data.startswith("\033%-12345X%!PS") or \ |
---|
| 500 | ((data[:128].find("\033%-12345X") != -1) and \ |
---|
| 501 | ((data.find("LANGUAGE=POSTSCRIPT") != -1) or \ |
---|
| 502 | (data.find("LANGUAGE = POSTSCRIPT") != -1) or \ |
---|
[1543] | 503 | (data.find("LANGUAGE = Postscript") != -1))) or \ |
---|
| 504 | (data.find("%!PS-Adobe") != -1) : |
---|
[1482] | 505 | return 1 |
---|
| 506 | else : |
---|
| 507 | return 0 |
---|
| 508 | |
---|
[1547] | 509 | def isPDF(self, data) : |
---|
| 510 | """Returns 1 if data is PDF, else 0.""" |
---|
| 511 | if data.startswith("%PDF-") or \ |
---|
| 512 | data.startswith("\033%-12345X%PDF-") or \ |
---|
| 513 | ((data[:128].find("\033%-12345X") != -1) and (data.upper().find("LANGUAGE=PDF") != -1)) or \ |
---|
| 514 | (data.find("%PDF-") != -1) : |
---|
| 515 | return 1 |
---|
| 516 | else : |
---|
| 517 | return 0 |
---|
| 518 | |
---|
[1482] | 519 | def isPCL(self, data) : |
---|
| 520 | """Returns 1 if data is PCL, else 0.""" |
---|
| 521 | if data.startswith("\033E\033") or \ |
---|
| 522 | ((data[:128].find("\033%-12345X") != -1) and \ |
---|
| 523 | ((data.find("LANGUAGE=PCL") != -1) or \ |
---|
| 524 | (data.find("LANGUAGE = PCL") != -1) or \ |
---|
| 525 | (data.find("LANGUAGE = Pcl") != -1))) : |
---|
| 526 | return 1 |
---|
| 527 | else : |
---|
| 528 | return 0 |
---|
| 529 | |
---|
| 530 | def isPCLXL(self, data) : |
---|
| 531 | """Returns 1 if data is PCLXL aka PCL6, else 0.""" |
---|
| 532 | if ((data[:128].find("\033%-12345X") != -1) and \ |
---|
| 533 | (data.find(" HP-PCL XL;") != -1) and \ |
---|
| 534 | ((data.find("LANGUAGE=PCLXL") != -1) or \ |
---|
| 535 | (data.find("LANGUAGE = PCLXL") != -1))) : |
---|
| 536 | return 1 |
---|
| 537 | else : |
---|
| 538 | return 0 |
---|
| 539 | |
---|
| 540 | def detectPDLHandler(self) : |
---|
| 541 | """Tries to autodetect the document format. |
---|
| 542 | |
---|
| 543 | Returns the correct PDL handler class or None if format is unknown |
---|
| 544 | """ |
---|
| 545 | # Try to detect file type by reading first block of datas |
---|
| 546 | self.infile.seek(0) |
---|
[1487] | 547 | firstblock = self.infile.read(KILOBYTE) |
---|
[1482] | 548 | self.infile.seek(0) |
---|
| 549 | if self.isPostScript(firstblock) : |
---|
| 550 | return PostScriptAnalyzer |
---|
| 551 | elif self.isPCLXL(firstblock) : |
---|
| 552 | return PCLXLAnalyzer |
---|
| 553 | elif self.isPCL(firstblock) : |
---|
| 554 | return PCLAnalyzer |
---|
[1547] | 555 | elif self.isPDF(firstblock) : |
---|
| 556 | return PDFAnalyzer |
---|
[1487] | 557 | else : |
---|
| 558 | raise PDLAnalyzerError, "Analysis of first data block failed." |
---|
| 559 | |
---|
| 560 | def main() : |
---|
| 561 | """Entry point for PDL Analyzer.""" |
---|
| 562 | if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) : |
---|
| 563 | sys.argv.append("-") |
---|
| 564 | |
---|
| 565 | totalsize = 0 |
---|
| 566 | for arg in sys.argv[1:] : |
---|
| 567 | try : |
---|
| 568 | parser = PDLAnalyzer(arg) |
---|
| 569 | totalsize += parser.getJobSize() |
---|
| 570 | except PDLAnalyzerError, msg : |
---|
[1551] | 571 | sys.stderr.write("ERROR: %s\n" % msg) |
---|
[1487] | 572 | sys.stderr.flush() |
---|
| 573 | print "%s" % totalsize |
---|
| 574 | |
---|
| 575 | if __name__ == "__main__" : |
---|
| 576 | main() |
---|