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

Revision 1987, 43.5 kB (checked in by jalet, 19 years ago)

Added some debugging code to PCL3/4/5 parser

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