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

Revision 1980, 42.9 kB (checked in by jalet, 19 years ago)

Added a --debug command line option to pkpgcounter, for people interested
in seeing what happens, and what will be available in the future :-)

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