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