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