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

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

Small fix for the PCL3/4/5 parser because of some drivers

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