[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 | # |
---|
[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() : |
---|
[1482] | 89 | if line.startswith("%%Page: ") : |
---|
| 90 | pagecount += 1 |
---|
[2053] | 91 | elif line.startswith("%%Requirements: numcopies(") : |
---|
| 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 |
---|
[1673] | 99 | elif line.startswith("%%BeginNonPPDFeature: NumCopies ") : |
---|
| 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 | |
---|
| 469 | |
---|
[2012] | 470 | if pagecount == mediasourcecount == escstart : |
---|
| 471 | pass # should be OK. |
---|
| 472 | elif (not startgfx) and (not endgfx) : |
---|
[2003] | 473 | pagecount = ejects or pagecount |
---|
| 474 | elif startgfx == endgfx : |
---|
| 475 | pagecount = startgfx |
---|
| 476 | elif startgfx == (endgfx - 1) : |
---|
| 477 | pagecount = startgfx |
---|
[1567] | 478 | else : |
---|
[2003] | 479 | pagecount = abs(startgfx - endgfx) |
---|
[1701] | 480 | |
---|
[1980] | 481 | if self.debug : |
---|
| 482 | for pnum in range(pagecount) : |
---|
| 483 | # if no number of copies defined, take the preceding one else the one set before any page else 1. |
---|
| 484 | page = pages.get(pnum, pages.get(pnum - 1, pages.get(0, { "copies" : 1, "mediasource" : "Main", "mediasize" : "Default", "mediatype" : "Plain", "orientation" : "Portrait"}))) |
---|
[1981] | 485 | sys.stderr.write("%s*%s*%s*%s*%s\n" % (page["copies"], page["mediatype"], page["mediasize"], page["orientation"], page["mediasource"])) |
---|
[2003] | 486 | |
---|
[1566] | 487 | return pagecount |
---|
| 488 | |
---|
[1482] | 489 | class PCLXLAnalyzer : |
---|
[1912] | 490 | """A class to parse PCL6 (aka XL) documents.""" |
---|
| 491 | mediasizes = { |
---|
| 492 | 0 : "Letter", |
---|
| 493 | 1 : "Legal", |
---|
| 494 | 2 : "A4", |
---|
| 495 | 3 : "Executive", |
---|
| 496 | 4 : "Ledger", |
---|
| 497 | 5 : "A3", |
---|
| 498 | 6 : "COM10Envelope", |
---|
| 499 | 7 : "MonarchEnvelope", |
---|
| 500 | 8 : "C5Envelope", |
---|
| 501 | 9 : "DLEnvelope", |
---|
| 502 | 10 : "JB4", |
---|
| 503 | 11 : "JB5", |
---|
| 504 | 12 : "B5Envelope", |
---|
| 505 | 14 : "JPostcard", |
---|
| 506 | 15 : "JDoublePostcard", |
---|
| 507 | 16 : "A5", |
---|
| 508 | 17 : "A6", |
---|
| 509 | 18 : "JB6", |
---|
| 510 | } |
---|
| 511 | |
---|
| 512 | mediasources = { |
---|
| 513 | 0 : "Default", |
---|
| 514 | 1 : "Auto", |
---|
| 515 | 2 : "Manual", |
---|
| 516 | 3 : "MultiPurpose", |
---|
| 517 | 4 : "UpperCassette", |
---|
| 518 | 5 : "LowerCassette", |
---|
| 519 | 6 : "EnvelopeTray", |
---|
| 520 | 7 : "ThirdCassette", |
---|
| 521 | } |
---|
| 522 | |
---|
| 523 | orientations = { |
---|
| 524 | 0 : "Portrait", |
---|
| 525 | 1 : "Landscape", |
---|
| 526 | 2 : "ReversePortrait", |
---|
| 527 | 3 : "ReverseLandscape", |
---|
| 528 | } |
---|
| 529 | |
---|
[1980] | 530 | def __init__(self, infile, debug=0) : |
---|
[1482] | 531 | """Initialize PCLXL Analyzer.""" |
---|
[1980] | 532 | self.debug = debug |
---|
[1482] | 533 | self.infile = infile |
---|
[1577] | 534 | self.endianness = None |
---|
[1482] | 535 | found = 0 |
---|
| 536 | while not found : |
---|
| 537 | line = self.infile.readline() |
---|
| 538 | if not line : |
---|
| 539 | break |
---|
| 540 | if line[1:12] == " HP-PCL XL;" : |
---|
| 541 | found = 1 |
---|
[1574] | 542 | endian = ord(line[0]) |
---|
| 543 | if endian == 0x29 : |
---|
[1575] | 544 | self.littleEndian() |
---|
[1574] | 545 | elif endian == 0x28 : |
---|
[1575] | 546 | self.bigEndian() |
---|
[1912] | 547 | # elif endian == 0x27 : # TODO : This is the ESC code : parse it for PJL statements ! |
---|
[1575] | 548 | # |
---|
[1574] | 549 | else : |
---|
[1591] | 550 | raise PDLAnalyzerError, "Unknown endianness marker 0x%02x at start !" % endian |
---|
[1482] | 551 | if not found : |
---|
[1487] | 552 | raise PDLAnalyzerError, "This file doesn't seem to be PCLXL (aka PCL6)" |
---|
[1482] | 553 | else : |
---|
[1575] | 554 | # Initialize table of tags |
---|
| 555 | self.tags = [ 0 ] * 256 |
---|
[1574] | 556 | |
---|
[1575] | 557 | # GhostScript's sources tell us that HP printers |
---|
| 558 | # only accept little endianness, but we can handle both. |
---|
| 559 | self.tags[0x28] = self.bigEndian # BigEndian |
---|
| 560 | self.tags[0x29] = self.littleEndian # LittleEndian |
---|
[1574] | 561 | |
---|
[1482] | 562 | self.tags[0x43] = self.beginPage # BeginPage |
---|
[1591] | 563 | self.tags[0x44] = self.endPage # EndPage |
---|
[1482] | 564 | |
---|
[1575] | 565 | self.tags[0xc0] = 1 # ubyte |
---|
| 566 | self.tags[0xc1] = 2 # uint16 |
---|
| 567 | self.tags[0xc2] = 4 # uint32 |
---|
| 568 | self.tags[0xc3] = 2 # sint16 |
---|
| 569 | self.tags[0xc4] = 4 # sint32 |
---|
| 570 | self.tags[0xc5] = 4 # real32 |
---|
[1574] | 571 | |
---|
[1482] | 572 | self.tags[0xc8] = self.array_8 # ubyte_array |
---|
| 573 | self.tags[0xc9] = self.array_16 # uint16_array |
---|
| 574 | self.tags[0xca] = self.array_32 # uint32_array |
---|
| 575 | self.tags[0xcb] = self.array_16 # sint16_array |
---|
| 576 | self.tags[0xcc] = self.array_32 # sint32_array |
---|
| 577 | self.tags[0xcd] = self.array_32 # real32_array |
---|
| 578 | |
---|
[1575] | 579 | self.tags[0xd0] = 2 # ubyte_xy |
---|
| 580 | self.tags[0xd1] = 4 # uint16_xy |
---|
| 581 | self.tags[0xd2] = 8 # uint32_xy |
---|
| 582 | self.tags[0xd3] = 4 # sint16_xy |
---|
| 583 | self.tags[0xd4] = 8 # sint32_xy |
---|
| 584 | self.tags[0xd5] = 8 # real32_xy |
---|
[1482] | 585 | |
---|
[1575] | 586 | self.tags[0xe0] = 4 # ubyte_box |
---|
| 587 | self.tags[0xe1] = 8 # uint16_box |
---|
| 588 | self.tags[0xe2] = 16 # uint32_box |
---|
| 589 | self.tags[0xe3] = 8 # sint16_box |
---|
| 590 | self.tags[0xe4] = 16 # sint32_box |
---|
| 591 | self.tags[0xe5] = 16 # real32_box |
---|
[1482] | 592 | |
---|
[1575] | 593 | self.tags[0xf8] = 1 # attr_ubyte |
---|
| 594 | self.tags[0xf9] = 2 # attr_uint16 |
---|
[1482] | 595 | |
---|
| 596 | self.tags[0xfa] = self.embeddedData # dataLength |
---|
| 597 | self.tags[0xfb] = self.embeddedDataSmall # dataLengthByte |
---|
| 598 | |
---|
| 599 | def beginPage(self) : |
---|
[1912] | 600 | """Indicates the beginning of a new page, and extracts media information.""" |
---|
[1482] | 601 | self.pagecount += 1 |
---|
[1912] | 602 | |
---|
| 603 | # Default values |
---|
| 604 | mediatypelabel = "Plain" |
---|
| 605 | mediasourcelabel = "Main" |
---|
| 606 | mediasizelabel = "Default" |
---|
| 607 | orientationlabel = "Portrait" |
---|
| 608 | |
---|
| 609 | # Now go upstream to decode media type, size, source, and orientation |
---|
| 610 | # this saves time because we don't need a complete parser ! |
---|
| 611 | minfile = self.minfile |
---|
| 612 | pos = self.pos - 2 |
---|
| 613 | while pos > 0 : # safety check : don't go back to far ! |
---|
| 614 | val = ord(minfile[pos]) |
---|
| 615 | if val in (0x44, 0x48, 0x41) : # if previous endPage or openDataSource or beginSession (first page) |
---|
| 616 | break |
---|
| 617 | if val == 0x26 : |
---|
| 618 | mediasource = ord(minfile[pos - 2]) |
---|
| 619 | mediasourcelabel = self.mediasources.get(mediasource, str(mediasource)) |
---|
| 620 | pos = pos - 4 |
---|
| 621 | elif val == 0x25 : |
---|
| 622 | mediasize = ord(minfile[pos - 2]) |
---|
| 623 | mediasizelabel = self.mediasizes.get(mediasize, str(mediasize)) |
---|
| 624 | pos = pos - 4 |
---|
| 625 | elif val == 0x28 : |
---|
| 626 | orientation = ord(minfile[pos - 2]) |
---|
| 627 | orienationlabel = self.orientations.get(orientation, str(orientation)) |
---|
| 628 | pos = pos - 4 |
---|
| 629 | elif val == 0x27 : |
---|
| 630 | savepos = pos |
---|
| 631 | pos = pos - 1 |
---|
| 632 | while pos > 0 : # safety check : don't go back to far ! |
---|
| 633 | val = ord(minfile[pos]) |
---|
| 634 | pos -= 1 |
---|
| 635 | if val == 0xc8 : |
---|
| 636 | break |
---|
| 637 | mediatypelabel = minfile[pos:savepos] # TODO : INCORRECT, WE HAVE TO STRIP OUT THE UBYTE ARRAY'S LENGTH !!! |
---|
| 638 | # else : TODO : CUSTOM MEDIA SIZE AND UNIT ! |
---|
| 639 | else : |
---|
| 640 | pos = pos - 2 # ignored |
---|
| 641 | self.pages[self.pagecount] = { "copies" : 1, |
---|
| 642 | "orientation" : orientationlabel, |
---|
| 643 | "mediatype" : mediatypelabel, |
---|
| 644 | "mediasize" : mediasizelabel, |
---|
| 645 | "mediasource" : mediasourcelabel, |
---|
| 646 | } |
---|
[1575] | 647 | return 0 |
---|
[1482] | 648 | |
---|
[1591] | 649 | def endPage(self) : |
---|
| 650 | """Indicates the end of a page.""" |
---|
| 651 | pos = self.pos |
---|
| 652 | minfile = self.minfile |
---|
| 653 | if (ord(minfile[pos-3]) == 0xf8) and (ord(minfile[pos-2]) == 0x31) : |
---|
[1912] | 654 | # The EndPage operator may be preceded by a PageCopies attribute |
---|
[1591] | 655 | # So set number of copies for current page. |
---|
| 656 | # From what I read in PCLXL documentation, the number |
---|
| 657 | # of copies is an unsigned 16 bits integer |
---|
[1912] | 658 | self.pages[self.pagecount]["copies"] = unpack(self.endianness + "H", minfile[pos-5:pos-3])[0] |
---|
[1591] | 659 | return 0 |
---|
| 660 | |
---|
[1577] | 661 | def array_8(self) : |
---|
| 662 | """Handles byte arrays.""" |
---|
[1576] | 663 | pos = self.pos |
---|
| 664 | datatype = self.minfile[pos] |
---|
| 665 | pos += 1 |
---|
[1575] | 666 | length = self.tags[ord(datatype)] |
---|
[1576] | 667 | if callable(length) : |
---|
| 668 | self.pos = pos |
---|
[1575] | 669 | length = length() |
---|
[1576] | 670 | pos = self.pos |
---|
[1575] | 671 | posl = pos + length |
---|
| 672 | self.pos = posl |
---|
| 673 | if length == 1 : |
---|
[1580] | 674 | return unpack("B", self.minfile[pos:posl])[0] |
---|
[1575] | 675 | elif length == 2 : |
---|
[1580] | 676 | return unpack(self.endianness + "H", self.minfile[pos:posl])[0] |
---|
[1575] | 677 | elif length == 4 : |
---|
[1580] | 678 | return unpack(self.endianness + "I", self.minfile[pos:posl])[0] |
---|
[1575] | 679 | else : |
---|
| 680 | raise PDLAnalyzerError, "Error on array size at %s" % self.pos |
---|
[1482] | 681 | |
---|
| 682 | def array_16(self) : |
---|
| 683 | """Handles byte arrays.""" |
---|
[1577] | 684 | pos = self.pos |
---|
| 685 | datatype = self.minfile[pos] |
---|
| 686 | pos += 1 |
---|
| 687 | length = self.tags[ord(datatype)] |
---|
| 688 | if callable(length) : |
---|
| 689 | self.pos = pos |
---|
| 690 | length = length() |
---|
| 691 | pos = self.pos |
---|
| 692 | posl = pos + length |
---|
| 693 | self.pos = posl |
---|
| 694 | if length == 1 : |
---|
[1580] | 695 | return 2 * unpack("B", self.minfile[pos:posl])[0] |
---|
[1577] | 696 | elif length == 2 : |
---|
[1580] | 697 | return 2 * unpack(self.endianness + "H", self.minfile[pos:posl])[0] |
---|
[1577] | 698 | elif length == 4 : |
---|
[1580] | 699 | return 2 * unpack(self.endianness + "I", self.minfile[pos:posl])[0] |
---|
[1577] | 700 | else : |
---|
| 701 | raise PDLAnalyzerError, "Error on array size at %s" % self.pos |
---|
[1482] | 702 | |
---|
| 703 | def array_32(self) : |
---|
| 704 | """Handles byte arrays.""" |
---|
[1577] | 705 | pos = self.pos |
---|
| 706 | datatype = self.minfile[pos] |
---|
| 707 | pos += 1 |
---|
| 708 | length = self.tags[ord(datatype)] |
---|
| 709 | if callable(length) : |
---|
| 710 | self.pos = pos |
---|
| 711 | length = length() |
---|
| 712 | pos = self.pos |
---|
| 713 | posl = pos + length |
---|
| 714 | self.pos = posl |
---|
| 715 | if length == 1 : |
---|
[1580] | 716 | return 4 * unpack("B", self.minfile[pos:posl])[0] |
---|
[1577] | 717 | elif length == 2 : |
---|
[1580] | 718 | return 4 * unpack(self.endianness + "H", self.minfile[pos:posl])[0] |
---|
[1577] | 719 | elif length == 4 : |
---|
[1580] | 720 | return 4 * unpack(self.endianness + "I", self.minfile[pos:posl])[0] |
---|
[1577] | 721 | else : |
---|
| 722 | raise PDLAnalyzerError, "Error on array size at %s" % self.pos |
---|
[1482] | 723 | |
---|
| 724 | def embeddedDataSmall(self) : |
---|
| 725 | """Handle small amounts of data.""" |
---|
[1576] | 726 | pos = self.pos |
---|
| 727 | length = ord(self.minfile[pos]) |
---|
| 728 | self.pos = pos + 1 |
---|
[1575] | 729 | return length |
---|
[1482] | 730 | |
---|
| 731 | def embeddedData(self) : |
---|
| 732 | """Handle normal amounts of data.""" |
---|
[1575] | 733 | pos = self.pos |
---|
| 734 | pos4 = pos + 4 |
---|
| 735 | self.pos = pos4 |
---|
[1588] | 736 | return unpack(self.endianness + "I", self.minfile[pos:pos4])[0] |
---|
[1482] | 737 | |
---|
[1575] | 738 | def littleEndian(self) : |
---|
[1482] | 739 | """Toggles to little endianness.""" |
---|
[1577] | 740 | self.endianness = "<" # little endian |
---|
[1575] | 741 | return 0 |
---|
[1482] | 742 | |
---|
[1575] | 743 | def bigEndian(self) : |
---|
[1482] | 744 | """Toggles to big endianness.""" |
---|
[1577] | 745 | self.endianness = ">" # big endian |
---|
[1575] | 746 | return 0 |
---|
[1482] | 747 | |
---|
| 748 | def getJobSize(self) : |
---|
[1591] | 749 | """Counts pages in a PCLXL (PCL6) document. |
---|
| 750 | |
---|
| 751 | Algorithm by Jerome Alet. |
---|
| 752 | |
---|
| 753 | The documentation used for this was : |
---|
| 754 | |
---|
| 755 | HP PCL XL Feature Reference |
---|
| 756 | Protocol Class 2.0 |
---|
| 757 | http://www.hpdevelopersolutions.com/downloads/64/358/xl_ref20r22.pdf |
---|
| 758 | """ |
---|
[1575] | 759 | infileno = self.infile.fileno() |
---|
[1912] | 760 | self.pages = {} |
---|
[1599] | 761 | self.minfile = minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED) |
---|
[1576] | 762 | tags = self.tags |
---|
[1482] | 763 | self.pagecount = 0 |
---|
[1576] | 764 | self.pos = pos = self.infile.tell() |
---|
[1575] | 765 | try : |
---|
| 766 | while 1 : |
---|
[1576] | 767 | char = minfile[pos] |
---|
| 768 | pos += 1 |
---|
| 769 | length = tags[ord(char)] |
---|
| 770 | if not length : |
---|
[1575] | 771 | continue |
---|
| 772 | if callable(length) : |
---|
[1576] | 773 | self.pos = pos |
---|
[1575] | 774 | length = length() |
---|
[1576] | 775 | pos = self.pos |
---|
| 776 | pos += length |
---|
[1575] | 777 | except IndexError : # EOF ? |
---|
| 778 | self.minfile.close() # reached EOF |
---|
[1591] | 779 | |
---|
| 780 | # now handle number of copies for each page (may differ). |
---|
[1675] | 781 | for pnum in range(1, self.pagecount + 1) : |
---|
[1591] | 782 | # if no number of copies defined, take 1, as explained |
---|
| 783 | # in PCLXL documentation. |
---|
| 784 | # NB : is number of copies is 0, the page won't be output |
---|
| 785 | # but the formula below is still correct : we want |
---|
| 786 | # to decrease the total number of pages in this case. |
---|
[1912] | 787 | page = self.pages.get(pnum, 1) |
---|
| 788 | copies = page["copies"] |
---|
| 789 | self.pagecount += (copies - 1) |
---|
[1980] | 790 | if self.debug : |
---|
[1982] | 791 | sys.stderr.write("%s*%s*%s*%s*%s\n" % (copies, page["mediatype"], page["mediasize"], page["orientation"], page["mediasource"])) |
---|
[1591] | 792 | |
---|
[1482] | 793 | return self.pagecount |
---|
[1487] | 794 | |
---|
[1482] | 795 | class PDLAnalyzer : |
---|
| 796 | """Generic PDL Analyzer class.""" |
---|
[1980] | 797 | def __init__(self, filename, debug=0) : |
---|
[1487] | 798 | """Initializes the PDL analyzer. |
---|
| 799 | |
---|
| 800 | filename is the name of the file or '-' for stdin. |
---|
| 801 | filename can also be a file-like object which |
---|
| 802 | supports read() and seek(). |
---|
| 803 | """ |
---|
[1980] | 804 | self.debug = debug |
---|
[1482] | 805 | self.filename = filename |
---|
[1570] | 806 | try : |
---|
| 807 | import psyco |
---|
| 808 | except ImportError : |
---|
| 809 | pass # Psyco is not installed |
---|
| 810 | else : |
---|
| 811 | # Psyco is installed, tell it to compile |
---|
| 812 | # the CPU intensive methods : PCL and PCLXL |
---|
| 813 | # parsing will greatly benefit from this, |
---|
| 814 | # for PostScript and PDF the difference is |
---|
| 815 | # barely noticeable since they are already |
---|
| 816 | # almost optimal, and much more speedy anyway. |
---|
| 817 | psyco.bind(PostScriptAnalyzer.getJobSize) |
---|
| 818 | psyco.bind(PDFAnalyzer.getJobSize) |
---|
[1686] | 819 | psyco.bind(ESCP2Analyzer.getJobSize) |
---|
[1570] | 820 | psyco.bind(PCLAnalyzer.getJobSize) |
---|
| 821 | psyco.bind(PCLXLAnalyzer.getJobSize) |
---|
[1482] | 822 | |
---|
| 823 | def getJobSize(self) : |
---|
| 824 | """Returns the job's size.""" |
---|
| 825 | self.openFile() |
---|
[1487] | 826 | try : |
---|
| 827 | pdlhandler = self.detectPDLHandler() |
---|
| 828 | except PDLAnalyzerError, msg : |
---|
| 829 | self.closeFile() |
---|
| 830 | raise PDLAnalyzerError, "ERROR : Unknown file format for %s (%s)" % (self.filename, msg) |
---|
| 831 | else : |
---|
[1482] | 832 | try : |
---|
[1980] | 833 | size = pdlhandler(self.infile, self.debug).getJobSize() |
---|
[1482] | 834 | finally : |
---|
| 835 | self.closeFile() |
---|
| 836 | return size |
---|
| 837 | |
---|
| 838 | def openFile(self) : |
---|
| 839 | """Opens the job's data stream for reading.""" |
---|
[1550] | 840 | self.mustclose = 0 # by default we don't want to close the file when finished |
---|
[1487] | 841 | if hasattr(self.filename, "read") and hasattr(self.filename, "seek") : |
---|
| 842 | # filename is in fact a file-like object |
---|
[1550] | 843 | infile = self.filename |
---|
[1487] | 844 | elif self.filename == "-" : |
---|
[1482] | 845 | # we must read from stdin |
---|
[1550] | 846 | infile = sys.stdin |
---|
[1482] | 847 | else : |
---|
| 848 | # normal file |
---|
[1553] | 849 | self.infile = open(self.filename, "rb") |
---|
[1550] | 850 | self.mustclose = 1 |
---|
| 851 | return |
---|
[1482] | 852 | |
---|
[1550] | 853 | # Use a temporary file, always seekable contrary to standard input. |
---|
[1553] | 854 | self.infile = tempfile.TemporaryFile(mode="w+b") |
---|
[1550] | 855 | while 1 : |
---|
| 856 | data = infile.read(MEGABYTE) |
---|
| 857 | if not data : |
---|
| 858 | break |
---|
| 859 | self.infile.write(data) |
---|
| 860 | self.infile.flush() |
---|
| 861 | self.infile.seek(0) |
---|
| 862 | |
---|
[1482] | 863 | def closeFile(self) : |
---|
[1487] | 864 | """Closes the job's data stream if we can close it.""" |
---|
| 865 | if self.mustclose : |
---|
| 866 | self.infile.close() |
---|
[1544] | 867 | else : |
---|
| 868 | # if we don't have to close the file, then |
---|
| 869 | # ensure the file pointer is reset to the |
---|
| 870 | # start of the file in case the process wants |
---|
| 871 | # to read the file again. |
---|
| 872 | try : |
---|
| 873 | self.infile.seek(0) |
---|
| 874 | except : |
---|
| 875 | pass # probably stdin, which is not seekable |
---|
[1482] | 876 | |
---|
[1701] | 877 | def isPostScript(self, sdata, edata) : |
---|
[1482] | 878 | """Returns 1 if data is PostScript, else 0.""" |
---|
[1701] | 879 | if sdata.startswith("%!") or \ |
---|
| 880 | sdata.startswith("\004%!") or \ |
---|
| 881 | sdata.startswith("\033%-12345X%!PS") or \ |
---|
| 882 | ((sdata[:128].find("\033%-12345X") != -1) and \ |
---|
| 883 | ((sdata.find("LANGUAGE=POSTSCRIPT") != -1) or \ |
---|
| 884 | (sdata.find("LANGUAGE = POSTSCRIPT") != -1) or \ |
---|
| 885 | (sdata.find("LANGUAGE = Postscript") != -1))) or \ |
---|
| 886 | (sdata.find("%!PS-Adobe") != -1) : |
---|
[1980] | 887 | if self.debug : |
---|
| 888 | sys.stderr.write("%s is a PostScript file\n" % str(self.filename)) |
---|
[1482] | 889 | return 1 |
---|
| 890 | else : |
---|
| 891 | return 0 |
---|
| 892 | |
---|
[1701] | 893 | def isPDF(self, sdata, edata) : |
---|
[1547] | 894 | """Returns 1 if data is PDF, else 0.""" |
---|
[1701] | 895 | if sdata.startswith("%PDF-") or \ |
---|
| 896 | sdata.startswith("\033%-12345X%PDF-") or \ |
---|
| 897 | ((sdata[:128].find("\033%-12345X") != -1) and (sdata.upper().find("LANGUAGE=PDF") != -1)) or \ |
---|
| 898 | (sdata.find("%PDF-") != -1) : |
---|
[1980] | 899 | if self.debug : |
---|
| 900 | sys.stderr.write("%s is a PDF file\n" % str(self.filename)) |
---|
[1547] | 901 | return 1 |
---|
| 902 | else : |
---|
| 903 | return 0 |
---|
| 904 | |
---|
[1701] | 905 | def isPCL(self, sdata, edata) : |
---|
[1482] | 906 | """Returns 1 if data is PCL, else 0.""" |
---|
[1701] | 907 | if sdata.startswith("\033E\033") or \ |
---|
| 908 | (sdata.startswith("\033*rbC") and (not edata[-3:] == "\f\033@")) or \ |
---|
[1702] | 909 | sdata.startswith("\033%8\033") or \ |
---|
[1701] | 910 | (sdata.find("\033%-12345X") != -1) : |
---|
[1980] | 911 | if self.debug : |
---|
| 912 | sys.stderr.write("%s is a PCL3/4/5 file\n" % str(self.filename)) |
---|
[1482] | 913 | return 1 |
---|
| 914 | else : |
---|
| 915 | return 0 |
---|
| 916 | |
---|
[1701] | 917 | def isPCLXL(self, sdata, edata) : |
---|
[1482] | 918 | """Returns 1 if data is PCLXL aka PCL6, else 0.""" |
---|
[1701] | 919 | if ((sdata[:128].find("\033%-12345X") != -1) and \ |
---|
| 920 | (sdata.find(" HP-PCL XL;") != -1) and \ |
---|
| 921 | ((sdata.find("LANGUAGE=PCLXL") != -1) or \ |
---|
| 922 | (sdata.find("LANGUAGE = PCLXL") != -1))) : |
---|
[1980] | 923 | if self.debug : |
---|
| 924 | sys.stderr.write("%s is a PCLXL (aka PCL6) file\n" % str(self.filename)) |
---|
[1482] | 925 | return 1 |
---|
| 926 | else : |
---|
| 927 | return 0 |
---|
| 928 | |
---|
[1701] | 929 | def isESCP2(self, sdata, edata) : |
---|
[1676] | 930 | """Returns 1 if data is ESC/P2, else 0.""" |
---|
[1701] | 931 | if sdata.startswith("\033@") or \ |
---|
| 932 | sdata.startswith("\033*") or \ |
---|
[1940] | 933 | sdata.startswith("\n\033@") or \ |
---|
| 934 | sdata.startswith("\0\0\0\033\1@EJL") : # ESC/P Raster ??? Seen on Stylus Photo 1284 |
---|
[1980] | 935 | if self.debug : |
---|
| 936 | sys.stderr.write("%s is an ESC/P2 file\n" % str(self.filename)) |
---|
[1676] | 937 | return 1 |
---|
| 938 | else : |
---|
| 939 | return 0 |
---|
| 940 | |
---|
[1482] | 941 | def detectPDLHandler(self) : |
---|
| 942 | """Tries to autodetect the document format. |
---|
| 943 | |
---|
| 944 | Returns the correct PDL handler class or None if format is unknown |
---|
| 945 | """ |
---|
| 946 | # Try to detect file type by reading first block of datas |
---|
| 947 | self.infile.seek(0) |
---|
[1699] | 948 | firstblock = self.infile.read(4 * KILOBYTE) |
---|
[1701] | 949 | try : |
---|
| 950 | self.infile.seek(-LASTBLOCKSIZE, 2) |
---|
[2026] | 951 | lastblock = self.infile.read(LASTBLOCKSIZE) |
---|
[1701] | 952 | except IOError : |
---|
| 953 | lastblock = "" |
---|
[2026] | 954 | |
---|
[1482] | 955 | self.infile.seek(0) |
---|
[1701] | 956 | if self.isPostScript(firstblock, lastblock) : |
---|
[1482] | 957 | return PostScriptAnalyzer |
---|
[1701] | 958 | elif self.isPCLXL(firstblock, lastblock) : |
---|
[1482] | 959 | return PCLXLAnalyzer |
---|
[1701] | 960 | elif self.isPDF(firstblock, lastblock) : |
---|
[1681] | 961 | return PDFAnalyzer |
---|
[1701] | 962 | elif self.isPCL(firstblock, lastblock) : |
---|
[1482] | 963 | return PCLAnalyzer |
---|
[1701] | 964 | elif self.isESCP2(firstblock, lastblock) : |
---|
[1676] | 965 | return ESCP2Analyzer |
---|
[1487] | 966 | else : |
---|
| 967 | raise PDLAnalyzerError, "Analysis of first data block failed." |
---|
| 968 | |
---|
| 969 | def main() : |
---|
| 970 | """Entry point for PDL Analyzer.""" |
---|
| 971 | if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) : |
---|
| 972 | sys.argv.append("-") |
---|
| 973 | |
---|
| 974 | totalsize = 0 |
---|
[1980] | 975 | debug = 0 |
---|
| 976 | minindex = 1 |
---|
| 977 | if sys.argv[1] == "--debug" : |
---|
| 978 | minindex = 2 |
---|
| 979 | debug = 1 |
---|
| 980 | for arg in sys.argv[minindex:] : |
---|
[1487] | 981 | try : |
---|
[1980] | 982 | parser = PDLAnalyzer(arg, debug) |
---|
[1487] | 983 | totalsize += parser.getJobSize() |
---|
| 984 | except PDLAnalyzerError, msg : |
---|
[1551] | 985 | sys.stderr.write("ERROR: %s\n" % msg) |
---|
[1487] | 986 | sys.stderr.flush() |
---|
| 987 | print "%s" % totalsize |
---|
| 988 | |
---|
| 989 | if __name__ == "__main__" : |
---|
[1577] | 990 | main() |
---|