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

Revision 2003, 44.0 kB (checked in by jalet, 19 years ago)

Of course if I forget some files during the commits, the software doesn't
work as expected ;-)

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