root / pkpgcounter / trunk / pkpgpdls / pdlparser.py @ 3573

Revision 3573, 5.3 kB (checked in by jerome, 11 years ago)

Removed all references to psyco

  • Property svn:eol-style set to native
  • Property svn:keywords set to Auth Date Id Rev
Line 
1# -*- coding: utf-8 -*-
2#
3# pkpgcounter : a generic Page Description Language parser
4#
5# (c) 2003-2009 Jerome Alet <alet@librelogiciel.com>
6# This program is free software: you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation, either version 3 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program.  If not, see <http://www.gnu.org/licenses/>.
18#
19# $Id$
20#
21
22"""This module defines the base class for all Page Description Language parsers."""
23
24import sys
25import os
26
27KILOBYTE = 1024
28MEGABYTE = 1024 * KILOBYTE
29FIRSTBLOCKSIZE = 16 * KILOBYTE
30LASTBLOCKSIZE = int(KILOBYTE / 4)
31
32class PDLParserError(Exception):
33    """An exception for PDLParser related stuff."""
34    def __init__(self, message = ""):
35        self.message = message
36        Exception.__init__(self, message)
37    def __repr__(self):
38        return self.message
39    __str__ = __repr__
40
41class PDLParser :
42    """Generic PDL parser."""
43    totiffcommands = None       # Default command to convert to TIFF
44    required = []               # Default list of required commands
45    openmode = "rb"             # Default file opening mode
46    format = "Unknown"          # Default file format
47    def __init__(self, parent, filename, (firstblock, lastblock)) :
48        """Initialize the generic parser."""
49        self.parent = parent
50        # We need some copies for later inclusion of parsers which
51        # would modify the parent's values
52        self.filename = filename[:]
53        self.firstblock = firstblock[:]
54        self.lastblock = lastblock[:]
55        self.infile = None
56        if not self.isValid() :
57            raise PDLParserError, "Invalid file format !"
58        else :
59            self.logdebug("Input file is in the '%s' file format." % self.format)
60        self.infile = open(self.filename, self.openmode)
61        # self.logdebug("Opened %s in '%s' mode." % (self.filename, self.openmode))
62
63    def __del__(self) :
64        """Ensures the input file gets closed."""
65        if self.infile :
66            self.infile.close()
67
68    def findExecutable(self, command) :
69        """Finds an executable in the PATH and returns True if found else False."""
70        for cmd in [p.strip() for p in command.split("|")] : # | can separate alternatives for similar commands (e.g. a2ps|enscript)
71            for path in os.environ.get("PATH", "").split(":") :
72                fullname = os.path.abspath(os.path.join(os.path.expanduser(path), cmd))
73                if os.path.isfile(fullname) and os.access(fullname, os.X_OK) :
74                    return True
75        return False
76
77    def isMissing(self, commands) :
78        """Returns True if some required commands are missing, else False."""
79        howmanythere = 0
80        for command in commands :
81            if not self.findExecutable(command) :
82                sys.stderr.write("ERROR: %(command)s is missing or not executable. You MUST install it for pkpgcounter to be able to do what you want.\n" % locals())
83                sys.stderr.flush()
84            else :
85                howmanythere += 1
86        if howmanythere == len(commands) :
87            return False
88        else :
89            return True
90
91    def logdebug(self, message) :
92        """Logs a debug message if needed."""
93        if self.parent.options.debug :
94            sys.stderr.write("%s\n" % message)
95
96    def isValid(self) :
97        """Returns True if data is in the expected format, else False."""
98        raise RuntimeError, "Not implemented !"
99
100    def getJobSize(self) :
101        """Counts pages in a document."""
102        raise RuntimeError, "Not implemented !"
103
104    def convertToTiffMultiPage24NC(self, outfname, dpi) :
105        """Converts the input file to TIFF format, X dpi, 24 bits per pixel, uncompressed.
106           Writes TIFF datas to the file named by outfname.
107        """
108        if self.totiffcommands :
109            if self.isMissing(self.required) :
110                raise PDLParserError, "At least one of the following commands is missing and should be installed for the computation of ink coverage : %s" % repr(self.required)
111            infname = self.filename
112            for totiffcommand in self.totiffcommands :
113                error = False
114                commandline = totiffcommand % locals()
115                # self.logdebug("Executing '%s'" % commandline)
116                status = os.system(commandline)
117                if os.WIFEXITED(status) :
118                    if os.WEXITSTATUS(status) :
119                        error = True
120                else :
121                    error = True
122                if not os.path.exists(outfname) :
123                    error = True
124                elif not os.stat(outfname).st_size :
125                    error = True
126                else :
127                    break       # Conversion worked fine it seems.
128                sys.stderr.write("Command failed : %s\n" % repr(commandline))
129            if error :
130                raise PDLParserError, "Problem during conversion to TIFF."
131        else :
132            raise PDLParserError, "Impossible to compute ink coverage for this file format."
Note: See TracBrowser for help on using the browser.