[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$ |
---|
[1676] | 24 | # Revision 1.30 2004/08/21 23:16:57 jalet |
---|
| 25 | # First draft of ESC/P2 (mini-)parser. |
---|
| 26 | # |
---|
[1675] | 27 | # Revision 1.29 2004/08/11 16:25:38 jalet |
---|
| 28 | # Fixed index problem in PCLXL parser when retrieving number of copies for |
---|
| 29 | # each page |
---|
| 30 | # |
---|
[1674] | 31 | # Revision 1.28 2004/08/10 23:01:49 jalet |
---|
| 32 | # Fixed number of copies in PCL5 parser |
---|
| 33 | # |
---|
[1673] | 34 | # Revision 1.27 2004/08/09 18:14:22 jalet |
---|
| 35 | # Added workaround for number of copies and some PostScript drivers |
---|
| 36 | # |
---|
[1622] | 37 | # Revision 1.26 2004/07/22 13:49:51 jalet |
---|
| 38 | # Added support for binary PostScript through GhostScript if native DSC |
---|
| 39 | # compliant PostScript analyzer doesn't find any page. This is much |
---|
| 40 | # slower though, so native analyzer is tried first. |
---|
| 41 | # |
---|
[1599] | 42 | # Revision 1.25 2004/07/10 14:06:36 jalet |
---|
| 43 | # Fix for Python2.1 incompatibilities |
---|
| 44 | # |
---|
[1591] | 45 | # Revision 1.24 2004/07/05 21:00:39 jalet |
---|
| 46 | # Fix for number of copies for each page in PCLXL parser |
---|
| 47 | # |
---|
[1588] | 48 | # Revision 1.23 2004/07/03 08:21:59 jalet |
---|
| 49 | # Testsuite for PDL Analyzer added |
---|
| 50 | # |
---|
[1580] | 51 | # Revision 1.22 2004/06/29 14:21:41 jalet |
---|
| 52 | # Smallish optimization |
---|
| 53 | # |
---|
[1577] | 54 | # Revision 1.21 2004/06/28 23:11:26 jalet |
---|
| 55 | # Code de-factorization in PCLXL parser |
---|
| 56 | # |
---|
[1576] | 57 | # Revision 1.20 2004/06/28 22:38:41 jalet |
---|
| 58 | # Increased speed by a factor of 2 in PCLXL parser |
---|
| 59 | # |
---|
[1575] | 60 | # Revision 1.19 2004/06/28 21:20:30 jalet |
---|
| 61 | # PCLXL support now works ! |
---|
| 62 | # |
---|
[1574] | 63 | # Revision 1.18 2004/06/27 22:59:37 jalet |
---|
| 64 | # More work on PCLXL parser |
---|
| 65 | # |
---|
[1573] | 66 | # Revision 1.17 2004/06/26 23:20:01 jalet |
---|
| 67 | # Additionnal speedup for GhostScript generated PCL5 files |
---|
| 68 | # |
---|
[1572] | 69 | # Revision 1.16 2004/06/26 15:31:00 jalet |
---|
| 70 | # mmap reintroduced in PCL5 parser |
---|
| 71 | # |
---|
[1570] | 72 | # Revision 1.15 2004/06/26 14:14:31 jalet |
---|
| 73 | # Now uses Psyco if it is available |
---|
| 74 | # |
---|
[1568] | 75 | # Revision 1.14 2004/06/25 09:50:28 jalet |
---|
| 76 | # More debug info in PCLXL parser |
---|
| 77 | # |
---|
[1567] | 78 | # Revision 1.13 2004/06/25 08:10:08 jalet |
---|
| 79 | # Another fix for PCL5 parser |
---|
| 80 | # |
---|
[1566] | 81 | # Revision 1.12 2004/06/24 23:09:53 jalet |
---|
| 82 | # Fix for number of copies in PCL5 parser |
---|
| 83 | # |
---|
[1564] | 84 | # Revision 1.11 2004/06/23 22:07:50 jalet |
---|
| 85 | # Fixed PCL5 parser according to the sources of rastertohp |
---|
| 86 | # |
---|
[1553] | 87 | # Revision 1.10 2004/06/18 22:24:03 jalet |
---|
| 88 | # Removed old comments |
---|
| 89 | # |
---|
[1552] | 90 | # Revision 1.9 2004/06/18 22:21:27 jalet |
---|
| 91 | # Native PDF parser greatly improved. |
---|
| 92 | # GhostScript based PDF parser completely removed because native code |
---|
| 93 | # is now portable across Python versions. |
---|
| 94 | # |
---|
[1551] | 95 | # Revision 1.8 2004/06/18 20:49:46 jalet |
---|
| 96 | # "ERROR:" prefix added |
---|
| 97 | # |
---|
[1550] | 98 | # Revision 1.7 2004/06/18 17:48:04 jalet |
---|
| 99 | # Added native fast PDF parsing method |
---|
| 100 | # |
---|
[1547] | 101 | # Revision 1.6 2004/06/18 14:00:16 jalet |
---|
| 102 | # Added PDF support in smart PDL analyzer (through GhostScript for now) |
---|
| 103 | # |
---|
[1544] | 104 | # Revision 1.5 2004/06/18 10:09:05 jalet |
---|
| 105 | # Resets file pointer to start of file in all cases |
---|
| 106 | # |
---|
[1543] | 107 | # Revision 1.4 2004/06/18 06:16:14 jalet |
---|
| 108 | # Fixes PostScript detection code for incorrect drivers |
---|
| 109 | # |
---|
[1487] | 110 | # Revision 1.3 2004/05/21 20:40:08 jalet |
---|
| 111 | # All the code for pkpgcounter is now in pdlanalyzer.py |
---|
| 112 | # |
---|
[1485] | 113 | # Revision 1.2 2004/05/19 19:09:36 jalet |
---|
| 114 | # Speed improvement |
---|
| 115 | # |
---|
[1482] | 116 | # Revision 1.1 2004/05/18 09:59:54 jalet |
---|
| 117 | # pkpgcounter is now just a wrapper around the PDLAnalyzer class |
---|
| 118 | # |
---|
| 119 | # |
---|
| 120 | # |
---|
| 121 | |
---|
| 122 | import sys |
---|
[1547] | 123 | import os |
---|
[1552] | 124 | import re |
---|
[1580] | 125 | from struct import unpack |
---|
[1482] | 126 | import tempfile |
---|
[1572] | 127 | import mmap |
---|
[1622] | 128 | import popen2 |
---|
[1482] | 129 | |
---|
[1487] | 130 | KILOBYTE = 1024 |
---|
| 131 | MEGABYTE = 1024 * KILOBYTE |
---|
| 132 | |
---|
| 133 | class PDLAnalyzerError(Exception): |
---|
| 134 | """An exception for PDL Analyzer related stuff.""" |
---|
| 135 | def __init__(self, message = ""): |
---|
| 136 | self.message = message |
---|
| 137 | Exception.__init__(self, message) |
---|
| 138 | def __repr__(self): |
---|
| 139 | return self.message |
---|
| 140 | __str__ = __repr__ |
---|
| 141 | |
---|
[1482] | 142 | class PostScriptAnalyzer : |
---|
| 143 | def __init__(self, infile) : |
---|
| 144 | """Initialize PostScript Analyzer.""" |
---|
| 145 | self.infile = infile |
---|
[1673] | 146 | self.copies = 1 |
---|
[1622] | 147 | |
---|
| 148 | def throughGhostScript(self) : |
---|
| 149 | """Get the count through GhostScript, useful for non-DSC compliant PS files.""" |
---|
| 150 | self.infile.seek(0) |
---|
| 151 | command = 'gs -sDEVICE=bbox -dNOPAUSE -dBATCH -dQUIET - 2>&1 | grep -c "%%HiResBoundingBox:" 2>/dev/null' |
---|
| 152 | child = popen2.Popen4(command) |
---|
| 153 | try : |
---|
| 154 | data = self.infile.read(MEGABYTE) |
---|
| 155 | while data : |
---|
| 156 | child.tochild.write(data) |
---|
| 157 | data = self.infile.read(MEGABYTE) |
---|
| 158 | child.tochild.flush() |
---|
| 159 | child.tochild.close() |
---|
| 160 | except (IOError, OSError), msg : |
---|
| 161 | raise PDLAnalyzerError, "Problem during analysis of Binary PostScript document." |
---|
| 162 | |
---|
| 163 | pagecount = 0 |
---|
| 164 | try : |
---|
| 165 | pagecount = int(child.fromchild.readline().strip()) |
---|
| 166 | except (IOError, OSError, AttributeError, ValueError) : |
---|
| 167 | raise PDLAnalyzerError, "Problem during analysis of Binary PostScript document." |
---|
| 168 | child.fromchild.close() |
---|
[1482] | 169 | |
---|
[1622] | 170 | try : |
---|
| 171 | retcode = child.wait() |
---|
| 172 | except OSError, msg : |
---|
| 173 | raise PDLAnalyzerError, "Problem during analysis of Binary PostScript document." |
---|
[1673] | 174 | return pagecount * self.copies |
---|
[1622] | 175 | |
---|
| 176 | def natively(self) : |
---|
[1482] | 177 | """Count pages in a DSC compliant PostScript document.""" |
---|
[1622] | 178 | self.infile.seek(0) |
---|
[1482] | 179 | pagecount = 0 |
---|
[1552] | 180 | for line in self.infile.xreadlines() : |
---|
[1482] | 181 | if line.startswith("%%Page: ") : |
---|
| 182 | pagecount += 1 |
---|
[1673] | 183 | elif line.startswith("%%BeginNonPPDFeature: NumCopies ") : |
---|
| 184 | # handle # of copies set by some Windows printer driver |
---|
| 185 | try : |
---|
| 186 | number = int(line.strip().split()[2]) |
---|
| 187 | except : |
---|
| 188 | pass |
---|
| 189 | else : |
---|
| 190 | if number > 1 : |
---|
| 191 | self.copies = number |
---|
| 192 | elif line.startswith("1 dict dup /NumCopies ") : |
---|
| 193 | # handle # of copies set by mozilla/kprinter |
---|
| 194 | try : |
---|
| 195 | number = int(line.strip().split()[4]) |
---|
| 196 | except : |
---|
| 197 | pass |
---|
| 198 | else : |
---|
| 199 | if number > 1 : |
---|
| 200 | self.copies = number |
---|
| 201 | return pagecount * self.copies |
---|
[1482] | 202 | |
---|
[1622] | 203 | def getJobSize(self) : |
---|
| 204 | """Count pages in PostScript document.""" |
---|
| 205 | return self.natively() or self.throughGhostScript() |
---|
| 206 | |
---|
[1547] | 207 | class PDFAnalyzer : |
---|
| 208 | def __init__(self, infile) : |
---|
| 209 | """Initialize PDF Analyzer.""" |
---|
| 210 | self.infile = infile |
---|
[1550] | 211 | |
---|
[1552] | 212 | def getJobSize(self) : |
---|
| 213 | """Counts pages in a PDF document.""" |
---|
[1573] | 214 | regexp = re.compile(r"(/Type) ?(/Page)[/ \t\r\n]") |
---|
[1550] | 215 | pagecount = 0 |
---|
[1552] | 216 | for line in self.infile.xreadlines() : |
---|
| 217 | pagecount += len(regexp.findall(line)) |
---|
[1550] | 218 | return pagecount |
---|
[1547] | 219 | |
---|
[1676] | 220 | class ESCP2Analyzer : |
---|
| 221 | def __init__(self, infile) : |
---|
| 222 | """Initialize ESC/P2 Analyzer.""" |
---|
| 223 | self.infile = infile |
---|
| 224 | |
---|
| 225 | def getJobSize(self) : |
---|
| 226 | """Counts pages in an ESC/P2 document.""" |
---|
| 227 | # typical new page marker is Carriage Return (with optional Line Feed) |
---|
| 228 | # followed by Form Feed, followed by Escape character |
---|
| 229 | marker1 = chr(13) + chr(12) + chr(27) |
---|
| 230 | marker2 = chr(13) + chr(10) + chr(12) + chr(27) |
---|
| 231 | pagecount = 0 |
---|
| 232 | for line in self.infile.xreadlines() : |
---|
| 233 | c = line.count(marker1) |
---|
| 234 | if not c : |
---|
| 235 | c = line.count(marker2) |
---|
| 236 | pagecount += c |
---|
| 237 | return pagecount |
---|
| 238 | |
---|
[1482] | 239 | class PCLAnalyzer : |
---|
| 240 | def __init__(self, infile) : |
---|
| 241 | """Initialize PCL Analyzer.""" |
---|
| 242 | self.infile = infile |
---|
| 243 | |
---|
| 244 | def getJobSize(self) : |
---|
[1591] | 245 | """Count pages in a PCL5 document. |
---|
| 246 | |
---|
| 247 | Should also work for PCL3 and PCL4 documents. |
---|
| 248 | |
---|
| 249 | Algorithm from pclcount |
---|
| 250 | (c) 2003, by Eduardo Gielamo Oliveira & Rodolfo Broco Manin |
---|
| 251 | published under the terms of the GNU General Public Licence v2. |
---|
| 252 | |
---|
| 253 | Backported from C to Python by Jerome Alet, then enhanced |
---|
| 254 | with more PCL tags detected. I think all the necessary PCL tags |
---|
| 255 | are recognized to correctly handle PCL5 files wrt their number |
---|
| 256 | of pages. The documentation used for this was : |
---|
| 257 | |
---|
| 258 | HP PCL/PJL Reference Set |
---|
| 259 | PCL5 Printer Language Technical Quick Reference Guide |
---|
| 260 | http://h20000.www2.hp.com/bc/docs/support/SupportManual/bpl13205/bpl13205.pdf |
---|
| 261 | """ |
---|
[1572] | 262 | infileno = self.infile.fileno() |
---|
[1599] | 263 | minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED) |
---|
[1482] | 264 | tagsends = { "&n" : "W", |
---|
| 265 | "&b" : "W", |
---|
| 266 | "*i" : "W", |
---|
| 267 | "*l" : "W", |
---|
| 268 | "*m" : "W", |
---|
| 269 | "*v" : "W", |
---|
| 270 | "*c" : "W", |
---|
| 271 | "(f" : "W", |
---|
| 272 | "(s" : "W", |
---|
| 273 | ")s" : "W", |
---|
| 274 | "&p" : "X", |
---|
[1564] | 275 | "&l" : "XH", |
---|
| 276 | "&a" : "G", |
---|
[1573] | 277 | # "*b" : "VW", # treated specially because it occurs very often |
---|
[1564] | 278 | } |
---|
[1567] | 279 | pagecount = resets = ejects = backsides = 0 |
---|
[1482] | 280 | tag = None |
---|
[1566] | 281 | copies = {} |
---|
[1572] | 282 | pos = 0 |
---|
| 283 | try : |
---|
| 284 | while 1 : |
---|
| 285 | char = minfile[pos] ; pos += 1 |
---|
| 286 | if char == "\014" : |
---|
| 287 | pagecount += 1 |
---|
| 288 | elif char == "\033" : |
---|
| 289 | # |
---|
| 290 | # <ESC>*b###W -> Start of a raster data row/block |
---|
| 291 | # <ESC>*b###V -> Start of a raster data plane |
---|
| 292 | # <ESC>*c###W -> Start of a user defined pattern |
---|
| 293 | # <ESC>*i###W -> Start of a viewing illuminant block |
---|
| 294 | # <ESC>*l###W -> Start of a color lookup table |
---|
| 295 | # <ESC>*m###W -> Start of a download dither matrix block |
---|
| 296 | # <ESC>*v###W -> Start of a configure image data block |
---|
| 297 | # <ESC>(s###W -> Start of a characters description block |
---|
| 298 | # <ESC>)s###W -> Start of a fonts description block |
---|
| 299 | # <ESC>(f###W -> Start of a symbol set block |
---|
| 300 | # <ESC>&b###W -> Start of configuration data block |
---|
| 301 | # <ESC>&l###X -> Number of copies for current page |
---|
| 302 | # <ESC>&n###W -> Starts an alphanumeric string ID block |
---|
| 303 | # <ESC>&p###X -> Start of a non printable characters block |
---|
| 304 | # <ESC>&a2G -> Back side when duplex mode as generated by rastertohp |
---|
| 305 | # <ESC>&l0H -> Eject if NumPlanes > 1, as generated by rastertohp |
---|
| 306 | # |
---|
| 307 | tagstart = minfile[pos] ; pos += 1 |
---|
| 308 | if tagstart in "E9=YZ" : # one byte PCL tag |
---|
| 309 | if tagstart == "E" : |
---|
| 310 | resets += 1 |
---|
| 311 | continue # skip to next tag |
---|
| 312 | tag = tagstart + minfile[pos] ; pos += 1 |
---|
[1573] | 313 | if tag == "*b" : |
---|
| 314 | tagend = "VW" |
---|
[1572] | 315 | else : |
---|
[1573] | 316 | try : |
---|
| 317 | tagend = tagsends[tag] |
---|
| 318 | except KeyError : |
---|
| 319 | continue # Unsupported PCL tag |
---|
| 320 | # Now read the numeric argument |
---|
| 321 | size = 0 |
---|
| 322 | while 1 : |
---|
| 323 | char = minfile[pos] ; pos += 1 |
---|
| 324 | if not char.isdigit() : |
---|
| 325 | break |
---|
| 326 | size = (size * 10) + int(char) |
---|
| 327 | if char in tagend : |
---|
| 328 | if (tag == "&l") and (char == "X") : # copies for current page |
---|
| 329 | copies[pagecount] = size |
---|
| 330 | elif (tag == "&l") and (char == "H") and (size == 0) : |
---|
| 331 | ejects += 1 # Eject |
---|
| 332 | elif (tag == "&a") and (size == 2) : |
---|
| 333 | backsides += 1 # Back side in duplex mode |
---|
| 334 | else : |
---|
| 335 | # we just ignore the block. |
---|
| 336 | if tag == "&n" : |
---|
| 337 | # we have to take care of the operation id byte |
---|
| 338 | # which is before the string itself |
---|
| 339 | size += 1 |
---|
| 340 | pos += size |
---|
[1572] | 341 | except IndexError : # EOF ? |
---|
| 342 | minfile.close() # reached EOF |
---|
[1482] | 343 | |
---|
[1567] | 344 | # if pagecount is still 0, we will use the number |
---|
[1482] | 345 | # of resets instead of the number of form feed characters. |
---|
| 346 | # but the number of resets is always at least 2 with a valid |
---|
| 347 | # pcl file : one at the very start and one at the very end |
---|
| 348 | # of the job's data. So we substract 2 from the number of |
---|
| 349 | # resets. And since on our test data we needed to substract |
---|
| 350 | # 1 more, we finally substract 3, and will test several |
---|
| 351 | # PCL files with this. If resets < 2, then the file is |
---|
[1567] | 352 | # probably not a valid PCL file, so we use 0 |
---|
| 353 | if not pagecount : |
---|
| 354 | pagecount = (pagecount or ((resets - 3) * (resets > 2))) |
---|
| 355 | else : |
---|
| 356 | # here we add counters for other ways new pages may have |
---|
| 357 | # been printed and ejected by the printer |
---|
| 358 | pagecount += ejects + backsides |
---|
[1482] | 359 | |
---|
[1566] | 360 | # now handle number of copies for each page (may differ). |
---|
| 361 | # in duplex mode, number of copies may be sent only once. |
---|
| 362 | for pnum in range(pagecount) : |
---|
[1674] | 363 | # if no number of copies defined, take the preceding one else the one set before any page else 1. |
---|
| 364 | nb = copies.get(pnum, copies.get(pnum-1, copies.get(0, 1))) |
---|
[1566] | 365 | pagecount += (nb - 1) |
---|
| 366 | return pagecount |
---|
| 367 | |
---|
[1482] | 368 | class PCLXLAnalyzer : |
---|
| 369 | def __init__(self, infile) : |
---|
| 370 | """Initialize PCLXL Analyzer.""" |
---|
| 371 | self.infile = infile |
---|
[1577] | 372 | self.endianness = None |
---|
[1482] | 373 | found = 0 |
---|
| 374 | while not found : |
---|
| 375 | line = self.infile.readline() |
---|
| 376 | if not line : |
---|
| 377 | break |
---|
| 378 | if line[1:12] == " HP-PCL XL;" : |
---|
| 379 | found = 1 |
---|
[1574] | 380 | endian = ord(line[0]) |
---|
| 381 | if endian == 0x29 : |
---|
[1575] | 382 | self.littleEndian() |
---|
[1574] | 383 | elif endian == 0x28 : |
---|
[1575] | 384 | self.bigEndian() |
---|
| 385 | # elif endian == 0x27 : TODO : What can we do here ? |
---|
| 386 | # |
---|
[1574] | 387 | else : |
---|
[1591] | 388 | raise PDLAnalyzerError, "Unknown endianness marker 0x%02x at start !" % endian |
---|
[1482] | 389 | if not found : |
---|
[1487] | 390 | raise PDLAnalyzerError, "This file doesn't seem to be PCLXL (aka PCL6)" |
---|
[1482] | 391 | else : |
---|
[1575] | 392 | # Initialize table of tags |
---|
| 393 | self.tags = [ 0 ] * 256 |
---|
[1574] | 394 | |
---|
[1575] | 395 | # GhostScript's sources tell us that HP printers |
---|
| 396 | # only accept little endianness, but we can handle both. |
---|
| 397 | self.tags[0x28] = self.bigEndian # BigEndian |
---|
| 398 | self.tags[0x29] = self.littleEndian # LittleEndian |
---|
[1574] | 399 | |
---|
[1482] | 400 | self.tags[0x43] = self.beginPage # BeginPage |
---|
[1591] | 401 | self.tags[0x44] = self.endPage # EndPage |
---|
[1482] | 402 | |
---|
[1575] | 403 | self.tags[0xc0] = 1 # ubyte |
---|
| 404 | self.tags[0xc1] = 2 # uint16 |
---|
| 405 | self.tags[0xc2] = 4 # uint32 |
---|
| 406 | self.tags[0xc3] = 2 # sint16 |
---|
| 407 | self.tags[0xc4] = 4 # sint32 |
---|
| 408 | self.tags[0xc5] = 4 # real32 |
---|
[1574] | 409 | |
---|
[1482] | 410 | self.tags[0xc8] = self.array_8 # ubyte_array |
---|
| 411 | self.tags[0xc9] = self.array_16 # uint16_array |
---|
| 412 | self.tags[0xca] = self.array_32 # uint32_array |
---|
| 413 | self.tags[0xcb] = self.array_16 # sint16_array |
---|
| 414 | self.tags[0xcc] = self.array_32 # sint32_array |
---|
| 415 | self.tags[0xcd] = self.array_32 # real32_array |
---|
| 416 | |
---|
[1575] | 417 | self.tags[0xd0] = 2 # ubyte_xy |
---|
| 418 | self.tags[0xd1] = 4 # uint16_xy |
---|
| 419 | self.tags[0xd2] = 8 # uint32_xy |
---|
| 420 | self.tags[0xd3] = 4 # sint16_xy |
---|
| 421 | self.tags[0xd4] = 8 # sint32_xy |
---|
| 422 | self.tags[0xd5] = 8 # real32_xy |
---|
[1482] | 423 | |
---|
[1575] | 424 | self.tags[0xe0] = 4 # ubyte_box |
---|
| 425 | self.tags[0xe1] = 8 # uint16_box |
---|
| 426 | self.tags[0xe2] = 16 # uint32_box |
---|
| 427 | self.tags[0xe3] = 8 # sint16_box |
---|
| 428 | self.tags[0xe4] = 16 # sint32_box |
---|
| 429 | self.tags[0xe5] = 16 # real32_box |
---|
[1482] | 430 | |
---|
[1575] | 431 | self.tags[0xf8] = 1 # attr_ubyte |
---|
| 432 | self.tags[0xf9] = 2 # attr_uint16 |
---|
[1482] | 433 | |
---|
| 434 | self.tags[0xfa] = self.embeddedData # dataLength |
---|
| 435 | self.tags[0xfb] = self.embeddedDataSmall # dataLengthByte |
---|
| 436 | |
---|
| 437 | def beginPage(self) : |
---|
| 438 | """Indicates the beginning of a new page.""" |
---|
| 439 | self.pagecount += 1 |
---|
[1575] | 440 | return 0 |
---|
[1482] | 441 | |
---|
[1591] | 442 | def endPage(self) : |
---|
| 443 | """Indicates the end of a page.""" |
---|
| 444 | pos = self.pos |
---|
| 445 | minfile = self.minfile |
---|
| 446 | if (ord(minfile[pos-3]) == 0xf8) and (ord(minfile[pos-2]) == 0x31) : |
---|
| 447 | # The EndPage operator is preceded by a PageCopies attribute |
---|
| 448 | # So set number of copies for current page. |
---|
| 449 | # From what I read in PCLXL documentation, the number |
---|
| 450 | # of copies is an unsigned 16 bits integer |
---|
| 451 | self.copies[self.pagecount] = unpack(self.endianness + "H", minfile[pos-5:pos-3])[0] |
---|
| 452 | return 0 |
---|
| 453 | |
---|
[1577] | 454 | def array_8(self) : |
---|
| 455 | """Handles byte arrays.""" |
---|
[1576] | 456 | pos = self.pos |
---|
| 457 | datatype = self.minfile[pos] |
---|
| 458 | pos += 1 |
---|
[1575] | 459 | length = self.tags[ord(datatype)] |
---|
[1576] | 460 | if callable(length) : |
---|
| 461 | self.pos = pos |
---|
[1575] | 462 | length = length() |
---|
[1576] | 463 | pos = self.pos |
---|
[1575] | 464 | posl = pos + length |
---|
| 465 | self.pos = posl |
---|
| 466 | if length == 1 : |
---|
[1580] | 467 | return unpack("B", self.minfile[pos:posl])[0] |
---|
[1575] | 468 | elif length == 2 : |
---|
[1580] | 469 | return unpack(self.endianness + "H", self.minfile[pos:posl])[0] |
---|
[1575] | 470 | elif length == 4 : |
---|
[1580] | 471 | return unpack(self.endianness + "I", self.minfile[pos:posl])[0] |
---|
[1575] | 472 | else : |
---|
| 473 | raise PDLAnalyzerError, "Error on array size at %s" % self.pos |
---|
[1482] | 474 | |
---|
| 475 | def array_16(self) : |
---|
| 476 | """Handles byte arrays.""" |
---|
[1577] | 477 | pos = self.pos |
---|
| 478 | datatype = self.minfile[pos] |
---|
| 479 | pos += 1 |
---|
| 480 | length = self.tags[ord(datatype)] |
---|
| 481 | if callable(length) : |
---|
| 482 | self.pos = pos |
---|
| 483 | length = length() |
---|
| 484 | pos = self.pos |
---|
| 485 | posl = pos + length |
---|
| 486 | self.pos = posl |
---|
| 487 | if length == 1 : |
---|
[1580] | 488 | return 2 * unpack("B", self.minfile[pos:posl])[0] |
---|
[1577] | 489 | elif length == 2 : |
---|
[1580] | 490 | return 2 * unpack(self.endianness + "H", self.minfile[pos:posl])[0] |
---|
[1577] | 491 | elif length == 4 : |
---|
[1580] | 492 | return 2 * unpack(self.endianness + "I", self.minfile[pos:posl])[0] |
---|
[1577] | 493 | else : |
---|
| 494 | raise PDLAnalyzerError, "Error on array size at %s" % self.pos |
---|
[1482] | 495 | |
---|
| 496 | def array_32(self) : |
---|
| 497 | """Handles byte arrays.""" |
---|
[1577] | 498 | pos = self.pos |
---|
| 499 | datatype = self.minfile[pos] |
---|
| 500 | pos += 1 |
---|
| 501 | length = self.tags[ord(datatype)] |
---|
| 502 | if callable(length) : |
---|
| 503 | self.pos = pos |
---|
| 504 | length = length() |
---|
| 505 | pos = self.pos |
---|
| 506 | posl = pos + length |
---|
| 507 | self.pos = posl |
---|
| 508 | if length == 1 : |
---|
[1580] | 509 | return 4 * unpack("B", self.minfile[pos:posl])[0] |
---|
[1577] | 510 | elif length == 2 : |
---|
[1580] | 511 | return 4 * unpack(self.endianness + "H", self.minfile[pos:posl])[0] |
---|
[1577] | 512 | elif length == 4 : |
---|
[1580] | 513 | return 4 * unpack(self.endianness + "I", self.minfile[pos:posl])[0] |
---|
[1577] | 514 | else : |
---|
| 515 | raise PDLAnalyzerError, "Error on array size at %s" % self.pos |
---|
[1482] | 516 | |
---|
| 517 | def embeddedDataSmall(self) : |
---|
| 518 | """Handle small amounts of data.""" |
---|
[1576] | 519 | pos = self.pos |
---|
| 520 | length = ord(self.minfile[pos]) |
---|
| 521 | self.pos = pos + 1 |
---|
[1575] | 522 | return length |
---|
[1482] | 523 | |
---|
| 524 | def embeddedData(self) : |
---|
| 525 | """Handle normal amounts of data.""" |
---|
[1575] | 526 | pos = self.pos |
---|
| 527 | pos4 = pos + 4 |
---|
| 528 | self.pos = pos4 |
---|
[1588] | 529 | return unpack(self.endianness + "I", self.minfile[pos:pos4])[0] |
---|
[1482] | 530 | |
---|
[1575] | 531 | def littleEndian(self) : |
---|
[1482] | 532 | """Toggles to little endianness.""" |
---|
[1577] | 533 | self.endianness = "<" # little endian |
---|
[1575] | 534 | return 0 |
---|
[1482] | 535 | |
---|
[1575] | 536 | def bigEndian(self) : |
---|
[1482] | 537 | """Toggles to big endianness.""" |
---|
[1577] | 538 | self.endianness = ">" # big endian |
---|
[1575] | 539 | return 0 |
---|
[1482] | 540 | |
---|
| 541 | def getJobSize(self) : |
---|
[1591] | 542 | """Counts pages in a PCLXL (PCL6) document. |
---|
| 543 | |
---|
| 544 | Algorithm by Jerome Alet. |
---|
| 545 | |
---|
| 546 | The documentation used for this was : |
---|
| 547 | |
---|
| 548 | HP PCL XL Feature Reference |
---|
| 549 | Protocol Class 2.0 |
---|
| 550 | http://www.hpdevelopersolutions.com/downloads/64/358/xl_ref20r22.pdf |
---|
| 551 | """ |
---|
[1575] | 552 | infileno = self.infile.fileno() |
---|
[1591] | 553 | self.copies = {} |
---|
[1599] | 554 | self.minfile = minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED) |
---|
[1576] | 555 | tags = self.tags |
---|
[1482] | 556 | self.pagecount = 0 |
---|
[1576] | 557 | self.pos = pos = self.infile.tell() |
---|
[1575] | 558 | try : |
---|
| 559 | while 1 : |
---|
[1576] | 560 | char = minfile[pos] |
---|
| 561 | pos += 1 |
---|
| 562 | length = tags[ord(char)] |
---|
| 563 | if not length : |
---|
[1575] | 564 | continue |
---|
| 565 | if callable(length) : |
---|
[1576] | 566 | self.pos = pos |
---|
[1575] | 567 | length = length() |
---|
[1576] | 568 | pos = self.pos |
---|
| 569 | pos += length |
---|
[1575] | 570 | except IndexError : # EOF ? |
---|
| 571 | self.minfile.close() # reached EOF |
---|
[1591] | 572 | |
---|
| 573 | # now handle number of copies for each page (may differ). |
---|
[1675] | 574 | for pnum in range(1, self.pagecount + 1) : |
---|
[1591] | 575 | # if no number of copies defined, take 1, as explained |
---|
| 576 | # in PCLXL documentation. |
---|
| 577 | # NB : is number of copies is 0, the page won't be output |
---|
| 578 | # but the formula below is still correct : we want |
---|
| 579 | # to decrease the total number of pages in this case. |
---|
| 580 | self.pagecount += (self.copies.get(pnum, 1) - 1) |
---|
| 581 | |
---|
[1482] | 582 | return self.pagecount |
---|
[1487] | 583 | |
---|
[1482] | 584 | class PDLAnalyzer : |
---|
| 585 | """Generic PDL Analyzer class.""" |
---|
| 586 | def __init__(self, filename) : |
---|
[1487] | 587 | """Initializes the PDL analyzer. |
---|
| 588 | |
---|
| 589 | filename is the name of the file or '-' for stdin. |
---|
| 590 | filename can also be a file-like object which |
---|
| 591 | supports read() and seek(). |
---|
| 592 | """ |
---|
[1482] | 593 | self.filename = filename |
---|
[1570] | 594 | try : |
---|
| 595 | import psyco |
---|
| 596 | except ImportError : |
---|
| 597 | pass # Psyco is not installed |
---|
| 598 | else : |
---|
| 599 | # Psyco is installed, tell it to compile |
---|
| 600 | # the CPU intensive methods : PCL and PCLXL |
---|
| 601 | # parsing will greatly benefit from this, |
---|
| 602 | # for PostScript and PDF the difference is |
---|
| 603 | # barely noticeable since they are already |
---|
| 604 | # almost optimal, and much more speedy anyway. |
---|
| 605 | psyco.bind(PostScriptAnalyzer.getJobSize) |
---|
| 606 | psyco.bind(PDFAnalyzer.getJobSize) |
---|
| 607 | psyco.bind(PCLAnalyzer.getJobSize) |
---|
| 608 | psyco.bind(PCLXLAnalyzer.getJobSize) |
---|
[1482] | 609 | |
---|
| 610 | def getJobSize(self) : |
---|
| 611 | """Returns the job's size.""" |
---|
| 612 | self.openFile() |
---|
[1487] | 613 | try : |
---|
| 614 | pdlhandler = self.detectPDLHandler() |
---|
| 615 | except PDLAnalyzerError, msg : |
---|
| 616 | self.closeFile() |
---|
| 617 | raise PDLAnalyzerError, "ERROR : Unknown file format for %s (%s)" % (self.filename, msg) |
---|
| 618 | else : |
---|
[1482] | 619 | try : |
---|
| 620 | size = pdlhandler(self.infile).getJobSize() |
---|
| 621 | finally : |
---|
| 622 | self.closeFile() |
---|
| 623 | return size |
---|
| 624 | |
---|
| 625 | def openFile(self) : |
---|
| 626 | """Opens the job's data stream for reading.""" |
---|
[1550] | 627 | self.mustclose = 0 # by default we don't want to close the file when finished |
---|
[1487] | 628 | if hasattr(self.filename, "read") and hasattr(self.filename, "seek") : |
---|
| 629 | # filename is in fact a file-like object |
---|
[1550] | 630 | infile = self.filename |
---|
[1487] | 631 | elif self.filename == "-" : |
---|
[1482] | 632 | # we must read from stdin |
---|
[1550] | 633 | infile = sys.stdin |
---|
[1482] | 634 | else : |
---|
| 635 | # normal file |
---|
[1553] | 636 | self.infile = open(self.filename, "rb") |
---|
[1550] | 637 | self.mustclose = 1 |
---|
| 638 | return |
---|
[1482] | 639 | |
---|
[1550] | 640 | # Use a temporary file, always seekable contrary to standard input. |
---|
[1553] | 641 | self.infile = tempfile.TemporaryFile(mode="w+b") |
---|
[1550] | 642 | while 1 : |
---|
| 643 | data = infile.read(MEGABYTE) |
---|
| 644 | if not data : |
---|
| 645 | break |
---|
| 646 | self.infile.write(data) |
---|
| 647 | self.infile.flush() |
---|
| 648 | self.infile.seek(0) |
---|
| 649 | |
---|
[1482] | 650 | def closeFile(self) : |
---|
[1487] | 651 | """Closes the job's data stream if we can close it.""" |
---|
| 652 | if self.mustclose : |
---|
| 653 | self.infile.close() |
---|
[1544] | 654 | else : |
---|
| 655 | # if we don't have to close the file, then |
---|
| 656 | # ensure the file pointer is reset to the |
---|
| 657 | # start of the file in case the process wants |
---|
| 658 | # to read the file again. |
---|
| 659 | try : |
---|
| 660 | self.infile.seek(0) |
---|
| 661 | except : |
---|
| 662 | pass # probably stdin, which is not seekable |
---|
[1482] | 663 | |
---|
| 664 | def isPostScript(self, data) : |
---|
| 665 | """Returns 1 if data is PostScript, else 0.""" |
---|
| 666 | if data.startswith("%!") or \ |
---|
| 667 | data.startswith("\004%!") or \ |
---|
| 668 | data.startswith("\033%-12345X%!PS") or \ |
---|
| 669 | ((data[:128].find("\033%-12345X") != -1) and \ |
---|
| 670 | ((data.find("LANGUAGE=POSTSCRIPT") != -1) or \ |
---|
| 671 | (data.find("LANGUAGE = POSTSCRIPT") != -1) or \ |
---|
[1543] | 672 | (data.find("LANGUAGE = Postscript") != -1))) or \ |
---|
| 673 | (data.find("%!PS-Adobe") != -1) : |
---|
[1482] | 674 | return 1 |
---|
| 675 | else : |
---|
| 676 | return 0 |
---|
| 677 | |
---|
[1547] | 678 | def isPDF(self, data) : |
---|
| 679 | """Returns 1 if data is PDF, else 0.""" |
---|
| 680 | if data.startswith("%PDF-") or \ |
---|
| 681 | data.startswith("\033%-12345X%PDF-") or \ |
---|
| 682 | ((data[:128].find("\033%-12345X") != -1) and (data.upper().find("LANGUAGE=PDF") != -1)) or \ |
---|
| 683 | (data.find("%PDF-") != -1) : |
---|
| 684 | return 1 |
---|
| 685 | else : |
---|
| 686 | return 0 |
---|
| 687 | |
---|
[1482] | 688 | def isPCL(self, data) : |
---|
| 689 | """Returns 1 if data is PCL, else 0.""" |
---|
| 690 | if data.startswith("\033E\033") or \ |
---|
| 691 | ((data[:128].find("\033%-12345X") != -1) and \ |
---|
| 692 | ((data.find("LANGUAGE=PCL") != -1) or \ |
---|
| 693 | (data.find("LANGUAGE = PCL") != -1) or \ |
---|
| 694 | (data.find("LANGUAGE = Pcl") != -1))) : |
---|
| 695 | return 1 |
---|
| 696 | else : |
---|
| 697 | return 0 |
---|
| 698 | |
---|
| 699 | def isPCLXL(self, data) : |
---|
| 700 | """Returns 1 if data is PCLXL aka PCL6, else 0.""" |
---|
| 701 | if ((data[:128].find("\033%-12345X") != -1) and \ |
---|
| 702 | (data.find(" HP-PCL XL;") != -1) and \ |
---|
| 703 | ((data.find("LANGUAGE=PCLXL") != -1) or \ |
---|
| 704 | (data.find("LANGUAGE = PCLXL") != -1))) : |
---|
| 705 | return 1 |
---|
| 706 | else : |
---|
| 707 | return 0 |
---|
| 708 | |
---|
[1676] | 709 | def isESCP2(self, data) : |
---|
| 710 | """Returns 1 if data is ESC/P2, else 0.""" |
---|
| 711 | if (data[:2] == "\033@") or (data[:2] == "\033*") : |
---|
| 712 | return 1 |
---|
| 713 | else : |
---|
| 714 | return 0 |
---|
| 715 | |
---|
[1482] | 716 | def detectPDLHandler(self) : |
---|
| 717 | """Tries to autodetect the document format. |
---|
| 718 | |
---|
| 719 | Returns the correct PDL handler class or None if format is unknown |
---|
| 720 | """ |
---|
| 721 | # Try to detect file type by reading first block of datas |
---|
| 722 | self.infile.seek(0) |
---|
[1487] | 723 | firstblock = self.infile.read(KILOBYTE) |
---|
[1482] | 724 | self.infile.seek(0) |
---|
| 725 | if self.isPostScript(firstblock) : |
---|
| 726 | return PostScriptAnalyzer |
---|
| 727 | elif self.isPCLXL(firstblock) : |
---|
| 728 | return PCLXLAnalyzer |
---|
| 729 | elif self.isPCL(firstblock) : |
---|
| 730 | return PCLAnalyzer |
---|
[1547] | 731 | elif self.isPDF(firstblock) : |
---|
| 732 | return PDFAnalyzer |
---|
[1676] | 733 | elif self.isESCP2(firstblock) : |
---|
| 734 | return ESCP2Analyzer |
---|
[1487] | 735 | else : |
---|
| 736 | raise PDLAnalyzerError, "Analysis of first data block failed." |
---|
| 737 | |
---|
| 738 | def main() : |
---|
| 739 | """Entry point for PDL Analyzer.""" |
---|
| 740 | if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) : |
---|
| 741 | sys.argv.append("-") |
---|
| 742 | |
---|
| 743 | totalsize = 0 |
---|
| 744 | for arg in sys.argv[1:] : |
---|
| 745 | try : |
---|
| 746 | parser = PDLAnalyzer(arg) |
---|
| 747 | totalsize += parser.getJobSize() |
---|
| 748 | except PDLAnalyzerError, msg : |
---|
[1551] | 749 | sys.stderr.write("ERROR: %s\n" % msg) |
---|
[1487] | 750 | sys.stderr.flush() |
---|
| 751 | print "%s" % totalsize |
---|
| 752 | |
---|
| 753 | if __name__ == "__main__" : |
---|
[1577] | 754 | main() |
---|