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