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

Revision 2139, 45.7 kB (checked in by jerome, 19 years ago)

Added the Log keyword property

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