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

Revision 2147, 40.7 kB (checked in by jerome, 19 years ago)

Removed all references to $Log$

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