root / pykota / trunk / pykota / pdlanalyzer.py @ 2012

Revision 2012, 45.2 kB (checked in by jalet, 19 years ago)

Another fix for PCL3/4/5

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