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

Revision 2026, 45.3 kB (checked in by jalet, 19 years ago)

Fixed a fuckingly strange exception by cleverly ignoring it entirely :-)

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