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

Revision 1940, 41.6 kB (checked in by jalet, 19 years ago)

Fixed Epson Stylus Photo problem in software accounting

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