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
RevLine 
[3410]1# -*- coding: utf-8 -*-
[192]2#
3# pkpgcounter : a generic Page Description Language parser
4#
[3474]5# (c) 2003-2009 Jerome Alet <alet@librelogiciel.com>
[463]6# This program is free software: you can redistribute it and/or modify
[192]7# it under the terms of the GNU General Public License as published by
[463]8# the Free Software Foundation, either version 3 of the License, or
[192]9# (at your option) any later version.
[3436]10#
[192]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.
[3436]15#
[192]16# You should have received a copy of the GNU General Public License
[463]17# along with this program.  If not, see <http://www.gnu.org/licenses/>.
[192]18#
19# $Id$
20#
21
[360]22"""This module defines the base class for all Page Description Language parsers."""
23
[199]24import sys
[428]25import os
[199]26
[3436]27KILOBYTE = 1024
28MEGABYTE = 1024 * KILOBYTE
[220]29FIRSTBLOCKSIZE = 16 * KILOBYTE
30LASTBLOCKSIZE = int(KILOBYTE / 4)
31
[193]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__
[3436]40
[192]41class PDLParser :
42    """Generic PDL parser."""
[527]43    totiffcommands = None       # Default command to convert to TIFF
44    required = []               # Default list of required commands
45    openmode = "rb"             # Default file opening mode
[555]46    format = "Unknown"          # Default file format
[529]47    def __init__(self, parent, filename, (firstblock, lastblock)) :
[192]48        """Initialize the generic parser."""
[520]49        self.parent = parent
[522]50        # We need some copies for later inclusion of parsers which
51        # would modify the parent's values
[529]52        self.filename = filename[:]
[522]53        self.firstblock = firstblock[:]
54        self.lastblock = lastblock[:]
[491]55        self.infile = None
[220]56        if not self.isValid() :
57            raise PDLParserError, "Invalid file format !"
[3436]58        else :
[555]59            self.logdebug("Input file is in the '%s' file format." % self.format)
[522]60        self.infile = open(self.filename, self.openmode)
61        # self.logdebug("Opened %s in '%s' mode." % (self.filename, self.openmode))
[3436]62
[491]63    def __del__(self) :
64        """Ensures the input file gets closed."""
65        if self.infile :
66            self.infile.close()
[3436]67
[527]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
[3436]76
77    def isMissing(self, commands) :
78        """Returns True if some required commands are missing, else False."""
[527]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()
[3436]84            else :
[527]85                howmanythere += 1
86        if howmanythere == len(commands) :
87            return False
[3436]88        else :
[527]89            return True
[3436]90
91    def logdebug(self, message) :
[252]92        """Logs a debug message if needed."""
[520]93        if self.parent.options.debug :
[252]94            sys.stderr.write("%s\n" % message)
[3436]95
96    def isValid(self) :
[387]97        """Returns True if data is in the expected format, else False."""
[192]98        raise RuntimeError, "Not implemented !"
[3436]99
100    def getJobSize(self) :
[220]101        """Counts pages in a document."""
102        raise RuntimeError, "Not implemented !"
[3436]103
[492]104    def convertToTiffMultiPage24NC(self, outfname, dpi) :
[362]105        """Converts the input file to TIFF format, X dpi, 24 bits per pixel, uncompressed.
[492]106           Writes TIFF datas to the file named by outfname.
[3436]107        """
[428]108        if self.totiffcommands :
[527]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)
[522]111            infname = self.filename
[492]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) :
[428]119                        error = True
[3436]120                else :
[492]121                    error = True
122                if not os.path.exists(outfname) :
123                    error = True
124                elif not os.stat(outfname).st_size :
125                    error = True
[3436]126                else :
[492]127                    break       # Conversion worked fine it seems.
128                sys.stderr.write("Command failed : %s\n" % repr(commandline))
[428]129            if error :
130                raise PDLParserError, "Problem during conversion to TIFF."
[3436]131        else :
[371]132            raise PDLParserError, "Impossible to compute ink coverage for this file format."
Note: See TracBrowser for help on using the browser.