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