[193] | 1 | #! /usr/bin/env python |
---|
| 2 | # -*- coding: ISO-8859-15 -*- |
---|
[191] | 3 | # |
---|
| 4 | # pkpgcounter : a generic Page Description Language parser |
---|
| 5 | # |
---|
[303] | 6 | # (c) 2003, 2004, 2005, 2006 Jerome Alet <alet@librelogiciel.com> |
---|
[191] | 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 |
---|
[211] | 19 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
---|
[191] | 20 | # |
---|
| 21 | # $Id$ |
---|
| 22 | # |
---|
[193] | 23 | |
---|
| 24 | import sys |
---|
[283] | 25 | import os |
---|
| 26 | import tempfile |
---|
[193] | 27 | import popen2 |
---|
| 28 | |
---|
[235] | 29 | import pdlparser |
---|
[283] | 30 | import inkcoverage |
---|
[193] | 31 | |
---|
[220] | 32 | class Parser(pdlparser.PDLParser) : |
---|
[193] | 33 | """A parser for PostScript documents.""" |
---|
[220] | 34 | def isValid(self) : |
---|
| 35 | """Returns 1 if data is PostScript, else 0.""" |
---|
| 36 | if self.firstblock.startswith("%!") or \ |
---|
| 37 | self.firstblock.startswith("\004%!") or \ |
---|
| 38 | self.firstblock.startswith("\033%-12345X%!PS") or \ |
---|
| 39 | ((self.firstblock[:128].find("\033%-12345X") != -1) and \ |
---|
| 40 | ((self.firstblock.find("LANGUAGE=POSTSCRIPT") != -1) or \ |
---|
| 41 | (self.firstblock.find("LANGUAGE = POSTSCRIPT") != -1) or \ |
---|
| 42 | (self.firstblock.find("LANGUAGE = Postscript") != -1))) or \ |
---|
| 43 | (self.firstblock.find("%!PS-Adobe") != -1) : |
---|
[252] | 44 | self.logdebug("DEBUG: Input file is in the PostScript format.") |
---|
[220] | 45 | return 1 |
---|
| 46 | else : |
---|
| 47 | return 0 |
---|
| 48 | |
---|
[193] | 49 | def throughGhostScript(self) : |
---|
| 50 | """Get the count through GhostScript, useful for non-DSC compliant PS files.""" |
---|
[252] | 51 | self.logdebug("Internal parser sucks, using GhostScript instead...") |
---|
[193] | 52 | self.infile.seek(0) |
---|
[283] | 53 | command = 'gs -sDEVICE=bbox -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET - 2>&1 | grep -c "%%HiResBoundingBox:" 2>/dev/null' |
---|
[193] | 54 | child = popen2.Popen4(command) |
---|
| 55 | try : |
---|
[237] | 56 | data = self.infile.read(pdlparser.MEGABYTE) |
---|
[193] | 57 | while data : |
---|
| 58 | child.tochild.write(data) |
---|
[237] | 59 | data = self.infile.read(pdlparser.MEGABYTE) |
---|
[193] | 60 | child.tochild.flush() |
---|
| 61 | child.tochild.close() |
---|
| 62 | except (IOError, OSError), msg : |
---|
[200] | 63 | raise pdlparser.PDLParserError, "Problem during analysis of Binary PostScript document : %s" % msg |
---|
[193] | 64 | |
---|
| 65 | pagecount = 0 |
---|
| 66 | try : |
---|
| 67 | pagecount = int(child.fromchild.readline().strip()) |
---|
| 68 | except (IOError, OSError, AttributeError, ValueError), msg : |
---|
[200] | 69 | raise pdlparser.PDLParserError, "Problem during analysis of Binary PostScript document : %s" % msg |
---|
[193] | 70 | child.fromchild.close() |
---|
| 71 | |
---|
| 72 | try : |
---|
| 73 | child.wait() |
---|
| 74 | except OSError, msg : |
---|
[200] | 75 | raise pdlparser.PDLParserError, "Problem during analysis of Binary PostScript document : %s" % msg |
---|
[273] | 76 | self.logdebug("GhostScript said : %s pages" % pagecount) |
---|
[193] | 77 | return pagecount * self.copies |
---|
| 78 | |
---|
| 79 | def natively(self) : |
---|
| 80 | """Count pages in a DSC compliant PostScript document.""" |
---|
| 81 | self.infile.seek(0) |
---|
| 82 | pagecount = 0 |
---|
[273] | 83 | self.pages = { 0 : { "copies" : 1 } } |
---|
[263] | 84 | oldpagenum = None |
---|
[252] | 85 | previousline = "" |
---|
[273] | 86 | notrust = 0 |
---|
[314] | 87 | prescribe = 0 # Kyocera's Prescribe commands |
---|
[323] | 88 | acrobatmarker = 0 |
---|
[193] | 89 | for line in self.infile.xreadlines() : |
---|
[321] | 90 | if (not prescribe) and line.startswith(r"%%BeginResource: procset pdf") \ |
---|
[323] | 91 | and not acrobatmarker : |
---|
[273] | 92 | notrust = 1 # Let this stuff be managed by GhostScript, but we still extract number of copies |
---|
[323] | 93 | elif line.startswith(r"%ADOPrintSettings: L3") : |
---|
| 94 | acrobatmarker = 1 |
---|
[314] | 95 | elif line.startswith("!R!") : |
---|
| 96 | prescribe = 1 |
---|
[272] | 97 | elif line.startswith(r"%%Page: ") or line.startswith(r"(%%[Page: ") : |
---|
[263] | 98 | proceed = 1 |
---|
| 99 | try : |
---|
| 100 | newpagenum = int(line.split(']')[0].split()[1]) |
---|
| 101 | except : |
---|
[323] | 102 | notinteger = 1 # It seems that sometimes it's not an integer but an EPS file name |
---|
[263] | 103 | else : |
---|
[323] | 104 | notinteger = 0 |
---|
[263] | 105 | if newpagenum == oldpagenum : |
---|
| 106 | proceed = 0 |
---|
| 107 | else : |
---|
| 108 | oldpagenum = newpagenum |
---|
[323] | 109 | if proceed and not notinteger : |
---|
[263] | 110 | pagecount += 1 |
---|
[273] | 111 | self.pages[pagecount] = { "copies" : self.pages[pagecount-1]["copies"] } |
---|
[208] | 112 | elif line.startswith(r"%%Requirements: numcopies(") : |
---|
[193] | 113 | try : |
---|
| 114 | number = int(line.strip().split('(')[1].split(')')[0]) |
---|
| 115 | except : |
---|
| 116 | pass |
---|
| 117 | else : |
---|
[273] | 118 | if number > self.pages[pagecount]["copies"] : |
---|
| 119 | self.pages[pagecount]["copies"] = number |
---|
[208] | 120 | elif line.startswith(r"%%BeginNonPPDFeature: NumCopies ") : |
---|
[193] | 121 | # handle # of copies set by some Windows printer driver |
---|
| 122 | try : |
---|
| 123 | number = int(line.strip().split()[2]) |
---|
| 124 | except : |
---|
| 125 | pass |
---|
| 126 | else : |
---|
[273] | 127 | if number > self.pages[pagecount]["copies"] : |
---|
| 128 | self.pages[pagecount]["copies"] = number |
---|
[193] | 129 | elif line.startswith("1 dict dup /NumCopies ") : |
---|
| 130 | # handle # of copies set by mozilla/kprinter |
---|
| 131 | try : |
---|
| 132 | number = int(line.strip().split()[4]) |
---|
| 133 | except : |
---|
| 134 | pass |
---|
| 135 | else : |
---|
[273] | 136 | if number > self.pages[pagecount]["copies"] : |
---|
| 137 | self.pages[pagecount]["copies"] = number |
---|
[248] | 138 | elif line.startswith("/languagelevel where{pop languagelevel}{1}ifelse 2 ge{1 dict dup/NumCopies") : |
---|
| 139 | try : |
---|
| 140 | number = int(previousline.strip()[2:]) |
---|
| 141 | except : |
---|
| 142 | pass |
---|
| 143 | else : |
---|
[273] | 144 | if number > self.pages[pagecount]["copies"] : |
---|
| 145 | self.pages[pagecount]["copies"] = number |
---|
[290] | 146 | elif line.startswith("/#copies ") : |
---|
| 147 | try : |
---|
| 148 | number = int(line.strip().split()[1]) |
---|
| 149 | except : |
---|
| 150 | pass |
---|
| 151 | else : |
---|
| 152 | if number > self.pages[pagecount]["copies"] : |
---|
| 153 | self.pages[pagecount]["copies"] = number |
---|
[248] | 154 | previousline = line |
---|
| 155 | |
---|
| 156 | # extract max number of copies to please the ghostscript parser, just |
---|
| 157 | # in case we will use it later |
---|
[273] | 158 | self.copies = max([ v["copies"] for (k, v) in self.pages.items() ]) |
---|
[193] | 159 | |
---|
[248] | 160 | # now apply the number of copies to each page |
---|
| 161 | for pnum in range(1, pagecount + 1) : |
---|
[273] | 162 | page = self.pages.get(pnum, self.pages.get(1, { "copies" : 1 })) |
---|
[248] | 163 | copies = page["copies"] |
---|
| 164 | pagecount += (copies - 1) |
---|
[252] | 165 | self.logdebug("%s * page #%s" % (copies, pnum)) |
---|
[273] | 166 | self.logdebug("Internal parser said : %s pages" % pagecount) |
---|
| 167 | |
---|
| 168 | if notrust : |
---|
| 169 | pagecount = 0 # Let gs do counting |
---|
[248] | 170 | return pagecount |
---|
| 171 | |
---|
[193] | 172 | def getJobSize(self) : |
---|
| 173 | """Count pages in PostScript document.""" |
---|
[202] | 174 | self.copies = 1 |
---|
[193] | 175 | return self.natively() or self.throughGhostScript() |
---|
[283] | 176 | |
---|
| 177 | def throughTiffMultiPage24NC(self, dpi) : |
---|
| 178 | """Converts the input file to TIFF format, X dpi, 24 bits per pixel, uncompressed. |
---|
| 179 | Returns percents of ink coverage and number of pages. |
---|
| 180 | """ |
---|
| 181 | self.logdebug("Converting input datas to TIFF...") |
---|
[292] | 182 | result = None |
---|
[283] | 183 | self.infile.seek(0) |
---|
| 184 | (handle, filename) = tempfile.mkstemp(".tmp", "pkpgcounter") |
---|
| 185 | os.close(handle) |
---|
| 186 | command = 'gs -sDEVICE=tiff24nc -dPARANOIDSAFER -dNOPAUSE -dBATCH -dQUIET -r%i -sOutputFile="%s" -' % (dpi, filename) |
---|
| 187 | try : |
---|
[291] | 188 | child = popen2.Popen4(command) |
---|
| 189 | try : |
---|
| 190 | data = self.infile.read(pdlparser.MEGABYTE) |
---|
| 191 | while data : |
---|
| 192 | child.tochild.write(data) |
---|
| 193 | data = self.infile.read(pdlparser.MEGABYTE) |
---|
| 194 | child.tochild.flush() |
---|
| 195 | child.tochild.close() |
---|
| 196 | except (IOError, OSError), msg : |
---|
| 197 | raise pdlparser.PDLParserError, "Problem during conversion to TIFF : %s" % msg |
---|
| 198 | |
---|
| 199 | child.fromchild.close() |
---|
| 200 | try : |
---|
| 201 | child.wait() |
---|
| 202 | except OSError, msg : |
---|
| 203 | raise pdlparser.PDLParserError, "Problem during conversion to TIFF : %s" % msg |
---|
| 204 | |
---|
| 205 | result = inkcoverage.getPercents(filename) |
---|
| 206 | finally : |
---|
| 207 | try : |
---|
| 208 | os.remove(filename) |
---|
| 209 | except : |
---|
| 210 | pass |
---|
[283] | 211 | return result |
---|
[193] | 212 | |
---|
| 213 | def test() : |
---|
| 214 | """Test function.""" |
---|
[196] | 215 | if (len(sys.argv) < 2) or ((not sys.stdin.isatty()) and ("-" not in sys.argv[1:])) : |
---|
| 216 | sys.argv.append("-") |
---|
| 217 | totalsize = 0 |
---|
| 218 | for arg in sys.argv[1:] : |
---|
| 219 | if arg == "-" : |
---|
| 220 | infile = sys.stdin |
---|
| 221 | mustclose = 0 |
---|
| 222 | else : |
---|
| 223 | infile = open(arg, "rb") |
---|
| 224 | mustclose = 1 |
---|
| 225 | try : |
---|
[220] | 226 | parser = Parser(infile, debug=1) |
---|
[196] | 227 | totalsize += parser.getJobSize() |
---|
[200] | 228 | except pdlparser.PDLParserError, msg : |
---|
[196] | 229 | sys.stderr.write("ERROR: %s\n" % msg) |
---|
| 230 | sys.stderr.flush() |
---|
| 231 | if mustclose : |
---|
| 232 | infile.close() |
---|
| 233 | print "%s" % totalsize |
---|
[193] | 234 | |
---|
| 235 | if __name__ == "__main__" : |
---|
| 236 | test() |
---|