[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 |
---|
[2302] | 19 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
---|
[1482] | 20 | # |
---|
| 21 | # $Id$ |
---|
| 22 | # |
---|
[2053] | 23 | # |
---|
[1482] | 24 | |
---|
| 25 | import sys |
---|
[1547] | 26 | import os |
---|
[1552] | 27 | import re |
---|
[1580] | 28 | from struct import unpack |
---|
[1482] | 29 | import tempfile |
---|
[1572] | 30 | import mmap |
---|
[1622] | 31 | import popen2 |
---|
[1482] | 32 | |
---|
[1487] | 33 | KILOBYTE = 1024 |
---|
| 34 | MEGABYTE = 1024 * KILOBYTE |
---|
[1701] | 35 | LASTBLOCKSIZE = int(KILOBYTE / 4) |
---|
[1487] | 36 | |
---|
| 37 | class PDLAnalyzerError(Exception): |
---|
| 38 | """An exception for PDL Analyzer related stuff.""" |
---|
| 39 | def __init__(self, message = ""): |
---|
| 40 | self.message = message |
---|
| 41 | Exception.__init__(self, message) |
---|
| 42 | def __repr__(self): |
---|
| 43 | return self.message |
---|
| 44 | __str__ = __repr__ |
---|
| 45 | |
---|
[1482] | 46 | class PostScriptAnalyzer : |
---|
[1912] | 47 | """A class to parse PostScript documents.""" |
---|
[1980] | 48 | def __init__(self, infile, debug=0) : |
---|
[1482] | 49 | """Initialize PostScript Analyzer.""" |
---|
[1980] | 50 | self.debug = debug |
---|
[1482] | 51 | self.infile = infile |
---|
[1673] | 52 | self.copies = 1 |
---|
[1622] | 53 | |
---|
| 54 | def throughGhostScript(self) : |
---|
| 55 | """Get the count through GhostScript, useful for non-DSC compliant PS files.""" |
---|
[1980] | 56 | if self.debug : |
---|
| 57 | sys.stderr.write("Internal parser sucks, using GhostScript instead...\n") |
---|
[1622] | 58 | self.infile.seek(0) |
---|
| 59 | command = 'gs -sDEVICE=bbox -dNOPAUSE -dBATCH -dQUIET - 2>&1 | grep -c "%%HiResBoundingBox:" 2>/dev/null' |
---|
| 60 | child = popen2.Popen4(command) |
---|
| 61 | try : |
---|
| 62 | data = self.infile.read(MEGABYTE) |
---|
| 63 | while data : |
---|
| 64 | child.tochild.write(data) |
---|
| 65 | data = self.infile.read(MEGABYTE) |
---|
| 66 | child.tochild.flush() |
---|
| 67 | child.tochild.close() |
---|
| 68 | except (IOError, OSError), msg : |
---|
[1743] | 69 | raise PDLAnalyzerError, "Problem during analysis of Binary PostScript document : %s" % msg |
---|
[1622] | 70 | |
---|
| 71 | pagecount = 0 |
---|
| 72 | try : |
---|
| 73 | pagecount = int(child.fromchild.readline().strip()) |
---|
[1743] | 74 | except (IOError, OSError, AttributeError, ValueError), msg : |
---|
| 75 | raise PDLAnalyzerError, "Problem during analysis of Binary PostScript document : %s" % msg |
---|
[1622] | 76 | child.fromchild.close() |
---|
[1482] | 77 | |
---|
[1622] | 78 | try : |
---|
[1743] | 79 | child.wait() |
---|
[1622] | 80 | except OSError, msg : |
---|
[1743] | 81 | raise PDLAnalyzerError, "Problem during analysis of Binary PostScript document : %s" % msg |
---|
[1673] | 82 | return pagecount * self.copies |
---|
[1622] | 83 | |
---|
| 84 | def natively(self) : |
---|
[1482] | 85 | """Count pages in a DSC compliant PostScript document.""" |
---|
[1622] | 86 | self.infile.seek(0) |
---|
[1482] | 87 | pagecount = 0 |
---|
[1552] | 88 | for line in self.infile.xreadlines() : |
---|
[2199] | 89 | if line.startswith(r"%%Page: ") : |
---|
[1482] | 90 | pagecount += 1 |
---|
[2199] | 91 | elif line.startswith(r"%%Requirements: numcopies(") : |
---|
[2053] | 92 | try : |
---|
| 93 | number = int(line.strip().split('(')[1].split(')')[0]) |
---|
| 94 | except : |
---|
| 95 | pass |
---|
| 96 | else : |
---|
| 97 | if number > self.copies : |
---|
| 98 | self.copies = number |
---|
[2199] | 99 | elif line.startswith(r"%%BeginNonPPDFeature: NumCopies ") : |
---|
[1673] | 100 | # handle # of copies set by some Windows printer driver |
---|
| 101 | try : |
---|
| 102 | number = int(line.strip().split()[2]) |
---|
| 103 | except : |
---|
| 104 | pass |
---|
| 105 | else : |
---|
[1683] | 106 | if number > self.copies : |
---|
[1673] | 107 | self.copies = number |
---|
| 108 | elif line.startswith("1 dict dup /NumCopies ") : |
---|
| 109 | # handle # of copies set by mozilla/kprinter |
---|
| 110 | try : |
---|
| 111 | number = int(line.strip().split()[4]) |
---|
| 112 | except : |
---|
| 113 | pass |
---|
| 114 | else : |
---|
[1683] | 115 | if number > self.copies : |
---|
[1673] | 116 | self.copies = number |
---|
| 117 | return pagecount * self.copies |
---|
[1482] | 118 | |
---|
[1622] | 119 | def getJobSize(self) : |
---|
| 120 | """Count pages in PostScript document.""" |
---|
| 121 | return self.natively() or self.throughGhostScript() |
---|
| 122 | |
---|
[1547] | 123 | class PDFAnalyzer : |
---|
[1912] | 124 | """A class to parse PDF documents.""" |
---|
[1980] | 125 | def __init__(self, infile, debug=0) : |
---|
[1547] | 126 | """Initialize PDF Analyzer.""" |
---|
[1980] | 127 | self.debug = debug |
---|
[1547] | 128 | self.infile = infile |
---|
[1550] | 129 | |
---|
[1552] | 130 | def getJobSize(self) : |
---|
| 131 | """Counts pages in a PDF document.""" |
---|
[1573] | 132 | regexp = re.compile(r"(/Type) ?(/Page)[/ \t\r\n]") |
---|
[1550] | 133 | pagecount = 0 |
---|
[1552] | 134 | for line in self.infile.xreadlines() : |
---|
| 135 | pagecount += len(regexp.findall(line)) |
---|
[1550] | 136 | return pagecount |
---|
[1547] | 137 | |
---|
[1676] | 138 | class ESCP2Analyzer : |
---|
[1912] | 139 | """A class to parse ESC/P2 documents.""" |
---|
[1980] | 140 | def __init__(self, infile, debug=0) : |
---|
[1676] | 141 | """Initialize ESC/P2 Analyzer.""" |
---|
[1980] | 142 | self.debug = debug |
---|
[1676] | 143 | self.infile = infile |
---|
| 144 | |
---|
| 145 | def getJobSize(self) : |
---|
| 146 | """Counts pages in an ESC/P2 document.""" |
---|
[1686] | 147 | # with Gimpprint, at least, for each page there |
---|
[1677] | 148 | # are two Reset Printer sequences (ESC + @) |
---|
[1686] | 149 | marker1 = "\033@" |
---|
| 150 | |
---|
| 151 | # with other software or printer driver, we |
---|
| 152 | # may prefer to search for "\r\n\fESCAPE" |
---|
| 153 | # or "\r\fESCAPE" |
---|
| 154 | marker2r = "\r\f\033" |
---|
| 155 | marker2rn = "\r\n\f\033" |
---|
| 156 | |
---|
| 157 | # and ghostscript's stcolor for example seems to |
---|
| 158 | # output ESC + @ + \f for each page plus one |
---|
| 159 | marker3 = "\033@\f" |
---|
| 160 | |
---|
| 161 | # while ghostscript's escp driver outputs instead |
---|
| 162 | # \f + ESC + @ |
---|
| 163 | marker4 = "\f\033@" |
---|
| 164 | |
---|
[1690] | 165 | data = self.infile.read() |
---|
| 166 | pagecount1 = data.count(marker1) |
---|
| 167 | pagecount2 = max(data.count(marker2r), data.count(marker2rn)) |
---|
| 168 | pagecount3 = data.count(marker3) |
---|
| 169 | pagecount4 = data.count(marker4) |
---|
[1686] | 170 | |
---|
| 171 | if pagecount2 : |
---|
| 172 | return pagecount2 |
---|
| 173 | elif pagecount3 > 1 : |
---|
| 174 | return pagecount3 - 1 |
---|
| 175 | elif pagecount4 : |
---|
| 176 | return pagecount4 |
---|
| 177 | else : |
---|
| 178 | return int(pagecount1 / 2) |
---|
[1676] | 179 | |
---|
[1482] | 180 | class PCLAnalyzer : |
---|
[1912] | 181 | """A class to parse PCL3, PCL4, PCL5 documents.""" |
---|
| 182 | mediasizes = { # ESC&l####A |
---|
| 183 | 0 : "Default", |
---|
| 184 | 1 : "Executive", |
---|
| 185 | 2 : "Letter", |
---|
| 186 | 3 : "Legal", |
---|
| 187 | 6 : "Ledger", |
---|
| 188 | 25 : "A5", |
---|
| 189 | 26 : "A4", |
---|
| 190 | 27 : "A3", |
---|
| 191 | 45 : "JB5", |
---|
| 192 | 46 : "JB4", |
---|
| 193 | 71 : "HagakiPostcard", |
---|
| 194 | 72 : "OufukuHagakiPostcard", |
---|
| 195 | 80 : "MonarchEnvelope", |
---|
| 196 | 81 : "COM10Envelope", |
---|
| 197 | 90 : "DLEnvelope", |
---|
| 198 | 91 : "C5Envelope", |
---|
| 199 | 100 : "B5Envelope", |
---|
| 200 | 101 : "Custom", |
---|
| 201 | } |
---|
| 202 | |
---|
| 203 | mediasources = { # ESC&l####H |
---|
| 204 | 0 : "Default", |
---|
| 205 | 1 : "Main", |
---|
| 206 | 2 : "Manual", |
---|
| 207 | 3 : "ManualEnvelope", |
---|
| 208 | 4 : "Alternate", |
---|
| 209 | 5 : "OptionalLarge", |
---|
| 210 | 6 : "EnvelopeFeeder", |
---|
| 211 | 7 : "Auto", |
---|
| 212 | 8 : "Tray1", |
---|
| 213 | } |
---|
| 214 | |
---|
| 215 | orientations = { # ESC&l####O |
---|
| 216 | 0 : "Portrait", |
---|
| 217 | 1 : "Landscape", |
---|
| 218 | 2 : "ReversePortrait", |
---|
| 219 | 3 : "ReverseLandscape", |
---|
| 220 | } |
---|
| 221 | |
---|
| 222 | mediatypes = { # ESC&l####M |
---|
| 223 | 0 : "Plain", |
---|
| 224 | 1 : "Bond", |
---|
| 225 | 2 : "Special", |
---|
| 226 | 3 : "Glossy", |
---|
| 227 | 4 : "Transparent", |
---|
| 228 | } |
---|
| 229 | |
---|
| 230 | |
---|
[1980] | 231 | def __init__(self, infile, debug=0) : |
---|
[1482] | 232 | """Initialize PCL Analyzer.""" |
---|
[1980] | 233 | self.debug = debug |
---|
[1482] | 234 | self.infile = infile |
---|
| 235 | |
---|
[1912] | 236 | def setPageDict(self, pages, number, attribute, value) : |
---|
| 237 | """Initializes a page dictionnary.""" |
---|
| 238 | dict = pages.setdefault(number, { "copies" : 1, "mediasource" : "Main", "mediasize" : "Default", "mediatype" : "Plain", "orientation" : "Portrait"}) |
---|
| 239 | dict[attribute] = value |
---|
| 240 | |
---|
[1482] | 241 | def getJobSize(self) : |
---|
[1591] | 242 | """Count pages in a PCL5 document. |
---|
| 243 | |
---|
| 244 | Should also work for PCL3 and PCL4 documents. |
---|
| 245 | |
---|
| 246 | Algorithm from pclcount |
---|
| 247 | (c) 2003, by Eduardo Gielamo Oliveira & Rodolfo Broco Manin |
---|
| 248 | published under the terms of the GNU General Public Licence v2. |
---|
| 249 | |
---|
| 250 | Backported from C to Python by Jerome Alet, then enhanced |
---|
| 251 | with more PCL tags detected. I think all the necessary PCL tags |
---|
| 252 | are recognized to correctly handle PCL5 files wrt their number |
---|
| 253 | of pages. The documentation used for this was : |
---|
| 254 | |
---|
| 255 | HP PCL/PJL Reference Set |
---|
| 256 | PCL5 Printer Language Technical Quick Reference Guide |
---|
| 257 | http://h20000.www2.hp.com/bc/docs/support/SupportManual/bpl13205/bpl13205.pdf |
---|
| 258 | """ |
---|
[1572] | 259 | infileno = self.infile.fileno() |
---|
[1599] | 260 | minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED) |
---|
[1482] | 261 | tagsends = { "&n" : "W", |
---|
| 262 | "&b" : "W", |
---|
| 263 | "*i" : "W", |
---|
| 264 | "*l" : "W", |
---|
| 265 | "*m" : "W", |
---|
| 266 | "*v" : "W", |
---|
| 267 | "*c" : "W", |
---|
| 268 | "(f" : "W", |
---|
| 269 | "(s" : "W", |
---|
| 270 | ")s" : "W", |
---|
| 271 | "&p" : "X", |
---|
[1912] | 272 | # "&l" : "XHAOM", # treated specially |
---|
[1700] | 273 | "&a" : "G", # TODO : 0 means next side, 1 front side, 2 back side |
---|
[1698] | 274 | "*g" : "W", |
---|
[1701] | 275 | "*r" : "sbABC", |
---|
[2012] | 276 | "*t" : "R", |
---|
[1573] | 277 | # "*b" : "VW", # treated specially because it occurs very often |
---|
[1564] | 278 | } |
---|
[1743] | 279 | pagecount = resets = ejects = backsides = startgfx = endgfx = 0 |
---|
[2012] | 280 | starb = ampl = ispcl3 = escstart = 0 |
---|
| 281 | mediasourcecount = mediasizecount = orientationcount = mediatypecount = 0 |
---|
[1482] | 282 | tag = None |
---|
[1912] | 283 | pages = {} |
---|
[1572] | 284 | pos = 0 |
---|
| 285 | try : |
---|
| 286 | while 1 : |
---|
| 287 | char = minfile[pos] ; pos += 1 |
---|
| 288 | if char == "\014" : |
---|
| 289 | pagecount += 1 |
---|
| 290 | elif char == "\033" : |
---|
[1912] | 291 | starb = ampl = 0 |
---|
[1572] | 292 | # |
---|
[1701] | 293 | # <ESC>*b###y#m###v###w... -> PCL3 raster graphics |
---|
[1572] | 294 | # <ESC>*b###W -> Start of a raster data row/block |
---|
| 295 | # <ESC>*b###V -> Start of a raster data plane |
---|
| 296 | # <ESC>*c###W -> Start of a user defined pattern |
---|
| 297 | # <ESC>*i###W -> Start of a viewing illuminant block |
---|
| 298 | # <ESC>*l###W -> Start of a color lookup table |
---|
| 299 | # <ESC>*m###W -> Start of a download dither matrix block |
---|
| 300 | # <ESC>*v###W -> Start of a configure image data block |
---|
[1701] | 301 | # <ESC>*r1A -> Start Gfx |
---|
[1572] | 302 | # <ESC>(s###W -> Start of a characters description block |
---|
| 303 | # <ESC>)s###W -> Start of a fonts description block |
---|
| 304 | # <ESC>(f###W -> Start of a symbol set block |
---|
| 305 | # <ESC>&b###W -> Start of configuration data block |
---|
| 306 | # <ESC>&l###X -> Number of copies for current page |
---|
| 307 | # <ESC>&n###W -> Starts an alphanumeric string ID block |
---|
| 308 | # <ESC>&p###X -> Start of a non printable characters block |
---|
| 309 | # <ESC>&a2G -> Back side when duplex mode as generated by rastertohp |
---|
[1698] | 310 | # <ESC>*g###W -> Needed for planes in PCL3 output |
---|
[1912] | 311 | # <ESC>&l###H (or only 0 ?) -> Eject if NumPlanes > 1, as generated by rastertohp. Also defines mediasource |
---|
| 312 | # <ESC>&l###A -> mediasize |
---|
| 313 | # <ESC>&l###O -> orientation |
---|
| 314 | # <ESC>&l###M -> mediatype |
---|
[2012] | 315 | # <ESC>*t###R -> gfx resolution |
---|
[1572] | 316 | # |
---|
| 317 | tagstart = minfile[pos] ; pos += 1 |
---|
| 318 | if tagstart in "E9=YZ" : # one byte PCL tag |
---|
| 319 | if tagstart == "E" : |
---|
| 320 | resets += 1 |
---|
| 321 | continue # skip to next tag |
---|
| 322 | tag = tagstart + minfile[pos] ; pos += 1 |
---|
[1573] | 323 | if tag == "*b" : |
---|
[1701] | 324 | starb = 1 |
---|
[1573] | 325 | tagend = "VW" |
---|
[1912] | 326 | elif tag == "&l" : |
---|
| 327 | ampl = 1 |
---|
| 328 | tagend = "XHAOM" |
---|
[1572] | 329 | else : |
---|
[1573] | 330 | try : |
---|
| 331 | tagend = tagsends[tag] |
---|
| 332 | except KeyError : |
---|
| 333 | continue # Unsupported PCL tag |
---|
| 334 | # Now read the numeric argument |
---|
| 335 | size = 0 |
---|
| 336 | while 1 : |
---|
| 337 | char = minfile[pos] ; pos += 1 |
---|
| 338 | if not char.isdigit() : |
---|
| 339 | break |
---|
| 340 | size = (size * 10) + int(char) |
---|
| 341 | if char in tagend : |
---|
[1912] | 342 | if tag == "&l" : |
---|
| 343 | if char == "X" : |
---|
| 344 | self.setPageDict(pages, pagecount, "copies", size) |
---|
| 345 | elif char == "H" : |
---|
| 346 | self.setPageDict(pages, pagecount, "mediasource", self.mediasources.get(size, str(size))) |
---|
[2012] | 347 | mediasourcecount += 1 |
---|
[1912] | 348 | ejects += 1 |
---|
| 349 | elif char == "A" : |
---|
| 350 | self.setPageDict(pages, pagecount, "mediasize", self.mediasizes.get(size, str(size))) |
---|
[2012] | 351 | mediasizecount += 1 |
---|
[1912] | 352 | elif char == "O" : |
---|
| 353 | self.setPageDict(pages, pagecount, "orientation", self.orientations.get(size, str(size))) |
---|
[2012] | 354 | orientationcount += 1 |
---|
[1912] | 355 | elif char == "M" : |
---|
| 356 | self.setPageDict(pages, pagecount, "mediatype", self.mediatypes.get(size, str(size))) |
---|
[2012] | 357 | mediatypecount += 1 |
---|
[1912] | 358 | elif tag == "*r" : |
---|
[1701] | 359 | # Special tests for PCL3 |
---|
| 360 | if (char == "s") and size : |
---|
| 361 | while 1 : |
---|
| 362 | char = minfile[pos] ; pos += 1 |
---|
| 363 | if char == "A" : |
---|
| 364 | break |
---|
| 365 | elif (char == "b") and (minfile[pos] == "C") and not size : |
---|
| 366 | ispcl3 = 1 # Certainely a PCL3 file |
---|
| 367 | startgfx += (char == "A") and (minfile[pos - 2] in ("0", "1", "2", "3")) # Start Gfx |
---|
| 368 | endgfx += (not size) and (char in ("C", "B")) # End Gfx |
---|
[2012] | 369 | elif tag == "*t" : |
---|
| 370 | escstart += 1 |
---|
[1573] | 371 | elif (tag == "&a") and (size == 2) : |
---|
| 372 | backsides += 1 # Back side in duplex mode |
---|
| 373 | else : |
---|
| 374 | # we just ignore the block. |
---|
| 375 | if tag == "&n" : |
---|
| 376 | # we have to take care of the operation id byte |
---|
| 377 | # which is before the string itself |
---|
| 378 | size += 1 |
---|
| 379 | pos += size |
---|
[1701] | 380 | else : |
---|
| 381 | if starb : |
---|
| 382 | # special handling of PCL3 in which |
---|
| 383 | # *b introduces combined ESCape sequences |
---|
| 384 | size = 0 |
---|
| 385 | while 1 : |
---|
| 386 | char = minfile[pos] ; pos += 1 |
---|
| 387 | if not char.isdigit() : |
---|
| 388 | break |
---|
| 389 | size = (size * 10) + int(char) |
---|
| 390 | if char in ("w", "v") : |
---|
| 391 | ispcl3 = 1 # certainely a PCL3 document |
---|
| 392 | pos += size - 1 |
---|
| 393 | elif char in ("y", "m") : |
---|
| 394 | ispcl3 = 1 # certainely a PCL3 document |
---|
| 395 | pos -= 1 # fix position : we were ahead |
---|
[1912] | 396 | elif ampl : |
---|
| 397 | # special handling of PCL3 in which |
---|
| 398 | # &l introduces combined ESCape sequences |
---|
| 399 | size = 0 |
---|
| 400 | while 1 : |
---|
| 401 | char = minfile[pos] ; pos += 1 |
---|
| 402 | if not char.isdigit() : |
---|
| 403 | break |
---|
| 404 | size = (size * 10) + int(char) |
---|
| 405 | if char in ("a", "o", "h", "m") : |
---|
| 406 | ispcl3 = 1 # certainely a PCL3 document |
---|
| 407 | pos -= 1 # fix position : we were ahead |
---|
| 408 | if char == "h" : |
---|
| 409 | self.setPageDict(pages, pagecount, "mediasource", self.mediasources.get(size, str(size))) |
---|
[2012] | 410 | mediasourcecount += 1 |
---|
[1912] | 411 | elif char == "a" : |
---|
| 412 | self.setPageDict(pages, pagecount, "mediasize", self.mediasizes.get(size, str(size))) |
---|
[2012] | 413 | mediasizecount += 1 |
---|
[1912] | 414 | elif char == "o" : |
---|
| 415 | self.setPageDict(pages, pagecount, "orientation", self.orientations.get(size, str(size))) |
---|
[2012] | 416 | orientationcount += 1 |
---|
[1912] | 417 | elif char == "m" : |
---|
| 418 | self.setPageDict(pages, pagecount, "mediatype", self.mediatypes.get(size, str(size))) |
---|
[2012] | 419 | mediatypecount += 1 |
---|
[1572] | 420 | except IndexError : # EOF ? |
---|
| 421 | minfile.close() # reached EOF |
---|
[1482] | 422 | |
---|
[1567] | 423 | # if pagecount is still 0, we will use the number |
---|
[1482] | 424 | # of resets instead of the number of form feed characters. |
---|
| 425 | # but the number of resets is always at least 2 with a valid |
---|
| 426 | # pcl file : one at the very start and one at the very end |
---|
| 427 | # of the job's data. So we substract 2 from the number of |
---|
| 428 | # resets. And since on our test data we needed to substract |
---|
| 429 | # 1 more, we finally substract 3, and will test several |
---|
| 430 | # PCL files with this. If resets < 2, then the file is |
---|
[1567] | 431 | # probably not a valid PCL file, so we use 0 |
---|
[1987] | 432 | |
---|
| 433 | if self.debug : |
---|
| 434 | sys.stderr.write("pagecount : %s\n" % pagecount) |
---|
| 435 | sys.stderr.write("resets : %s\n" % resets) |
---|
| 436 | sys.stderr.write("ejects : %s\n" % ejects) |
---|
| 437 | sys.stderr.write("backsides : %s\n" % backsides) |
---|
| 438 | sys.stderr.write("startgfx : %s\n" % startgfx) |
---|
| 439 | sys.stderr.write("endgfx : %s\n" % endgfx) |
---|
[2012] | 440 | sys.stderr.write("mediasourcecount : %s\n" % mediasourcecount) |
---|
| 441 | sys.stderr.write("mediasizecount : %s\n" % mediasizecount) |
---|
| 442 | sys.stderr.write("orientationcount : %s\n" % orientationcount) |
---|
| 443 | sys.stderr.write("mediatypecount : %s\n" % mediatypecount) |
---|
| 444 | sys.stderr.write("escstart : %s\n" % escstart) |
---|
[1987] | 445 | |
---|
[2003] | 446 | # if not pagecount : |
---|
| 447 | # pagecount = (pagecount or ((resets - 3) * (resets > 2))) |
---|
| 448 | # else : |
---|
| 449 | # # here we add counters for other ways new pages may have |
---|
| 450 | # # been printed and ejected by the printer |
---|
| 451 | # pagecount += ejects + backsides |
---|
| 452 | # |
---|
| 453 | # # now handle number of copies for each page (may differ). |
---|
| 454 | # # in duplex mode, number of copies may be sent only once. |
---|
| 455 | # for pnum in range(pagecount) : |
---|
| 456 | # # if no number of copies defined, take the preceding one else the one set before any page else 1. |
---|
| 457 | # page = pages.get(pnum, pages.get(pnum - 1, pages.get(0, { "copies" : 1 }))) |
---|
| 458 | # pagecount += (page["copies"] - 1) |
---|
| 459 | # |
---|
| 460 | # # in PCL3 files, there's one Start Gfx tag per page |
---|
| 461 | # if ispcl3 : |
---|
| 462 | # if endgfx == int(startgfx / 2) : # special case for cdj1600 |
---|
| 463 | # pagecount = endgfx |
---|
| 464 | # elif startgfx : |
---|
| 465 | # pagecount = startgfx |
---|
| 466 | # elif endgfx : |
---|
| 467 | # pagecount = endgfx |
---|
| 468 | |
---|
[2012] | 469 | if pagecount == mediasourcecount == escstart : |
---|
| 470 | pass # should be OK. |
---|
| 471 | elif (not startgfx) and (not endgfx) : |
---|
[2003] | 472 | pagecount = ejects or pagecount |
---|
| 473 | elif startgfx == endgfx : |
---|
| 474 | pagecount = startgfx |
---|
| 475 | elif startgfx == (endgfx - 1) : |
---|
| 476 | pagecount = startgfx |
---|
[2316] | 477 | elif (startgfx == 1) and not endgfx : |
---|
| 478 | pass |
---|
[1567] | 479 | else : |
---|
[2003] | 480 | pagecount = abs(startgfx - endgfx) |
---|
[1701] | 481 | |
---|
[1980] | 482 | if self.debug : |
---|
| 483 | for pnum in range(pagecount) : |
---|
| 484 | # if no number of copies defined, take the preceding one else the one set before any page else 1. |
---|
| 485 | page = pages.get(pnum, pages.get(pnum - 1, pages.get(0, { "copies" : 1, "mediasource" : "Main", "mediasize" : "Default", "mediatype" : "Plain", "orientation" : "Portrait"}))) |
---|
[1981] | 486 | sys.stderr.write("%s*%s*%s*%s*%s\n" % (page["copies"], page["mediatype"], page["mediasize"], page["orientation"], page["mediasource"])) |
---|
[2003] | 487 | |
---|
[1566] | 488 | return pagecount |
---|
| 489 | |
---|
[1482] | 490 | class PCLXLAnalyzer : |
---|
[1912] | 491 | """A class to parse PCL6 (aka XL) documents.""" |
---|
| 492 | mediasizes = { |
---|
| 493 | 0 : "Letter", |
---|
| 494 | 1 : "Legal", |
---|
| 495 | 2 : "A4", |
---|
| 496 | 3 : "Executive", |
---|
| 497 | 4 : "Ledger", |
---|
| 498 | 5 : "A3", |
---|
| 499 | 6 : "COM10Envelope", |
---|
| 500 | 7 : "MonarchEnvelope", |
---|
| 501 | 8 : "C5Envelope", |
---|
| 502 | 9 : "DLEnvelope", |
---|
| 503 | 10 : "JB4", |
---|
| 504 | 11 : "JB5", |
---|
| 505 | 12 : "B5Envelope", |
---|
| 506 | 14 : "JPostcard", |
---|
| 507 | 15 : "JDoublePostcard", |
---|
| 508 | 16 : "A5", |
---|
| 509 | 17 : "A6", |
---|
| 510 | 18 : "JB6", |
---|
| 511 | } |
---|
| 512 | |
---|
| 513 | mediasources = { |
---|
| 514 | 0 : "Default", |
---|
| 515 | 1 : "Auto", |
---|
| 516 | 2 : "Manual", |
---|
| 517 | 3 : "MultiPurpose", |
---|
| 518 | 4 : "UpperCassette", |
---|
| 519 | 5 : "LowerCassette", |
---|
| 520 | 6 : "EnvelopeTray", |
---|
| 521 | 7 : "ThirdCassette", |
---|
| 522 | } |
---|
| 523 | |
---|
| 524 | orientations = { |
---|
| 525 | 0 : "Portrait", |
---|
| 526 | 1 : "Landscape", |
---|
| 527 | 2 : "ReversePortrait", |
---|
| 528 | 3 : "ReverseLandscape", |
---|
| 529 | } |
---|
| 530 | |
---|
[1980] | 531 | def __init__(self, infile, debug=0) : |
---|
[1482] | 532 | """Initialize PCLXL Analyzer.""" |
---|
[1980] | 533 | self.debug = debug |
---|
[1482] | 534 | self.infile = infile |
---|
[1577] | 535 | self.endianness = None |
---|
[2197] | 536 | self.iscolor = None |
---|
[1482] | 537 | found = 0 |
---|
| 538 | while not found : |
---|
| 539 | line = self.infile.readline() |
---|
| 540 | if not line : |
---|
| 541 | break |
---|
| 542 | if line[1:12] == " HP-PCL XL;" : |
---|
| 543 | found = 1 |
---|
[1574] | 544 | endian = ord(line[0]) |
---|
| 545 | if endian == 0x29 : |
---|
[1575] | 546 | self.littleEndian() |
---|
[1574] | 547 | elif endian == 0x28 : |
---|
[1575] | 548 | self.bigEndian() |
---|
[1912] | 549 | # elif endian == 0x27 : # TODO : This is the ESC code : parse it for PJL statements ! |
---|
[1575] | 550 | # |
---|
[1574] | 551 | else : |
---|
[1591] | 552 | raise PDLAnalyzerError, "Unknown endianness marker 0x%02x at start !" % endian |
---|
[1482] | 553 | if not found : |
---|
[1487] | 554 | raise PDLAnalyzerError, "This file doesn't seem to be PCLXL (aka PCL6)" |
---|
[1574] | 555 | |
---|
[2197] | 556 | # Initialize table of tags |
---|
| 557 | self.tags = [ 0 ] * 256 |
---|
| 558 | |
---|
| 559 | # GhostScript's sources tell us that HP printers |
---|
| 560 | # only accept little endianness, but we can handle both. |
---|
| 561 | self.tags[0x28] = self.bigEndian # BigEndian |
---|
| 562 | self.tags[0x29] = self.littleEndian # LittleEndian |
---|
| 563 | |
---|
| 564 | self.tags[0x43] = self.beginPage # BeginPage |
---|
| 565 | self.tags[0x44] = self.endPage # EndPage |
---|
| 566 | |
---|
| 567 | self.tags[0x6a] = self.setColorSpace # to detect color/b&w mode |
---|
| 568 | |
---|
| 569 | self.tags[0xc0] = 1 # ubyte |
---|
| 570 | self.tags[0xc1] = 2 # uint16 |
---|
| 571 | self.tags[0xc2] = 4 # uint32 |
---|
| 572 | self.tags[0xc3] = 2 # sint16 |
---|
| 573 | self.tags[0xc4] = 4 # sint32 |
---|
| 574 | self.tags[0xc5] = 4 # real32 |
---|
| 575 | |
---|
| 576 | self.tags[0xc8] = self.array_8 # ubyte_array |
---|
| 577 | self.tags[0xc9] = self.array_16 # uint16_array |
---|
| 578 | self.tags[0xca] = self.array_32 # uint32_array |
---|
| 579 | self.tags[0xcb] = self.array_16 # sint16_array |
---|
| 580 | self.tags[0xcc] = self.array_32 # sint32_array |
---|
| 581 | self.tags[0xcd] = self.array_32 # real32_array |
---|
| 582 | |
---|
| 583 | self.tags[0xd0] = 2 # ubyte_xy |
---|
| 584 | self.tags[0xd1] = 4 # uint16_xy |
---|
| 585 | self.tags[0xd2] = 8 # uint32_xy |
---|
| 586 | self.tags[0xd3] = 4 # sint16_xy |
---|
| 587 | self.tags[0xd4] = 8 # sint32_xy |
---|
| 588 | self.tags[0xd5] = 8 # real32_xy |
---|
| 589 | |
---|
| 590 | self.tags[0xe0] = 4 # ubyte_box |
---|
| 591 | self.tags[0xe1] = 8 # uint16_box |
---|
| 592 | self.tags[0xe2] = 16 # uint32_box |
---|
| 593 | self.tags[0xe3] = 8 # sint16_box |
---|
| 594 | self.tags[0xe4] = 16 # sint32_box |
---|
| 595 | self.tags[0xe5] = 16 # real32_box |
---|
| 596 | |
---|
| 597 | self.tags[0xf8] = 1 # attr_ubyte |
---|
| 598 | self.tags[0xf9] = 2 # attr_uint16 |
---|
| 599 | |
---|
| 600 | self.tags[0xfa] = self.embeddedData # dataLength |
---|
| 601 | self.tags[0xfb] = self.embeddedDataSmall # dataLengthByte |
---|
[1574] | 602 | |
---|
[2197] | 603 | # color spaces |
---|
| 604 | self.BWColorSpace = "".join([chr(0x00), chr(0xf8), chr(0x03)]) |
---|
| 605 | self.GrayColorSpace = "".join([chr(0x01), chr(0xf8), chr(0x03)]) |
---|
| 606 | self.RGBColorSpace = "".join([chr(0x02), chr(0xf8), chr(0x03)]) |
---|
| 607 | |
---|
| 608 | # set number of copies |
---|
| 609 | self.setNumberOfCopies = "".join([chr(0xf8), chr(0x31)]) |
---|
[1482] | 610 | |
---|
| 611 | def beginPage(self) : |
---|
[1912] | 612 | """Indicates the beginning of a new page, and extracts media information.""" |
---|
[1482] | 613 | self.pagecount += 1 |
---|
[1912] | 614 | |
---|
| 615 | # Default values |
---|
| 616 | mediatypelabel = "Plain" |
---|
| 617 | mediasourcelabel = "Main" |
---|
| 618 | mediasizelabel = "Default" |
---|
| 619 | orientationlabel = "Portrait" |
---|
| 620 | |
---|
| 621 | # Now go upstream to decode media type, size, source, and orientation |
---|
| 622 | # this saves time because we don't need a complete parser ! |
---|
| 623 | minfile = self.minfile |
---|
| 624 | pos = self.pos - 2 |
---|
| 625 | while pos > 0 : # safety check : don't go back to far ! |
---|
| 626 | val = ord(minfile[pos]) |
---|
| 627 | if val in (0x44, 0x48, 0x41) : # if previous endPage or openDataSource or beginSession (first page) |
---|
| 628 | break |
---|
| 629 | if val == 0x26 : |
---|
| 630 | mediasource = ord(minfile[pos - 2]) |
---|
| 631 | mediasourcelabel = self.mediasources.get(mediasource, str(mediasource)) |
---|
| 632 | pos = pos - 4 |
---|
| 633 | elif val == 0x25 : |
---|
| 634 | mediasize = ord(minfile[pos - 2]) |
---|
| 635 | mediasizelabel = self.mediasizes.get(mediasize, str(mediasize)) |
---|
| 636 | pos = pos - 4 |
---|
| 637 | elif val == 0x28 : |
---|
| 638 | orientation = ord(minfile[pos - 2]) |
---|
| 639 | orienationlabel = self.orientations.get(orientation, str(orientation)) |
---|
| 640 | pos = pos - 4 |
---|
| 641 | elif val == 0x27 : |
---|
| 642 | savepos = pos |
---|
| 643 | pos = pos - 1 |
---|
| 644 | while pos > 0 : # safety check : don't go back to far ! |
---|
| 645 | val = ord(minfile[pos]) |
---|
| 646 | pos -= 1 |
---|
| 647 | if val == 0xc8 : |
---|
| 648 | break |
---|
| 649 | mediatypelabel = minfile[pos:savepos] # TODO : INCORRECT, WE HAVE TO STRIP OUT THE UBYTE ARRAY'S LENGTH !!! |
---|
| 650 | # else : TODO : CUSTOM MEDIA SIZE AND UNIT ! |
---|
| 651 | else : |
---|
| 652 | pos = pos - 2 # ignored |
---|
| 653 | self.pages[self.pagecount] = { "copies" : 1, |
---|
| 654 | "orientation" : orientationlabel, |
---|
| 655 | "mediatype" : mediatypelabel, |
---|
| 656 | "mediasize" : mediasizelabel, |
---|
| 657 | "mediasource" : mediasourcelabel, |
---|
| 658 | } |
---|
[1575] | 659 | return 0 |
---|
[1482] | 660 | |
---|
[1591] | 661 | def endPage(self) : |
---|
| 662 | """Indicates the end of a page.""" |
---|
| 663 | pos = self.pos |
---|
[2197] | 664 | pos3 = pos - 3 |
---|
[1591] | 665 | minfile = self.minfile |
---|
[2197] | 666 | if minfile[pos3:pos-1] == self.setNumberOfCopies : |
---|
[1912] | 667 | # The EndPage operator may be preceded by a PageCopies attribute |
---|
[1591] | 668 | # So set number of copies for current page. |
---|
| 669 | # From what I read in PCLXL documentation, the number |
---|
| 670 | # of copies is an unsigned 16 bits integer |
---|
[2197] | 671 | self.pages[self.pagecount]["copies"] = unpack(self.endianness + "H", minfile[pos-5:pos3])[0] |
---|
[1591] | 672 | return 0 |
---|
| 673 | |
---|
[2197] | 674 | def setColorSpace(self) : |
---|
| 675 | """Changes the color space.""" |
---|
| 676 | if self.minfile[self.pos-4:self.pos-1] == self.RGBColorSpace : |
---|
| 677 | self.iscolor = 1 |
---|
| 678 | return 0 |
---|
| 679 | |
---|
[1577] | 680 | def array_8(self) : |
---|
| 681 | """Handles byte arrays.""" |
---|
[1576] | 682 | pos = self.pos |
---|
| 683 | datatype = self.minfile[pos] |
---|
| 684 | pos += 1 |
---|
[1575] | 685 | length = self.tags[ord(datatype)] |
---|
[1576] | 686 | if callable(length) : |
---|
| 687 | self.pos = pos |
---|
[1575] | 688 | length = length() |
---|
[1576] | 689 | pos = self.pos |
---|
[1575] | 690 | posl = pos + length |
---|
| 691 | self.pos = posl |
---|
| 692 | if length == 1 : |
---|
[1580] | 693 | return unpack("B", self.minfile[pos:posl])[0] |
---|
[1575] | 694 | elif length == 2 : |
---|
[1580] | 695 | return unpack(self.endianness + "H", self.minfile[pos:posl])[0] |
---|
[1575] | 696 | elif length == 4 : |
---|
[1580] | 697 | return unpack(self.endianness + "I", self.minfile[pos:posl])[0] |
---|
[1575] | 698 | else : |
---|
| 699 | raise PDLAnalyzerError, "Error on array size at %s" % self.pos |
---|
[1482] | 700 | |
---|
| 701 | def array_16(self) : |
---|
| 702 | """Handles byte arrays.""" |
---|
[1577] | 703 | pos = self.pos |
---|
| 704 | datatype = self.minfile[pos] |
---|
| 705 | pos += 1 |
---|
| 706 | length = self.tags[ord(datatype)] |
---|
| 707 | if callable(length) : |
---|
| 708 | self.pos = pos |
---|
| 709 | length = length() |
---|
| 710 | pos = self.pos |
---|
| 711 | posl = pos + length |
---|
| 712 | self.pos = posl |
---|
| 713 | if length == 1 : |
---|
[1580] | 714 | return 2 * unpack("B", self.minfile[pos:posl])[0] |
---|
[1577] | 715 | elif length == 2 : |
---|
[1580] | 716 | return 2 * unpack(self.endianness + "H", self.minfile[pos:posl])[0] |
---|
[1577] | 717 | elif length == 4 : |
---|
[1580] | 718 | return 2 * unpack(self.endianness + "I", self.minfile[pos:posl])[0] |
---|
[1577] | 719 | else : |
---|
| 720 | raise PDLAnalyzerError, "Error on array size at %s" % self.pos |
---|
[1482] | 721 | |
---|
| 722 | def array_32(self) : |
---|
| 723 | """Handles byte arrays.""" |
---|
[1577] | 724 | pos = self.pos |
---|
| 725 | datatype = self.minfile[pos] |
---|
| 726 | pos += 1 |
---|
| 727 | length = self.tags[ord(datatype)] |
---|
| 728 | if callable(length) : |
---|
| 729 | self.pos = pos |
---|
| 730 | length = length() |
---|
| 731 | pos = self.pos |
---|
| 732 | posl = pos + length |
---|
| 733 | self.pos = posl |
---|
| 734 | if length == 1 : |
---|
[1580] | 735 | return 4 * unpack("B", self.minfile[pos:posl])[0] |
---|
[1577] | 736 | elif length == 2 : |
---|
[1580] | 737 | return 4 * unpack(self.endianness + "H", self.minfile[pos:posl])[0] |
---|
[1577] | 738 | elif length == 4 : |
---|
[1580] | 739 | return 4 * unpack(self.endianness + "I", self.minfile[pos:posl])[0] |
---|
[1577] | 740 | else : |
---|
| 741 | raise PDLAnalyzerError, "Error on array size at %s" % self.pos |
---|
[1482] | 742 | |
---|
| 743 | def embeddedDataSmall(self) : |
---|
| 744 | """Handle small amounts of data.""" |
---|
[1576] | 745 | pos = self.pos |
---|
| 746 | length = ord(self.minfile[pos]) |
---|
| 747 | self.pos = pos + 1 |
---|
[1575] | 748 | return length |
---|
[1482] | 749 | |
---|
| 750 | def embeddedData(self) : |
---|
| 751 | """Handle normal amounts of data.""" |
---|
[1575] | 752 | pos = self.pos |
---|
| 753 | pos4 = pos + 4 |
---|
| 754 | self.pos = pos4 |
---|
[1588] | 755 | return unpack(self.endianness + "I", self.minfile[pos:pos4])[0] |
---|
[1482] | 756 | |
---|
[1575] | 757 | def littleEndian(self) : |
---|
[1482] | 758 | """Toggles to little endianness.""" |
---|
[1577] | 759 | self.endianness = "<" # little endian |
---|
[1575] | 760 | return 0 |
---|
[1482] | 761 | |
---|
[1575] | 762 | def bigEndian(self) : |
---|
[1482] | 763 | """Toggles to big endianness.""" |
---|
[1577] | 764 | self.endianness = ">" # big endian |
---|
[1575] | 765 | return 0 |
---|
[1482] | 766 | |
---|
| 767 | def getJobSize(self) : |
---|
[1591] | 768 | """Counts pages in a PCLXL (PCL6) document. |
---|
| 769 | |
---|
| 770 | Algorithm by Jerome Alet. |
---|
| 771 | |
---|
| 772 | The documentation used for this was : |
---|
| 773 | |
---|
| 774 | HP PCL XL Feature Reference |
---|
| 775 | Protocol Class 2.0 |
---|
| 776 | http://www.hpdevelopersolutions.com/downloads/64/358/xl_ref20r22.pdf |
---|
| 777 | """ |
---|
[1575] | 778 | infileno = self.infile.fileno() |
---|
[1912] | 779 | self.pages = {} |
---|
[1599] | 780 | self.minfile = minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED) |
---|
[1576] | 781 | tags = self.tags |
---|
[1482] | 782 | self.pagecount = 0 |
---|
[1576] | 783 | self.pos = pos = self.infile.tell() |
---|
[1575] | 784 | try : |
---|
| 785 | while 1 : |
---|
[1576] | 786 | char = minfile[pos] |
---|
| 787 | pos += 1 |
---|
| 788 | length = tags[ord(char)] |
---|
| 789 | if not length : |
---|
[1575] | 790 | continue |
---|
| 791 | if callable(length) : |
---|
[1576] | 792 | self.pos = pos |
---|
[1575] | 793 | length = length() |
---|
[1576] | 794 | pos = self.pos |
---|
| 795 | pos += length |
---|
[1575] | 796 | except IndexError : # EOF ? |
---|
| 797 | self.minfile.close() # reached EOF |
---|
[1591] | 798 | |
---|
| 799 | # now handle number of copies for each page (may differ). |
---|
[2197] | 800 | if self.iscolor : |
---|
| 801 | colormode = "Color" |
---|
| 802 | else : |
---|
| 803 | colormode = "Black" |
---|
[1675] | 804 | for pnum in range(1, self.pagecount + 1) : |
---|
[1591] | 805 | # if no number of copies defined, take 1, as explained |
---|
| 806 | # in PCLXL documentation. |
---|
| 807 | # NB : is number of copies is 0, the page won't be output |
---|
| 808 | # but the formula below is still correct : we want |
---|
| 809 | # to decrease the total number of pages in this case. |
---|
[1912] | 810 | page = self.pages.get(pnum, 1) |
---|
| 811 | copies = page["copies"] |
---|
| 812 | self.pagecount += (copies - 1) |
---|
[1980] | 813 | if self.debug : |
---|
[2197] | 814 | sys.stderr.write("%s*%s*%s*%s*%s*%s\n" % (copies, |
---|
| 815 | page["mediatype"], |
---|
| 816 | page["mediasize"], |
---|
| 817 | page["orientation"], |
---|
| 818 | page["mediasource"], |
---|
| 819 | colormode)) |
---|
[1482] | 820 | return self.pagecount |
---|
[1487] | 821 | |
---|
[1482] | 822 | class PDLAnalyzer : |
---|
| 823 | """Generic PDL Analyzer class.""" |
---|
[1980] | 824 | def __init__(self, filename, debug=0) : |
---|
[1487] | 825 | """Initializes the PDL analyzer. |
---|
| 826 | |
---|
| 827 | filename is the name of the file or '-' for stdin. |
---|
| 828 | filename can also be a file-like object which |
---|
| 829 | supports read() and seek(). |
---|
| 830 | """ |
---|
[1980] | 831 | self.debug = debug |
---|
[1482] | 832 | self.filename = filename |
---|
[1570] | 833 | try : |
---|
| 834 | import psyco |
---|
| 835 | except ImportError : |
---|
| 836 | pass # Psyco is not installed |
---|
| 837 | else : |
---|
| 838 | # Psyco is installed, tell it to compile |
---|
| 839 | # the CPU intensive methods : PCL and PCLXL |
---|
| 840 | # parsing will greatly benefit from this, |
---|
| 841 | # for PostScript and PDF the difference is |
---|
| 842 | # barely noticeable since they are already |
---|
| 843 | # almost optimal, and much more speedy anyway. |
---|
| 844 | psyco.bind(PostScriptAnalyzer.getJobSize) |
---|
| 845 | psyco.bind(PDFAnalyzer.getJobSize) |
---|
[1686] | 846 | psyco.bind(ESCP2Analyzer.getJobSize) |
---|
[1570] | 847 | psyco.bind(PCLAnalyzer.getJobSize) |
---|
| 848 | psyco.bind(PCLXLAnalyzer.getJobSize) |
---|
[1482] | 849 | |
---|
| 850 | def getJobSize(self) : |
---|
| 851 | """Returns the job's size.""" |
---|
| 852 | self.openFile() |
---|
[1487] | 853 | try : |
---|
| 854 | pdlhandler = self.detectPDLHandler() |
---|
| 855 | except PDLAnalyzerError, msg : |
---|
| 856 | self.closeFile() |
---|
| 857 | raise PDLAnalyzerError, "ERROR : Unknown file format for %s (%s)" % (self.filename, msg) |
---|
| 858 | else : |
---|
[1482] | 859 | try : |
---|
[1980] | 860 | size = pdlhandler(self.infile, self.debug).getJobSize() |
---|
[1482] | 861 | finally : |
---|
| 862 | self.closeFile() |
---|
| 863 | return size |
---|
| 864 | |
---|
| 865 | def openFile(self) : |
---|
| 866 | """Opens the job's data stream for reading.""" |
---|
[1550] | 867 | self.mustclose = 0 # by default we don't want to close the file when finished |
---|
[1487] | 868 | if hasattr(self.filename, "read") and hasattr(self.filename, "seek") : |
---|
| 869 | # filename is in fact a file-like object |
---|
[1550] | 870 | infile = self.filename |
---|
[1487] | 871 | elif self.filename == "-" : |
---|
[1482] | 872 | # we must read from stdin |
---|
[1550] | 873 | infile = sys.stdin |
---|
[1482] | 874 | else : |
---|
| 875 | # normal file |
---|
[1553] | 876 | self.infile = open(self.filename, "rb") |
---|
[1550] | 877 | self.mustclose = 1 |
---|
| 878 | return |
---|
[1482] | 879 | |
---|
[1550] | 880 | # Use a temporary file, always seekable contrary to standard input. |
---|
[1553] | 881 | self.infile = tempfile.TemporaryFile(mode="w+b") |
---|
[1550] | 882 | while 1 : |
---|
| 883 | data = infile.read(MEGABYTE) |
---|
| 884 | if not data : |
---|
| 885 | break |
---|
| 886 | self.infile.write(data) |
---|
| 887 | self.infile.flush() |
---|
| 888 | self.infile.seek(0) |
---|
| 889 | |
---|
[1482] | 890 | def closeFile(self) : |
---|
[1487] | 891 | """Closes the job's data stream if we can close it.""" |
---|
| 892 | if self.mustclose : |
---|
| 893 | self.infile.close() |
---|
[1544] | 894 | else : |
---|
| 895 | # if we don't have to close the file, then |
---|
| 896 | # ensure the file pointer is reset to the |
---|
| 897 | # start of the file in case the process wants |
---|
| 898 | # to read the file again. |
---|
| 899 | try : |
---|
| 900 | self.infile.seek(0) |
---|
| 901 | except : |
---|
| 902 | pass # probably stdin, which is not seekable |
---|
[1482] | 903 | |
---|
[1701] | 904 | def isPostScript(self, sdata, edata) : |
---|
[1482] | 905 | """Returns 1 if data is PostScript, else 0.""" |
---|
[1701] | 906 | if sdata.startswith("%!") or \ |
---|
| 907 | sdata.startswith("\004%!") or \ |
---|
| 908 | sdata.startswith("\033%-12345X%!PS") or \ |
---|
| 909 | ((sdata[:128].find("\033%-12345X") != -1) and \ |
---|
| 910 | ((sdata.find("LANGUAGE=POSTSCRIPT") != -1) or \ |
---|
| 911 | (sdata.find("LANGUAGE = POSTSCRIPT") != -1) or \ |
---|
| 912 | (sdata.find("LANGUAGE = Postscript") != -1))) or \ |
---|
| 913 | (sdata.find("%!PS-Adobe") != -1) : |
---|
[1980] | 914 | if self.debug : |
---|
| 915 | sys.stderr.write("%s is a PostScript file\n" % str(self.filename)) |
---|
[1482] | 916 | return 1 |
---|
| 917 | else : |
---|
| 918 | return 0 |
---|
| 919 | |
---|
[1701] | 920 | def isPDF(self, sdata, edata) : |
---|
[1547] | 921 | """Returns 1 if data is PDF, else 0.""" |
---|
[1701] | 922 | if sdata.startswith("%PDF-") or \ |
---|
| 923 | sdata.startswith("\033%-12345X%PDF-") or \ |
---|
| 924 | ((sdata[:128].find("\033%-12345X") != -1) and (sdata.upper().find("LANGUAGE=PDF") != -1)) or \ |
---|
| 925 | (sdata.find("%PDF-") != -1) : |
---|
[1980] | 926 | if self.debug : |
---|
| 927 | sys.stderr.write("%s is a PDF file\n" % str(self.filename)) |
---|
[1547] | 928 | return 1 |
---|
| 929 | else : |
---|
| 930 | return 0 |
---|
| 931 | |
---|
[1701] | 932 | def isPCL(self, sdata, edata) : |
---|
[1482] | 933 | """Returns 1 if data is PCL, else 0.""" |
---|
[1701] | 934 | if sdata.startswith("\033E\033") or \ |
---|
| 935 | (sdata.startswith("\033*rbC") and (not edata[-3:] == "\f\033@")) or \ |
---|
[1702] | 936 | sdata.startswith("\033%8\033") or \ |
---|
[1701] | 937 | (sdata.find("\033%-12345X") != -1) : |
---|
[1980] | 938 | if self.debug : |
---|
| 939 | sys.stderr.write("%s is a PCL3/4/5 file\n" % str(self.filename)) |
---|
[1482] | 940 | return 1 |
---|
| 941 | else : |
---|
| 942 | return 0 |
---|
| 943 | |
---|
[1701] | 944 | def isPCLXL(self, sdata, edata) : |
---|
[1482] | 945 | """Returns 1 if data is PCLXL aka PCL6, else 0.""" |
---|
[1701] | 946 | if ((sdata[:128].find("\033%-12345X") != -1) and \ |
---|
| 947 | (sdata.find(" HP-PCL XL;") != -1) and \ |
---|
| 948 | ((sdata.find("LANGUAGE=PCLXL") != -1) or \ |
---|
| 949 | (sdata.find("LANGUAGE = PCLXL") != -1))) : |
---|
[1980] | 950 | if self.debug : |
---|
| 951 | sys.stderr.write("%s is a PCLXL (aka PCL6) file\n" % str(self.filename)) |
---|
[1482] | 952 | return 1 |
---|
| 953 | else : |
---|
| 954 | return 0 |
---|
| 955 | |
---|
[1701] | 956 | def isESCP2(self, sdata, edata) : |
---|
[1676] | 957 | """Returns 1 if data is ESC/P2, else 0.""" |
---|
[1701] | 958 | if sdata.startswith("\033@") or \ |
---|
| 959 | sdata.startswith("\033*") or \ |
---|
[1940] | 960 | sdata.startswith("\n\033@") or \ |
---|
| 961 | sdata.startswith("\0\0\0\033\1@EJL") : # ESC/P Raster ??? Seen on Stylus Photo 1284 |
---|
[1980] | 962 | if self.debug : |
---|
| 963 | sys.stderr.write("%s is an ESC/P2 file\n" % str(self.filename)) |
---|
[1676] | 964 | return 1 |
---|
| 965 | else : |
---|
| 966 | return 0 |
---|
| 967 | |
---|
[1482] | 968 | def detectPDLHandler(self) : |
---|
| 969 | """Tries to autodetect the document format. |
---|
| 970 | |
---|
| 971 | Returns the correct PDL handler class or None if format is unknown |
---|
| 972 | """ |
---|
| 973 | # Try to detect file type by reading first block of datas |
---|
| 974 | self.infile.seek(0) |
---|
[2316] | 975 | firstblock = self.infile.read(16 * KILOBYTE) |
---|
[1701] | 976 | try : |
---|
| 977 | self.infile.seek(-LASTBLOCKSIZE, 2) |
---|
[2026] | 978 | lastblock = self.infile.read(LASTBLOCKSIZE) |
---|
[1701] | 979 | except IOError : |
---|
| 980 | lastblock = "" |
---|
[2026] | 981 | |
---|
[1482] | 982 | self.infile.seek(0) |
---|
[1701] | 983 | if self.isPostScript(firstblock, lastblock) : |
---|
[1482] | 984 | return PostScriptAnalyzer |
---|
[1701] | 985 | elif self.isPCLXL(firstblock, lastblock) : |
---|
[1482] | 986 | return PCLXLAnalyzer |
---|
[1701] | 987 | elif self.isPDF(firstblock, lastblock) : |
---|
[1681] | 988 | return PDFAnalyzer |
---|
[1701] | 989 | elif self.isPCL(firstblock, lastblock) : |
---|
[1482] | 990 | return PCLAnalyzer |
---|
[1701] | 991 | elif self.isESCP2(firstblock, lastblock) : |
---|
[1676] | 992 | return ESCP2Analyzer |
---|
[1487] | 993 | else : |
---|
| 994 | raise PDLAnalyzerError, "Analysis of first data block failed." |
---|
| 995 | |
---|
| 996 | def main() : |
---|
| 997 | """Entry point for PDL Analyzer.""" |
---|
| 998 | if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) : |
---|
| 999 | sys.argv.append("-") |
---|
| 1000 | |
---|
| 1001 | totalsize = 0 |
---|
[1980] | 1002 | debug = 0 |
---|
| 1003 | minindex = 1 |
---|
| 1004 | if sys.argv[1] == "--debug" : |
---|
| 1005 | minindex = 2 |
---|
| 1006 | debug = 1 |
---|
| 1007 | for arg in sys.argv[minindex:] : |
---|
[1487] | 1008 | try : |
---|
[1980] | 1009 | parser = PDLAnalyzer(arg, debug) |
---|
[1487] | 1010 | totalsize += parser.getJobSize() |
---|
| 1011 | except PDLAnalyzerError, msg : |
---|
[1551] | 1012 | sys.stderr.write("ERROR: %s\n" % msg) |
---|
[1487] | 1013 | sys.stderr.flush() |
---|
| 1014 | print "%s" % totalsize |
---|
| 1015 | |
---|
| 1016 | if __name__ == "__main__" : |
---|
[1577] | 1017 | main() |
---|