root / pkpgcounter / trunk / pkpgpdls / postscript.py @ 520

Revision 520, 9.4 kB (checked in by jerome, 16 years ago)

Code cleaning.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Auth Date Id Rev
RevLine 
[193]1#! /usr/bin/env python
2# -*- coding: ISO-8859-15 -*-
[191]3#
4# pkpgcounter : a generic Page Description Language parser
5#
[443]6# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
[463]7# This program is free software: you can redistribute it and/or modify
[191]8# it under the terms of the GNU General Public License as published by
[463]9# the Free Software Foundation, either version 3 of the License, or
[191]10# (at your option) any later version.
[463]11#
[191]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
[463]18# along with this program.  If not, see <http://www.gnu.org/licenses/>.
[191]19#
20# $Id$
21#
[193]22
[357]23"""This modules implements a page counter for PostScript documents."""
24
[193]25import sys
[283]26import os
27import tempfile
[193]28import popen2
29
[235]30import pdlparser
[283]31import inkcoverage
[193]32
[220]33class Parser(pdlparser.PDLParser) :
[193]34    """A parser for PostScript documents."""
[492]35    totiffcommands = [ 'gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r"%(dpi)i" -sOutputFile="%(outfname)s" "%(infname)s"' ]
[491]36    openmode = "rU"
[220]37    def isValid(self) :   
[387]38        """Returns True if data is PostScript, else False."""
[520]39        if self.parent.firstblock.startswith("%!") or \
40           self.parent.firstblock.startswith("\004%!") or \
41           self.parent.firstblock.startswith("\033%-12345X%!PS") or \
42           ((self.parent.firstblock[:128].find("\033%-12345X") != -1) and \
43             ((self.parent.firstblock.find("LANGUAGE=POSTSCRIPT") != -1) or \
44              (self.parent.firstblock.find("LANGUAGE = POSTSCRIPT") != -1) or \
45              (self.parent.firstblock.find("LANGUAGE = Postscript") != -1))) or \
46              (self.parent.firstblock.find("%!PS-Adobe") != -1) :
[252]47            self.logdebug("DEBUG: Input file is in the PostScript format.")
[387]48            return True
[220]49        else :   
[387]50            return False
[220]51       
[193]52    def throughGhostScript(self) :
53        """Get the count through GhostScript, useful for non-DSC compliant PS files."""
[252]54        self.logdebug("Internal parser sucks, using GhostScript instead...")
[283]55        command = 'gs -sDEVICE=bbox -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET - 2>&1 | grep -c "%%HiResBoundingBox:" 2>/dev/null'
[491]56        pagecount = 0
57        # we need to reopen the input file in binary mode again, just in case
58        # otherwise we might break the original file's contents.
[520]59        infile = open(self.parent.filename, "rb")
[193]60        try :
[491]61            child = popen2.Popen4(command)
62            try :
63                data = infile.read(pdlparser.MEGABYTE)   
64                while data :
65                    child.tochild.write(data)
66                    data = infile.read(pdlparser.MEGABYTE)
67                child.tochild.flush()
68                child.tochild.close()   
69            except (IOError, OSError), msg :   
70                raise pdlparser.PDLParserError, "Problem during analysis of Binary PostScript document : %s" % msg
71               
72            pagecount = 0
73            try :
74                pagecount = int(child.fromchild.readline().strip())
75            except (IOError, OSError, AttributeError, ValueError), msg :
76                raise pdlparser.PDLParserError, "Problem during analysis of Binary PostScript document : %s" % msg
77            child.fromchild.close()
[193]78           
[491]79            try :
80                child.wait()
81            except OSError, msg :   
82                raise pdlparser.PDLParserError, "Problem during analysis of Binary PostScript document : %s" % msg
83        finally :       
84            infile.close()
[273]85        self.logdebug("GhostScript said : %s pages" % pagecount)   
[193]86        return pagecount * self.copies
87       
88    def natively(self) :
89        """Count pages in a DSC compliant PostScript document."""
90        pagecount = 0
[273]91        self.pages = { 0 : { "copies" : 1 } }
[263]92        oldpagenum = None
[252]93        previousline = ""
[273]94        notrust = 0
[314]95        prescribe = 0 # Kyocera's Prescribe commands
[323]96        acrobatmarker = 0
[444]97        pagescomment = None
[491]98        for line in self.infile :
99            line = line.strip()
[321]100            if (not prescribe) and line.startswith(r"%%BeginResource: procset pdf") \
[323]101               and not acrobatmarker :
[273]102                notrust = 1 # Let this stuff be managed by GhostScript, but we still extract number of copies
[334]103            elif line.startswith(r"%ADOPrintSettings: L") :
[323]104                acrobatmarker = 1
[314]105            elif line.startswith("!R!") :
106                prescribe = 1
[444]107            elif line.startswith(r"%%Pages: ") :
108                try :
[447]109                    pagescomment = max(pagescomment or 0, int(line.split()[1]))
[444]110                except ValueError :
111                    pass # strange, to say the least
[272]112            elif line.startswith(r"%%Page: ") or line.startswith(r"(%%[Page: ") :
[263]113                proceed = 1
114                try :
[437]115                    # treats both "%%Page: x x" and "%%Page: (x-y) z" (probably N-up mode)
116                    newpagenum = int(line.split(']')[0].split()[-1])
[263]117                except :   
[323]118                    notinteger = 1 # It seems that sometimes it's not an integer but an EPS file name
[263]119                else :   
[323]120                    notinteger = 0
[263]121                    if newpagenum == oldpagenum :
122                        proceed = 0
123                    else :
124                        oldpagenum = newpagenum
[323]125                if proceed and not notinteger :       
[263]126                    pagecount += 1
[273]127                    self.pages[pagecount] = { "copies" : self.pages[pagecount-1]["copies"] }
[208]128            elif line.startswith(r"%%Requirements: numcopies(") :   
[193]129                try :
[491]130                    number = int(line.split('(')[1].split(')')[0])
[193]131                except :     
132                    pass
133                else :   
[273]134                    if number > self.pages[pagecount]["copies"] :
135                        self.pages[pagecount]["copies"] = number
[208]136            elif line.startswith(r"%%BeginNonPPDFeature: NumCopies ") :
[193]137                # handle # of copies set by some Windows printer driver
138                try :
[491]139                    number = int(line.split()[2])
[193]140                except :     
141                    pass
142                else :   
[273]143                    if number > self.pages[pagecount]["copies"] :
144                        self.pages[pagecount]["copies"] = number
[193]145            elif line.startswith("1 dict dup /NumCopies ") :
146                # handle # of copies set by mozilla/kprinter
147                try :
[491]148                    number = int(line.split()[4])
[193]149                except :     
150                    pass
151                else :   
[273]152                    if number > self.pages[pagecount]["copies"] :
153                        self.pages[pagecount]["copies"] = number
[389]154            elif line.startswith("{ pop 1 dict dup /NumCopies ") :
155                # handle # of copies set by firefox/kprinter/cups (alternate syntax)
156                try :
[491]157                    number = int(line.split()[6])
[389]158                except :
159                    pass
160                else :
161                    if number > self.pages[pagecount]["copies"] :
162                        self.pages[pagecount]["copies"] = number
[248]163            elif line.startswith("/languagelevel where{pop languagelevel}{1}ifelse 2 ge{1 dict dup/NumCopies") :
164                try :
[491]165                    number = int(previousline[2:])
[248]166                except :
167                    pass
168                else :
[273]169                    if number > self.pages[pagecount]["copies"] :
170                        self.pages[pagecount]["copies"] = number
[290]171            elif line.startswith("/#copies ") :
172                try :
[491]173                    number = int(line.split()[1])
[290]174                except :     
175                    pass
176                else :   
177                    if number > self.pages[pagecount]["copies"] :
178                        self.pages[pagecount]["copies"] = number
[448]179            elif line.startswith(r"%RBINumCopies: ") :   
180                try :
[491]181                    number = int(line.split()[1])
[448]182                except :     
183                    pass
184                else :   
185                    if number > self.pages[pagecount]["copies"] :
186                        self.pages[pagecount]["copies"] = number
[248]187            previousline = line
188           
189        # extract max number of copies to please the ghostscript parser, just   
190        # in case we will use it later
[273]191        self.copies = max([ v["copies"] for (k, v) in self.pages.items() ])
[193]192       
[248]193        # now apply the number of copies to each page
[448]194        if not pagecount and pagescomment :   
195            pagecount = pagescomment
[248]196        for pnum in range(1, pagecount + 1) :
[448]197            page = self.pages.get(pnum, self.pages.get(1, self.pages.get(0, { "copies" : 1 })))
[248]198            copies = page["copies"]
199            pagecount += (copies - 1)
[252]200            self.logdebug("%s * page #%s" % (copies, pnum))
[444]201           
[273]202        self.logdebug("Internal parser said : %s pages" % pagecount)
[384]203        return (pagecount, notrust)
[273]204       
[193]205    def getJobSize(self) :   
206        """Count pages in PostScript document."""
[202]207        self.copies = 1
[384]208        (nbpages, notrust) = self.natively()
209        newnbpages = nbpages
[444]210        if notrust or not nbpages :
[384]211            try :
212                newnbpages = self.throughGhostScript()
213            except pdlparser.PDLParserError, msg :
214                self.logdebug(msg)
215        return max(nbpages, newnbpages)   
Note: See TracBrowser for help on using the browser.