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

Revision 2302, 41.6 kB (checked in by jerome, 19 years ago)

Updated the FSF's address

  • 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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(r"%%Page: ") :
90                pagecount += 1
91            elif line.startswith(r"%%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(r"%%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        self.iscolor = None
536        found = 0
537        while not found :
538            line = self.infile.readline()
539            if not line :
540                break
541            if line[1:12] == " HP-PCL XL;" :
542                found = 1
543                endian = ord(line[0])
544                if endian == 0x29 :
545                    self.littleEndian()
546                elif endian == 0x28 :   
547                    self.bigEndian()
548                # elif endian == 0x27 : # TODO : This is the ESC code : parse it for PJL statements !
549                #
550                else :   
551                    raise PDLAnalyzerError, "Unknown endianness marker 0x%02x at start !" % endian
552        if not found :
553            raise PDLAnalyzerError, "This file doesn't seem to be PCLXL (aka PCL6)"
554           
555        # Initialize table of tags
556        self.tags = [ 0 ] * 256   
557       
558        # GhostScript's sources tell us that HP printers
559        # only accept little endianness, but we can handle both.
560        self.tags[0x28] = self.bigEndian    # BigEndian
561        self.tags[0x29] = self.littleEndian # LittleEndian
562       
563        self.tags[0x43] = self.beginPage    # BeginPage
564        self.tags[0x44] = self.endPage      # EndPage
565       
566        self.tags[0x6a] = self.setColorSpace    # to detect color/b&w mode
567       
568        self.tags[0xc0] = 1 # ubyte
569        self.tags[0xc1] = 2 # uint16
570        self.tags[0xc2] = 4 # uint32
571        self.tags[0xc3] = 2 # sint16
572        self.tags[0xc4] = 4 # sint32
573        self.tags[0xc5] = 4 # real32
574       
575        self.tags[0xc8] = self.array_8  # ubyte_array
576        self.tags[0xc9] = self.array_16 # uint16_array
577        self.tags[0xca] = self.array_32 # uint32_array
578        self.tags[0xcb] = self.array_16 # sint16_array
579        self.tags[0xcc] = self.array_32 # sint32_array
580        self.tags[0xcd] = self.array_32 # real32_array
581       
582        self.tags[0xd0] = 2 # ubyte_xy
583        self.tags[0xd1] = 4 # uint16_xy
584        self.tags[0xd2] = 8 # uint32_xy
585        self.tags[0xd3] = 4 # sint16_xy
586        self.tags[0xd4] = 8 # sint32_xy
587        self.tags[0xd5] = 8 # real32_xy
588       
589        self.tags[0xe0] = 4  # ubyte_box
590        self.tags[0xe1] = 8  # uint16_box
591        self.tags[0xe2] = 16 # uint32_box
592        self.tags[0xe3] = 8  # sint16_box
593        self.tags[0xe4] = 16 # sint32_box
594        self.tags[0xe5] = 16 # real32_box
595       
596        self.tags[0xf8] = 1 # attr_ubyte
597        self.tags[0xf9] = 2 # attr_uint16
598       
599        self.tags[0xfa] = self.embeddedData      # dataLength
600        self.tags[0xfb] = self.embeddedDataSmall # dataLengthByte
601           
602        # color spaces   
603        self.BWColorSpace = "".join([chr(0x00), chr(0xf8), chr(0x03)])
604        self.GrayColorSpace = "".join([chr(0x01), chr(0xf8), chr(0x03)])
605        self.RGBColorSpace = "".join([chr(0x02), chr(0xf8), chr(0x03)])
606       
607        # set number of copies
608        self.setNumberOfCopies = "".join([chr(0xf8), chr(0x31)]) 
609           
610    def beginPage(self) :
611        """Indicates the beginning of a new page, and extracts media information."""
612        self.pagecount += 1
613       
614        # Default values
615        mediatypelabel = "Plain"
616        mediasourcelabel = "Main"
617        mediasizelabel = "Default"
618        orientationlabel = "Portrait"
619       
620        # Now go upstream to decode media type, size, source, and orientation
621        # this saves time because we don't need a complete parser !
622        minfile = self.minfile
623        pos = self.pos - 2
624        while pos > 0 : # safety check : don't go back to far !
625            val = ord(minfile[pos])
626            if val in (0x44, 0x48, 0x41) : # if previous endPage or openDataSource or beginSession (first page)
627                break
628            if val == 0x26 :   
629                mediasource = ord(minfile[pos - 2])
630                mediasourcelabel = self.mediasources.get(mediasource, str(mediasource))
631                pos = pos - 4
632            elif val == 0x25 :
633                mediasize = ord(minfile[pos - 2])
634                mediasizelabel = self.mediasizes.get(mediasize, str(mediasize))
635                pos = pos - 4
636            elif val == 0x28 :   
637                orientation = ord(minfile[pos - 2])
638                orienationlabel = self.orientations.get(orientation, str(orientation))
639                pos = pos - 4
640            elif val == 0x27 :   
641                savepos = pos
642                pos = pos - 1
643                while pos > 0 : # safety check : don't go back to far !
644                    val = ord(minfile[pos])
645                    pos -= 1   
646                    if val == 0xc8 :
647                        break
648                mediatypelabel = minfile[pos:savepos] # TODO : INCORRECT, WE HAVE TO STRIP OUT THE UBYTE ARRAY'S LENGTH !!!
649            # else : TODO : CUSTOM MEDIA SIZE AND UNIT !
650            else :   
651                pos = pos - 2   # ignored
652        self.pages[self.pagecount] = { "copies" : 1, 
653                                       "orientation" : orientationlabel, 
654                                       "mediatype" : mediatypelabel, 
655                                       "mediasize" : mediasizelabel,
656                                       "mediasource" : mediasourcelabel,
657                                     } 
658        return 0
659       
660    def endPage(self) :   
661        """Indicates the end of a page."""
662        pos = self.pos
663        pos3 = pos - 3
664        minfile = self.minfile
665        if minfile[pos3:pos-1] == self.setNumberOfCopies :
666            # The EndPage operator may be preceded by a PageCopies attribute
667            # So set number of copies for current page.
668            # From what I read in PCLXL documentation, the number
669            # of copies is an unsigned 16 bits integer
670            self.pages[self.pagecount]["copies"] = unpack(self.endianness + "H", minfile[pos-5:pos3])[0]
671        return 0
672       
673    def setColorSpace(self) :   
674        """Changes the color space."""
675        if self.minfile[self.pos-4:self.pos-1] == self.RGBColorSpace :
676            self.iscolor = 1
677        return 0
678           
679    def array_8(self) :   
680        """Handles byte arrays."""
681        pos = self.pos
682        datatype = self.minfile[pos]
683        pos += 1
684        length = self.tags[ord(datatype)]
685        if callable(length) :
686            self.pos = pos
687            length = length()
688            pos = self.pos
689        posl = pos + length
690        self.pos = posl
691        if length == 1 :   
692            return unpack("B", self.minfile[pos:posl])[0]
693        elif length == 2 :   
694            return unpack(self.endianness + "H", self.minfile[pos:posl])[0]
695        elif length == 4 :   
696            return unpack(self.endianness + "I", self.minfile[pos:posl])[0]
697        else :   
698            raise PDLAnalyzerError, "Error on array size at %s" % self.pos
699       
700    def array_16(self) :   
701        """Handles byte arrays."""
702        pos = self.pos
703        datatype = self.minfile[pos]
704        pos += 1
705        length = self.tags[ord(datatype)]
706        if callable(length) :
707            self.pos = pos
708            length = length()
709            pos = self.pos
710        posl = pos + length
711        self.pos = posl
712        if length == 1 :   
713            return 2 * unpack("B", self.minfile[pos:posl])[0]
714        elif length == 2 :   
715            return 2 * unpack(self.endianness + "H", self.minfile[pos:posl])[0]
716        elif length == 4 :   
717            return 2 * unpack(self.endianness + "I", self.minfile[pos:posl])[0]
718        else :   
719            raise PDLAnalyzerError, "Error on array size at %s" % self.pos
720       
721    def array_32(self) :   
722        """Handles byte arrays."""
723        pos = self.pos
724        datatype = self.minfile[pos]
725        pos += 1
726        length = self.tags[ord(datatype)]
727        if callable(length) :
728            self.pos = pos
729            length = length()
730            pos = self.pos
731        posl = pos + length
732        self.pos = posl
733        if length == 1 :   
734            return 4 * unpack("B", self.minfile[pos:posl])[0]
735        elif length == 2 :   
736            return 4 * unpack(self.endianness + "H", self.minfile[pos:posl])[0]
737        elif length == 4 :   
738            return 4 * unpack(self.endianness + "I", self.minfile[pos:posl])[0]
739        else :   
740            raise PDLAnalyzerError, "Error on array size at %s" % self.pos
741       
742    def embeddedDataSmall(self) :
743        """Handle small amounts of data."""
744        pos = self.pos
745        length = ord(self.minfile[pos])
746        self.pos = pos + 1
747        return length
748       
749    def embeddedData(self) :
750        """Handle normal amounts of data."""
751        pos = self.pos
752        pos4 = pos + 4
753        self.pos = pos4
754        return unpack(self.endianness + "I", self.minfile[pos:pos4])[0]
755       
756    def littleEndian(self) :       
757        """Toggles to little endianness."""
758        self.endianness = "<" # little endian
759        return 0
760       
761    def bigEndian(self) :   
762        """Toggles to big endianness."""
763        self.endianness = ">" # big endian
764        return 0
765   
766    def getJobSize(self) :
767        """Counts pages in a PCLXL (PCL6) document.
768       
769           Algorithm by Jerome Alet.
770           
771           The documentation used for this was :
772         
773           HP PCL XL Feature Reference
774           Protocol Class 2.0
775           http://www.hpdevelopersolutions.com/downloads/64/358/xl_ref20r22.pdf
776        """
777        infileno = self.infile.fileno()
778        self.pages = {}
779        self.minfile = minfile = mmap.mmap(infileno, os.fstat(infileno)[6], prot=mmap.PROT_READ, flags=mmap.MAP_SHARED)
780        tags = self.tags
781        self.pagecount = 0
782        self.pos = pos = self.infile.tell()
783        try :
784            while 1 :
785                char = minfile[pos]
786                pos += 1
787                length = tags[ord(char)]
788                if not length :
789                    continue
790                if callable(length) :   
791                    self.pos = pos
792                    length = length()
793                    pos = self.pos
794                pos += length   
795        except IndexError : # EOF ?
796            self.minfile.close() # reached EOF
797           
798        # now handle number of copies for each page (may differ).
799        if self.iscolor :
800            colormode = "Color"
801        else :   
802            colormode = "Black"
803        for pnum in range(1, self.pagecount + 1) :
804            # if no number of copies defined, take 1, as explained
805            # in PCLXL documentation.
806            # NB : is number of copies is 0, the page won't be output
807            # but the formula below is still correct : we want
808            # to decrease the total number of pages in this case.
809            page = self.pages.get(pnum, 1)
810            copies = page["copies"]
811            self.pagecount += (copies - 1)
812            if self.debug :
813                sys.stderr.write("%s*%s*%s*%s*%s*%s\n" % (copies, 
814                                                          page["mediatype"], 
815                                                          page["mediasize"], 
816                                                          page["orientation"], 
817                                                          page["mediasource"], 
818                                                          colormode))
819        return self.pagecount
820       
821class PDLAnalyzer :   
822    """Generic PDL Analyzer class."""
823    def __init__(self, filename, debug=0) :
824        """Initializes the PDL analyzer.
825       
826           filename is the name of the file or '-' for stdin.
827           filename can also be a file-like object which
828           supports read() and seek().
829        """
830        self.debug = debug
831        self.filename = filename
832        try :
833            import psyco 
834        except ImportError :   
835            pass # Psyco is not installed
836        else :   
837            # Psyco is installed, tell it to compile
838            # the CPU intensive methods : PCL and PCLXL
839            # parsing will greatly benefit from this,
840            # for PostScript and PDF the difference is
841            # barely noticeable since they are already
842            # almost optimal, and much more speedy anyway.
843            psyco.bind(PostScriptAnalyzer.getJobSize)
844            psyco.bind(PDFAnalyzer.getJobSize)
845            psyco.bind(ESCP2Analyzer.getJobSize)
846            psyco.bind(PCLAnalyzer.getJobSize)
847            psyco.bind(PCLXLAnalyzer.getJobSize)
848       
849    def getJobSize(self) :   
850        """Returns the job's size."""
851        self.openFile()
852        try :
853            pdlhandler = self.detectPDLHandler()
854        except PDLAnalyzerError, msg :   
855            self.closeFile()
856            raise PDLAnalyzerError, "ERROR : Unknown file format for %s (%s)" % (self.filename, msg)
857        else :
858            try :
859                size = pdlhandler(self.infile, self.debug).getJobSize()
860            finally :   
861                self.closeFile()
862            return size
863       
864    def openFile(self) :   
865        """Opens the job's data stream for reading."""
866        self.mustclose = 0  # by default we don't want to close the file when finished
867        if hasattr(self.filename, "read") and hasattr(self.filename, "seek") :
868            # filename is in fact a file-like object
869            infile = self.filename
870        elif self.filename == "-" :
871            # we must read from stdin
872            infile = sys.stdin
873        else :   
874            # normal file
875            self.infile = open(self.filename, "rb")
876            self.mustclose = 1
877            return
878           
879        # Use a temporary file, always seekable contrary to standard input.
880        self.infile = tempfile.TemporaryFile(mode="w+b")
881        while 1 :
882            data = infile.read(MEGABYTE) 
883            if not data :
884                break
885            self.infile.write(data)
886        self.infile.flush()   
887        self.infile.seek(0)
888           
889    def closeFile(self) :       
890        """Closes the job's data stream if we can close it."""
891        if self.mustclose :
892            self.infile.close()   
893        else :   
894            # if we don't have to close the file, then
895            # ensure the file pointer is reset to the
896            # start of the file in case the process wants
897            # to read the file again.
898            try :
899                self.infile.seek(0)
900            except :   
901                pass    # probably stdin, which is not seekable
902       
903    def isPostScript(self, sdata, edata) :   
904        """Returns 1 if data is PostScript, else 0."""
905        if sdata.startswith("%!") or \
906           sdata.startswith("\004%!") or \
907           sdata.startswith("\033%-12345X%!PS") or \
908           ((sdata[:128].find("\033%-12345X") != -1) and \
909             ((sdata.find("LANGUAGE=POSTSCRIPT") != -1) or \
910              (sdata.find("LANGUAGE = POSTSCRIPT") != -1) or \
911              (sdata.find("LANGUAGE = Postscript") != -1))) or \
912              (sdata.find("%!PS-Adobe") != -1) :
913            if self.debug : 
914                sys.stderr.write("%s is a PostScript file\n" % str(self.filename))
915            return 1
916        else :   
917            return 0
918       
919    def isPDF(self, sdata, edata) :   
920        """Returns 1 if data is PDF, else 0."""
921        if sdata.startswith("%PDF-") or \
922           sdata.startswith("\033%-12345X%PDF-") or \
923           ((sdata[:128].find("\033%-12345X") != -1) and (sdata.upper().find("LANGUAGE=PDF") != -1)) or \
924           (sdata.find("%PDF-") != -1) :
925            if self.debug : 
926                sys.stderr.write("%s is a PDF file\n" % str(self.filename))
927            return 1
928        else :   
929            return 0
930       
931    def isPCL(self, sdata, edata) :   
932        """Returns 1 if data is PCL, else 0."""
933        if sdata.startswith("\033E\033") or \
934           (sdata.startswith("\033*rbC") and (not edata[-3:] == "\f\033@")) or \
935           sdata.startswith("\033%8\033") or \
936           (sdata.find("\033%-12345X") != -1) :
937            if self.debug : 
938                sys.stderr.write("%s is a PCL3/4/5 file\n" % str(self.filename))
939            return 1
940        else :   
941            return 0
942       
943    def isPCLXL(self, sdata, edata) :   
944        """Returns 1 if data is PCLXL aka PCL6, else 0."""
945        if ((sdata[:128].find("\033%-12345X") != -1) and \
946             (sdata.find(" HP-PCL XL;") != -1) and \
947             ((sdata.find("LANGUAGE=PCLXL") != -1) or \
948              (sdata.find("LANGUAGE = PCLXL") != -1))) :
949            if self.debug : 
950                sys.stderr.write("%s is a PCLXL (aka PCL6) file\n" % str(self.filename))
951            return 1
952        else :   
953            return 0
954           
955    def isESCP2(self, sdata, edata) :       
956        """Returns 1 if data is ESC/P2, else 0."""
957        if sdata.startswith("\033@") or \
958           sdata.startswith("\033*") or \
959           sdata.startswith("\n\033@") or \
960           sdata.startswith("\0\0\0\033\1@EJL") : # ESC/P Raster ??? Seen on Stylus Photo 1284
961            if self.debug : 
962                sys.stderr.write("%s is an ESC/P2 file\n" % str(self.filename))
963            return 1
964        else :   
965            return 0
966   
967    def detectPDLHandler(self) :   
968        """Tries to autodetect the document format.
969       
970           Returns the correct PDL handler class or None if format is unknown
971        """   
972        # Try to detect file type by reading first block of datas   
973        self.infile.seek(0)
974        firstblock = self.infile.read(4 * KILOBYTE)
975        try :
976            self.infile.seek(-LASTBLOCKSIZE, 2)
977            lastblock = self.infile.read(LASTBLOCKSIZE)
978        except IOError :   
979            lastblock = ""
980           
981        self.infile.seek(0)
982        if self.isPostScript(firstblock, lastblock) :
983            return PostScriptAnalyzer
984        elif self.isPCLXL(firstblock, lastblock) :   
985            return PCLXLAnalyzer
986        elif self.isPDF(firstblock, lastblock) :   
987            return PDFAnalyzer
988        elif self.isPCL(firstblock, lastblock) :   
989            return PCLAnalyzer
990        elif self.isESCP2(firstblock, lastblock) :   
991            return ESCP2Analyzer
992        else :   
993            raise PDLAnalyzerError, "Analysis of first data block failed."
994           
995def main() :   
996    """Entry point for PDL Analyzer."""
997    if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) :
998        sys.argv.append("-")
999       
1000    totalsize = 0   
1001    debug = 0
1002    minindex = 1
1003    if sys.argv[1] == "--debug" :
1004        minindex = 2
1005        debug = 1
1006    for arg in sys.argv[minindex:] :
1007        try :
1008            parser = PDLAnalyzer(arg, debug)
1009            totalsize += parser.getJobSize()
1010        except PDLAnalyzerError, msg :   
1011            sys.stderr.write("ERROR: %s\n" % msg)
1012            sys.stderr.flush()
1013    print "%s" % totalsize
1014   
1015if __name__ == "__main__" :   
1016    main()
Note: See TracBrowser for help on using the browser.