Complete.Org: Mailing Lists: Archives: freeciv-data: January 2003:
[freeciv-data] The resource editor, a promised
Home

[freeciv-data] The resource editor, a promised

[Top] [All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index] [Thread Index]
To: freeciv-data@xxxxxxxxxxx
Subject: [freeciv-data] The resource editor, a promised
From: "Eric S. Raymond" <esr@xxxxxxxxxxxxxxxxx>
Date: Sat, 18 Jan 2003 15:33:26 -0500
Reply-to: freeciv-data@xxxxxxxxxxx

#!/usr/bin/env python
"""
Usage: imagehack.py [-p prefix] {-xe specfile]

The -e option, it starts an interactive editor for FreeCiv graphics resources.
Note!  Writing out a changed specfile will lose any comments in it!

The -x option bursts the contents of a specfile into a subdirectory
named for it.  Graphics tiles become individual PNGs.  Data in the
info.artists member is written to a file named artists.  If the specfile
is itself a directory, imagehack will recurse down it converting all files
that end in .spec

The -p option sets the name of the subdirectory into which -x dir will
generate conveted files.

To convert an entire data directory, it is normally only necessary to
run this command in it:

        imagehack.py -p graphics -x .

Note: this code won't work with a stock ConfigParser, it needs the
modified version distributed with this package.  I'm trying to get
these changes folded back into Python 2.3.

Requires Python 2.x, Python Imaging Library.  Tested w/Python 2.3a + PIL 1.1.3.

0.1 version by Eric S. Raymond, Jan 2003

KNOWN BUG: This won't resize the image array if it's full when we try to add
        an image.  I have not figured out how to make the underlying graphics
        library do this yet.
"""

# Customized version of ConfigParser starts here:
#------------------------------------------------------------------------------
"""Configuration file parser.

A setup file consists of sections, lead by a "[section]" header,
and followed by "name: value" entries, with continuations and such in
the style of RFC 822.

The option values can contain format strings which refer to other values in
the same section, or values in a special [DEFAULT] section.

For example:

    something: %(dir)s/whatever

would resolve the "%(dir)s" to the value of dir.  All reference
expansions are done late, on demand.

Intrinsic defaults can be specified by passing them into the
ConfigParser constructor as a dictionary.

class:

ConfigParser -- responsible for for parsing a list of
                configuration files, and managing the parsed database.

    methods:

    __init__(defaults=None)
        create the parser and specify a dictionary of intrinsic defaults.  The
        keys must be strings, the values must be appropriate for %()s string
        interpolation.  Note that `__name__' is always an intrinsic default;
        it's value is the section's name.

    sections()
        return all the configuration section names, sans DEFAULT

    has_section(section)
        return whether the given section exists

    has_option(section, option)
        return whether the given option exists in the given section

    options(section)
        return list of configuration options for the named section

    read(filenames)
        read and parse the list of named configuration files, given by
        name.  A single filename is also allowed.  Non-existing files
        are ignored.

    readfp(fp, filename=None)
        read and parse one configuration file, given as a file object.
        The filename defaults to fp.name; it is only used in error
        messages (if fp has no `name' attribute, the string `<???>' is used).

    get(section, option, raw=False, vars=None)
        return a string value for the named option.  All % interpolations are
        expanded in the return values, based on the defaults passed into the
        constructor and the DEFAULT section.  Additional substitutions may be
        provided using the `vars' argument, which must be a dictionary whose
        contents override any pre-existing defaults.

    getint(section, options)
        like get(), but convert value to an integer

    getfloat(section, options)
        like get(), but convert value to a float

    getboolean(section, options)
        like get(), but convert value to a boolean (currently case
        insensitively defined as 0, false, no, off for False, and 1, true,
        yes, on for True).  Returns False or True.

    items(section, raw=False, vars=None)
        return a list of tuples with (name, value) for each option
        in the section.

    remove_section(section)
        remove the given file section and all its options

    remove_option(section, option)
        remove the given option from the given section

    set(section, option, value)
        set the given option

    write(fp)
        write the configuration state in .ini format
"""

import re

__all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
           "InterpolationError", "InterpolationDepthError",
           "InterpolationSyntaxError", "ParsingError",
           "MissingSectionHeaderError", "ConfigParser",
           "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]

DEFAULTSECT = "DEFAULT"

MAX_INTERPOLATION_DEPTH = 10



# exception classes
class Error(Exception):
    """Base class for ConfigParser exceptions."""

    def __init__(self, msg=''):
        self._msg = msg
        Exception.__init__(self, msg)

    def __repr__(self):
        return self._msg

    __str__ = __repr__

class NoSectionError(Error):
    """Raised when no section matches a requested option."""

    def __init__(self, section):
        Error.__init__(self, 'No section: %s' % section)
        self.section = section

class DuplicateSectionError(Error):
    """Raised when a section is multiply-created."""

    def __init__(self, section):
        Error.__init__(self, "Section %s already exists" % section)
        self.section = section

class NoOptionError(Error):
    """A requested option was not found."""

    def __init__(self, option, section):
        Error.__init__(self, "No option `%s' in section: %s" %
                       (option, section))
        self.option = option
        self.section = section

class InterpolationError(Error):
    """A string substitution required a setting which was not available."""

    def __init__(self, reference, option, section, rawval):
        Error.__init__(self,
                       "Bad value substitution:\n"
                       "\tsection: [%s]\n"
                       "\toption : %s\n"
                       "\tkey    : %s\n"
                       "\trawval : %s\n"
                       % (section, option, reference, rawval))
        self.reference = reference
        self.option = option
        self.section = section

class InterpolationSyntaxError(Error):
    """Raised when the source text into which substitutions are made
    does not conform to the required syntax."""

class InterpolationDepthError(Error):
    """Raised when substitutions are nested too deeply."""

    def __init__(self, option, section, rawval):
        Error.__init__(self,
                       "Value interpolation too deeply recursive:\n"
                       "\tsection: [%s]\n"
                       "\toption : %s\n"
                       "\trawval : %s\n"
                       % (section, option, rawval))
        self.option = option
        self.section = section

class ParsingError(Error):
    """Raised when a configuration file does not follow legal syntax."""

    def __init__(self, filename):
        Error.__init__(self, 'File contains parsing errors: %s' % filename)
        self.filename = filename
        self.errors = []

    def append(self, lineno, line):
        self.errors.append((lineno, line))
        self._msg = self._msg + '\n\t[line %2d]: %s' % (lineno, line)

class MissingSectionHeaderError(ParsingError):
    """Raised when a key-value pair is found before any section header."""

    def __init__(self, filename, lineno, line):
        Error.__init__(
            self,
            'File contains no section headers.\nfile: %s, line: %d\n%s' %
            (filename, lineno, line))
        self.filename = filename
        self.lineno = lineno
        self.line = line



class RawConfigParser:
    def __init__(self, defaults=None):
        self._sections = {}
        if defaults is None:
            self._defaults = {}
        else:
            self._defaults = defaults
        self._sectkeys = []
        self._optkeys = {}
        self._listbrackets = None
        self._stringquotes = None

    def defaults(self):
        return self._defaults

    def sections(self):
        """Return a list of section names, excluding [DEFAULT]"""
        # self._sections will never have [DEFAULT] in it
        return self._sections.keys()

    def add_section(self, section):
        """Create a new section in the configuration.

        Raise DuplicateSectionError if a section by the specified name
        already exists.
        """
        if section in self._sections:
            raise DuplicateSectionError(section)
        self._sections[section] = {}

    def has_section(self, section):
        """Indicate whether the named section is present in the configuration.

        The DEFAULT section is not acknowledged.
        """
        return section in self._sections

    def options(self, section):
        """Return a list of option names for the given section name."""
        try:
            opts = self._sections[section].copy()
        except KeyError:
            raise NoSectionError(section)
        opts.update(self._defaults)
        if '__name__' in opts:
            del opts['__name__']
        return opts.keys()

    def read(self, filenames):
        """Read and parse a filename or a list of filenames.

        Files that cannot be opened are silently ignored; this is
        designed so that you can specify a list of potential
        configuration file locations (e.g. current directory, user's
        home directory, systemwide directory), and all existing
        configuration files in the list will be read.  A single
        filename may also be given.
        """
        if isinstance(filenames, basestring):
            filenames = [filenames]
        for filename in filenames:
            try:
                fp = open(filename)
            except IOError:
                continue
            self._read(fp, filename)
            fp.close()

    def readfp(self, fp, filename=None):
        """Like read() but the argument must be a file-like object.

        The `fp' argument must have a `readline' method.  Optional
        second argument is the `filename', which if not given, is
        taken from fp.name.  If fp has no `name' attribute, `<???>' is
        used.

        """
        if filename is None:
            try:
                filename = fp.name
            except AttributeError:
                filename = '<???>'
        self._read(fp, filename)

    def get(self, section, option):
        opt = self.optionxform(option)
        if section not in self._sections:
            if section != DEFAULTSECT:
                raise NoSectionError(section)
            if opt in self._defaults:
                return self._defaults[opt]
            else:
                raise NoOptionError(option, section)
        elif opt in self._sections[section]:
            return self._sections[section][opt]
        elif opt in self._defaults:
            return self._defaults[opt]
        else:
            raise NoOptionError(option, section)

    def items(self, section):
        try:
            d2 = self._sections[section]
        except KeyError:
            if section != DEFAULTSECT:
                raise NoSectionError(section)
            d2 = {}
        d = self._defaults.copy()
        d.update(d2)
        if "__name__" in d:
            del d["__name__"]
        return d.items()

    def _get(self, section, conv, option):
        return conv(self.get(section, option))

    def getint(self, section, option):
        return self._get(section, int, option)

    def getfloat(self, section, option):
        return self._get(section, float, option)

    _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
                       '0': False, 'no': False, 'false': False, 'off': False}

    def getstring(self, section, option):
        v = self.get(section, option)
        for c in self._stringquotes:
            if v[0] == c and v[-1] == c:
                return v[1:-1]
        else:
            return v

    def getboolean(self, section, option):
        v = self.get(section, option)
        if v.lower() not in self._boolean_states:
            raise ValueError, 'Not a boolean: %s' % v
        return self._boolean_states[v.lower()]

    def optionxform(self, optionstr):
        return optionstr.lower()

    def has_option(self, section, option):
        """Check for the existence of a given option in a given section."""
        if not section or section == DEFAULTSECT:
            option = self.optionxform(option)
            return option in self._defaults
        elif section not in self._sections:
            return False
        else:
            option = self.optionxform(option)
            return (option in self._sections[section]
                    or option in self._defaults)

    def set(self, section, option, value):
        """Set an option."""
        if not section or section == DEFAULTSECT:
            sectdict = self._defaults
        else:
            try:
                sectdict = self._sections[section]
            except KeyError:
                raise NoSectionError(section)
        sectdict[self.optionxform(option)] = value

    def dump_value(self, section, key, value):
        """Dump a value in a canonical form.
        Section and key arguments are in case a subclass needs to do
        special handling.
        """
        if self._listbrackets and type(value) == type([]):
            return self._listbrackets[0] + ", ".join(map(lambda x: 
self.dump_value(section, key, x), value)) + self._listbrackets[1]
        elif self._stringquotes and value[0] in self._stringquotes:
            return str(value)
        else:
            return str(value).replace('\n', '\n\t')

    def write(self, fp):
        """Write an .ini-format representation of the configuration state."""
        if self._defaults:
            fp.write("[%s]\n" % DEFAULTSECT)
            for key in self._optkeys[DEFAULTSECT]:
                value = self._defaults[key]
                fp.write("%s = %s\n" % (key, self.dump_value(DEFAULTSECT, key, 
value)))
            fp.write("\n")
        for section in self._sectkeys:
            fp.write("[%s]\n" % section)
            for key in self._optkeys[section]:
                value = self.get(section, key)
                if key != "__name__":
                    fp.write("%s = %s\n" % (key, self.dump_value(section, key, 
value)))
            fp.write("\n")

    def remove_option(self, section, option):
        """Remove an option."""
        if not section or section == DEFAULTSECT:
            sectdict = self._defaults
        else:
            try:
                sectdict = self._sections[section]
            except KeyError:
                raise NoSectionError(section)
        option = self.optionxform(option)
        existed = option in sectdict
        if existed:
            del sectdict[option]
        return existed

    def remove_section(self, section):
        """Remove a file section."""
        existed = section in self._sections
        if existed:
            del self._sections[section]
        return existed

    #
    # Regular expressions for parsing section headers and options.
    #
    SECTCRE = re.compile(
        r'\['                                 # [
        r'(?P<header>[^]]+)'                  # very permissive!
        r'\]'                                 # ]
        )
    OPTCRE = re.compile(
        r'(?P<option>[^:=\s][^:=]*)'          # very permissive!
        r'\s*(?P<vi>[:=])\s*'                 # any number of space/tab,
                                              # followed by separator
                                              # (either : or =), followed
                                              # by any # space/tab
        r'(?P<value>.*)$'                     # everything up to eol
        )

    def listbrackets(self, lb):
        "Set the list brackets to be used by array value parsing."
        if lb:
            self._listbrackets = lb
        return self._listbrackets

    def stringquotes(self, sq):
        "Set the string quotes to be used by multiline-string parsing"
        if sq:
            self._stringquotes = sq
        return self._stringquotes

    def _read(self, fp, fpname):
        """Parse a sectioned setup file.

        The sections in setup file contains a title line at the top,
        indicated by a name in square brackets (`[]'), plus key/value
        options lines, indicated by `name: value' format lines.
        Continuations are represented by an embedded newline then
        leading whitespace.  Blank lines, lines beginning with a '#',
        and just about everything else are ignored.
        """
        cursect = None                            # None, or a dictionary
        optname = None
        lineno = 0
        e = None                                  # None, or an exception
        while True:
            line = fp.readline()
            if not line:
                break
            lineno = lineno + 1
            # comment or blank line?
            if line.strip() == '' or line[0] in '#;':
                continue
            if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
                # no leading whitespace
                continue
            # continuation line?
            if line[0].isspace() and cursect is not None and optname:
                value = line.strip()
                if value:
                    cursect[optname] = "%s\n%s" % (cursect[optname], value)
            # a section header or option header?
            else:
                # is it a section header?
                mo = self.SECTCRE.match(line)
                if mo:
                    sectname = mo.group('header')
                    if sectname in self._sections:
                        cursect = self._sections[sectname]
                    elif sectname == DEFAULTSECT:
                        cursect = self._defaults
                        self._optkeys[DEFAULTSECT] = []
                    else:
                        cursect = {'__name__': sectname}
                        self._sections[sectname] = cursect
                        self._sectkeys.append(sectname)
                        self._optkeys[sectname] = []
                    # So sections can't start with a continuation line
                    optname = None
                # no section header in the file?
                elif cursect is None:
                    raise MissingSectionHeaderError(fpname, lineno, `line`)
                # an option line?
                else:
                    mo = self.OPTCRE.match(line)
                    if mo:
                        optname, vi, optval = mo.group('option', 'vi', 'value')
                        if vi in ('=', ':') and ';' in optval:
                            # ';' is a comment delimiter only if it follows
                            # a spacing character
                            pos = optval.find(';')
                            if pos != -1 and optval[pos-1].isspace():
                                optval = optval[:pos]
                        optval = optval.strip()
                        # allow empty values
                        if optval == '""':
                            optval = ''
                        optname = self.optionxform(optname.rstrip())
                        self._optkeys[sectname].append(optname)
                        if self._listbrackets and optval[0] == 
self._listbrackets[0]:
                            # we see a list delimiter
                            import cStringIO, shlex
                            valuelist = []
                            restofline = cStringIO.StringIO(optval)
                            tokenizer = shlex.shlex(restofline)
                            tokenizer.whitespace += ","
                            tokenizer.commenters += "#;"
                            tokenizer.get_token()
                            while 1:
                                tok = tokenizer.get_token()
                                if tok == '':
                                    break
                                else:
                                    valuelist.append(tok)
                            if valuelist[-1] == self._listbrackets[1]:
                                valuelist.pop()
                            else:
                                tokenizer = shlex.shlex(fp)
                                tokenizer.whitespace += ","
                                tokenizer.commenters += "#;"
                                while 1:
                                    tok = tokenizer.get_token()
                                    if tok=='' or tok == self._listbrackets[1]:
                                        break
                                    else:
                                        valuelist.append(tok)
                            cursect[optname] = valuelist
                        elif self._stringquotes and optval[0] in 
self._stringquotes:
                            # string-quoted literal
                            if len(optval) == 1 or optval[-1] != optval[0]:
                                optval += '\n'
                                while 1:
                                    line = fp.readline()
                                    optval += line
                                    if line == '' or len(line.rstrip()) > 0 and 
line.rstrip()[-1] == optval[0]:
                                        break;
                            cursect[optname] = optval.rstrip()
                        else:
                            # normal case -- single value
                            cursect[optname] = optval
                    else:
                        # a non-fatal parsing error occurred.  set up the
                        # exception but keep going. the exception will be
                        # raised at the end of the file and will contain a
                        # list of all bogus lines
                        if not e:
                            e = ParsingError(fpname)
                        e.append(lineno, `line`)
        # if any parsing errors occurred, raise an exception
        if e:
            raise e


class ConfigParser(RawConfigParser):

    def get(self, section, option, raw=False, vars=None):
        """Get an option value for a given section.

        All % interpolations are expanded in the return values, based on the
        defaults passed into the constructor, unless the optional argument
        `raw' is true.  Additional substitutions may be provided using the
        `vars' argument, which must be a dictionary whose contents overrides
        any pre-existing defaults.

        The section DEFAULT is special.
        """
        d = self._defaults.copy()
        try:
            d.update(self._sections[section])
        except KeyError:
            if section != DEFAULTSECT:
                raise NoSectionError(section)
        # Update with the entry specific variables
        if vars is not None:
            d.update(vars)
        option = self.optionxform(option)
        try:
            value = d[option]
        except KeyError:
            raise NoOptionError(option, section)

        if raw:
            return value
        else:
            return self._interpolate(section, option, value, d)

    def items(self, section, raw=False, vars=None):
        """Return a list of tuples with (name, value) for each option
        in the section.

        All % interpolations are expanded in the return values, based on the
        defaults passed into the constructor, unless the optional argument
        `raw' is true.  Additional substitutions may be provided using the
        `vars' argument, which must be a dictionary whose contents overrides
        any pre-existing defaults.

        The section DEFAULT is special.
        """
        d = self._defaults.copy()
        try:
            d.update(self._sections[section])
        except KeyError:
            if section != DEFAULTSECT:
                raise NoSectionError(section)
        # Update with the entry specific variables
        if vars:
            d.update(vars)
        options = d.keys()
        if "__name__" in options:
            options.remove("__name__")
        if raw:
            for option in options:
                yield (option, d[option])
        else:
            for option in options:
                yield (option,
                       self._interpolate(section, option, d[option], d))

    def _interpolate(self, section, option, rawval, vars):
        # do the string interpolation
        if type(rawval) == type([]):
            return map(lambda v:self._interpolate(section, option, v, vars), 
rawval)
        value = rawval
        depth = MAX_INTERPOLATION_DEPTH
        while depth:                    # Loop through this until it's done
            depth -= 1
            if value.find("%(") != -1:
                try:
                    value = value % vars
                except KeyError, e:
                    raise InterpolationError(e[0], option, section, rawval)
            else:
                break
        if value.find("%(") != -1:
            raise InterpolationDepthError(option, section, rawval)
        return value


class SafeConfigParser(ConfigParser):

    def _interpolate(self, section, option, rawval, vars):
        # do the string interpolation
        if type(rawval) == type([]):
            return map(lambda v:self._interpolate(section, option, v, vars), 
rawval)
        L = []
        self._interpolate_some(option, L, rawval, section, vars, 1)
        return ''.join(L)

    _interpvar_match = re.compile(r"%\(([^)]+)\)s").match

    def _interpolate_some(self, option, accum, rest, section, map, depth):
        if depth > MAX_INTERPOLATION_DEPTH:
            raise InterpolationDepthError(option, section, rest)
        while rest:
            p = rest.find("%")
            if p < 0:
                accum.append(rest)
                return
            if p > 0:
                accum.append(rest[:p])
                rest = rest[p:]
            # p is no longer used
            c = rest[1:2]
            if c == "%":
                accum.append("%")
                rest = rest[2:]
            elif c == "(":
                m = self._interpvar_match(rest)
                if m is None:
                    raise InterpolationSyntaxError(
                        "bad interpolation variable syntax at: %r" % rest)
                var = m.group(1)
                rest = rest[m.end():]
                try:
                    v = map[var]
                except KeyError:
                    raise InterpolationError(var, option, section, rest)
                if "%" in v:
                    self._interpolate_some(option, accum, v,
                                           section, map, depth + 1)
                else:
                    accum.append(v)
            else:
                raise InterpolationSyntaxError(
                    "'%' must be followed by '%' or '('")

#------------------------------------------------------------------------------

intro_string = """Welcome to the imagehack utility.

This is a special-purpose editor for hacking FreeCiv graphics resources.
You have already loaded a specification file and its associated image array.

You can display the image array by typing 'c'.
You can list the coordinates and names of the images with 'l'.
You can select a sub-image to be operated on with 's'.
You can display the selected image with 'd'
You can export the selected image with 'e'.
You can import a replacement for the selected iimage with 'i'.
You can add an image to the array with 'a'
You can write the altered resources out with 'w'
You can exit with 'q' or end-of-file.

See the help on individual commands for details.
"""
import os, sys, re, getopt, string, cmd, readline

try:
    import Image
except ImportError:
    print "imagehack needs the Python Imaging Library."
    raise SystemExit, 1

viewer = "display -title '%s'"  # Use ImageMagick viewer for fast display

class ResourceGridSection:
    "Encapsulate a FreeCiv tile grid."
    def __init__(self, grid, data, section):
        self.grid = grid
        self.data = data
        self.section = section
        self.is_pixel_border = 0
        self.x_top_left = data.getint(section, "x_top_left")
        self.y_top_left = data.getint(section, "y_top_left")
        if data.has_option(section, "is_pixel_border"):
            self.is_pixel_border = data.getint(section, "is_pixel_border")
        self.dx         = data.getint(section, "dx")
        self.dy         = data.getint(section, "dy")
        payload = data.get(section, "tiles")
        self.headers = payload[:3]              # Save the headers
        payload = payload[3:]                   # Skip the column headers
        # Extract coordinate pairs
        while payload:
            y = int(payload.pop(0))
            x = int(payload.pop(0))
            if x > self.grid.x_max:
                self.grid.x_max = x
            if y > self.grid.y_max:
                self.grid.y_max = y
            namelist = []
            while payload and payload[0][0] == '"':
                namelist.append(payload.pop(0)[1:-1])
            self.grid.tiles[(y, x)] = [tuple(namelist)]
            #
            # Raimar Falke says:
            # ----------------------------------------------------------------
            # Each PNG file divided into equal sized tiles of size (dx,dy).
            # There may _one_ pixel spacing between these if is_pixel_border
            # is set true in the spec file.
            # 
            # For the flags and for the flags only: we crop the sprite further
            # (gui-gtk/plrdlg.c:build_flag) by calling
            # gui-gtk/graphics.c:sprite_get_bounding_box and
            # gui-gtk/graphics.c:crop_sprite.  And yes this is isn't what
            # I would call nice.
            # ----------------------------------------------------------------
            #
            # First, crop out the base rectangle. 
            image = self.grid.composite.crop(self.bbox((y, x)))
            # Rely on the fact that the background pixels are zero.
            image = image.crop(image.getbbox())
            # Keep each image with the corresponding coord/names association.
            self.grid.tiles[(y, x)].append(image)
            # Back mapping of tiles to sections
            self.grid.tile_section[(y, x)] = self

    def corner(self, where):
        "Tile coordinates to pixel coordinates."
        (y, x) = where
        x_base = self.x_top_left + x * (self.dx + self.is_pixel_border)
        y_base = self.y_top_left + y * (self.dy + self.is_pixel_border)
        # Swap because PIL tuples want X first
        return (x_base, y_base)

    def bbox(self, where):
        "Return the bounding box of the given tile."
        topleft = self.corner(where)
        return (topleft[0], topleft[1],
                topleft[0] + self.dx - 1,
                topleft[1] + self.dy - 1)

class ResourceGrid:
    "Encapsulate a FreeCiv tile grid."
    def __init__(self, data, graphics):
        self.x_max = self.y_max = 0
        self.tiles = {}
        self.gridmap = {}
        self.tile_section = {}
        self.composite = Image.open(graphics)
        self.composite_hacked = 0
        for sect in data.sections():
            if sect[:5] == "grid_":
                self.gridmap[sect] = ResourceGridSection(self, data, sect)
        # Initially select the first empty slot
        self.select(None)

    def export_to_data(self, data):
        "Propagate changes from this object into the specfile."
        for (sect, resource) in self.gridmap.items():
            tiledata = resource.headers
            for y in range(self.y_max+1):
                for x in range(self.x_max+1):
                    if (y, x) in self.grid.tiles and 
self.tile_section[(y,x)]==resource:
                        tiledata.append(`y`)
                        tiledata.append(`x`)
                        tiledata += map(lambda x: '"%s"' % x, 
list(self.grid.tiles[(y,x)][0]))
            data.set(sect, "tiles", tiledata)        

    def next(self):
        "Return the tuple location of the first unoccupied slot."
        y_max = reduce(max, map(lambda y: y[0], self.tiles.keys()))
        x_max = reduce(max, map(lambda x: x[1], self.tiles.keys()))
        x_new = 0
        for (y, x) in self.tiles.keys():
            if y == y_max:
                if x > x_new:
                    x_new = x
        if x_new == x_max:
            y_max += 1
            x_new = 0
        else:
            x_new += 1
            x_max = x_new
        return (y_max, x_new)

    def select(self, key):
        "Select an image by coordinates or name."
        if type(key) == type(""):               # Select by name
            pattern = re.compile(key)
            for (key, data) in self.tiles.items():
                if pattern.search(" ".join(data[0])):
                    self.selection = key
        elif key in self.tiles:                 # Select by tuple
            self.selection = key
        elif key == None:                       # Select first unoccupied slot 
            self.selection = self.next()
        else:                                   # Key wasn't right
            raise KeyError

    def selected(self):
        "Return the selected coordinate/namelist/image item"
        if self.selection == self.next():
            return [self.selection, None, None]
        else:
            return [self.selection] + self.tiles[self.selection]

    def replace(self, image):
        "Replace the selected image with a specified one."
        subsect = self.tile_section[self.selection]
        if image.size[0] > subsect.dx or image.size[1] > subsect.dy:
            raise ImportError
        (l, t) = subsect.corner(self.selection)
        (dx, dy) = image.size
        # Clear the landing area, then drop in the new image
        self.composite.paste(0, subsect.bbox(self.selection))
        self.composite.paste(image, (l, t, l + dx, t + dy))
        self.tiles[self.selection][1] = image
        self.composite_hacked += 1

    def add(self, name, section, image):
        "Add the given image to the array."
        if filter(lambda x: name in x[0], self.tiles.values()):
            raise ValueError, name
        self.select(None)
        self.tiles[self.selection] = [(name,), None]
        self.tile_section[self.selection] = self.gridmap[section]
        self.replace(image)

    def list(self):
        "Dump a list of associations from tuples to name lists."
        for (sect, resource) in self.gridmap.items():
            print "[" + sect + "]"
            for y in range(self.y_max+1):
                for x in range(self.x_max+1):
                    if (y, x) in self.tiles and 
self.tile_section[(y,x)]==resource:
                        datum = self.tiles[(y, x)]
                        print "(%d, %d) : %s -> %s" % (y, x, datum[0], 
resource.bbox((y,x)))

class FreecivDataParser(ConfigParser):
    "Handle syntax level of FreeCiv data file parsing."
    def __init__(self):
        ConfigParser.__init__(self)
        self.listbrackets("{}")
        self.stringquotes("\"'")

    def dump_value(self, section, key, value):
        """Dump a specfile in a canonical form.
        Section and key arguments are in case a subclass needs to do
        special handling.
        """
        rep = ""
        if type(value)==type([]):
            rep += "{"
            for (i, x) in enumerate(value):
                rep += str(x)
                if i == len(value)-1:
                    rep += '\n'
                elif x[0] == '"' and value[i+1][0] in string.digits:
                    rep += "\n\t"
                else:
                    rep += ", "
            rep += "}"
        else:
            rep += ConfigParser.dump_value(self,section,key,value)
        return rep

class SpecFile:
    "Read a FreeCiv config file and parse the associated graphics resources."
    def __init__(self, file):
        self.specfile = file
        self.spec = FreecivDataParser()
        self.spec.read(self.specfile)
        self.specfile_hacked = 0
        self.tiles = {}
        # Ugh -- ad-hoc logic to figure out where the graphics file is
        self.graphics = self.spec.getstring("file", "gfx") + ".png"
        if os.path.exists(self.graphics):
            pass
        elif os.path.exists(os.path.basename(self.graphics)):
            self.graphics = os.path.basename(self.graphics)
        else:
            raise NameError
        # Now that we've got the graphics file, merge spec data and images
        self.resource = ResourceGrid(self.spec, self.graphics)

    def burst(self, dest=None):
        "Burst a graphics array into a subdirectory."
        if not dest:
            dest = self.specfile
        if dest.endswith(".spec"):
            dest = dest[:-5]
        os.makedirs(dest)
        for y in range(self.resource.y_max+1):
            for x in range(self.resource.x_max+1):
                if (y, x) in self.resource.tiles:
                    (names, graphic) = self.resource.tiles[(y, x)]
                    for name in names:
                        graphic.save(os.path.join(dest, name + ".png"))
        if self.spec.has_option("info", "artists"):
            fp = open(os.path.join(dest, "artists"), "w")
            fp.write(self.spec.getstring("info", "artists"))
            fp.close()

def usage():
    print "usage: imagehack.py [-x specfile]"
    raise SystemExit, 1

class EditInterpreter(cmd.Cmd, SpecFile):
    "Interactively edit a spec file and the associate graphics resource."
    def __init__(self, file):
        self.prompt = "imagehack> "
        if not os.path.exists(file):
            print "imagehack.py: %s doesn't exist " % file
            raise SystemExit, 1
        else:
            SpecFile.__init__(self, file)
            print "Loaded %d images from %s.  Type `?' for help." 
%(len(self.resource.tiles),self.graphics)
    def help_intro(self):
        print intro_string
    def do_list(self, line):
        self.resource.list()
    def help_list(self):
        print "List the coordinate pair-to-tilenames associations."
    do_l = do_list
    help_l = help_list
    def do_composite(self, line):
        self.resource.composite.show("Image grid", viewer % "Image grid")
    def help_composite(self):
        print "Display the current composite file."
    do_c = do_composite
    help_c = help_composite
    def do_display(self, line):
        (coordinates, names, image) = self.resource.selected()
        if image:
            print "Displaying %s: %s" % (coordinates, names)
            image.show(names[0], viewer % names[0])
        else:
            print "Empty slot is selected."
    def help_display(self):
        print "Display the currently selected icon, if any."
    do_d = do_display
    help_d = help_display
    def do_import(self, line):
        (coordinates, names, image) = self.resource.selected()
        if image == None:
            print "Empty slot is selected."
        else:
            if not line:
                import_from = names[0]
            else:
                import_from = line.strip()
            import_from += ".png"
            print "Importing from %s" % import_from
            try:
                self.resource.replace(Image.open(import_from))
            except ImportError: 
                print "Image is too large to fit in a tile."
            except IOError: 
                print "Image file nonexistent or unreadable."
    def help_import(self):
        print "Import the currently selected icon.  If an argument is given,"
        print "it will become the basename of the exported image.  If no"
        print "argument is given, the first name of the flag will be used."
    do_i = do_import
    help_i = help_import
    def do_export(self, line):
        (coordinates, names, image) = self.resource.selected()
        if image == None:
            print "Empty slot is selected."
        else:
            export_to = names[0] + ".png"
            print "Exporting %s as %s" % (coordinates, export_to)
            image.save(export_to)
    def help_export(self, line):
        print "Export the currently selected icon, if any."
    do_e = do_export
    help_e = help_export
    def do_output(self, line):
        self.spec.write(sys.stdout)
    def help_output(self, line):
        print "Dump the state of the specfile."
    do_o = do_output
    help_o = help_output
    def do_add(self, line):
        args = line.strip().split()
        if len(args) > 1:
            section = args[1]
            if section not in self.resource.gridmap.keys():
                print "No such section as", section
                return
        elif len(self.resource.gridmap) == 1:
            section = self.resource.gridmap.keys()[0]
        else:
                print "You need to specify a section to add this to."
                return
        name = args[0]
        try:
            self.resource.add(name, section, Image.open(name + ".png"))
        except ImportError: 
            print "Image is too large to fit in a tile."
        except ValueError, name: 
            print "An image named %s already exists in the resource." % name
        except IOError: 
            print "Image file nonexistemnt or unreadable."
        self.specfile_hacked += 1
    def help_add(self, line):
        print "Add the specified file to the first unused spot in the array."
    do_a = do_add
    help_a = help_add
    def do_find(self, line):
        args = line.split()
        if len(args) == 0:
            self.resource.select(None)
        elif args[0] in string.digits:
            self.resource.select((int(args[0]), int(args[1])))
        else:
            self.resource.select(args[0])
        (coordinates, names, image) = self.resource.selected()
        print "%s: %s -> %s" % (coordinates, names, 
self.resource.tile_section[coordinates].bbox(coordinates))
        if image:
            image.show(names[0], viewer % names[0])
        else:
            print "Empty slot selected."
    def help_find(self):
        print "The select command selects an icon to operate on."
        print "You can select either by substring match on the names,"
        print "or by giving a coordinate pair."
    do_f = do_find
    help_f = help_find
    def do_write(self, line):
        "Write out all changed resources."
        try:
            if self.resource.composite_hacked:
                    self.resource.composite.save(self.graphics)            
            else:
                print "Specfile is unchanged; write suppressed."
        except IOError:
            print "Graphics write failed."
            return
        if self.specfile_hacked:
            print "Any comments in the specfile will be lost."
            self.resource.export_to_data(self.spec)
            try:
                fp = open(self.specfile, "w")
                self.spec.write(fp)
                fp.close()
            except IOError:
                print "Spec file write failed."
        else:
            print "Graphic file is unchanged; write suppressed."
    def help_write(self):
        print "The write command saves the altered spec and graphics files."
    do_w = do_write
    help_w = help_write
    def do_quit(self, line):
        return 1
    def help_quit(self):
        print "The quit command ends your editing session."
    do_q = do_quit
    help_q = help_quit
    def do_EOF(self, line):
        print ""
        self.do_quit(None)
        return 1

def traverse(root, func, prefix):
    "Walk a function over all the speciles in a directory."
    def visit(root, dir, names):
        os.chdir(dir)
        for file in names:
            if file.endswith(".spec"):
                here = os.path.join(dir, file)
                func(here, os.path.join(here[:len(root)+1], prefix, 
here[len(root)+1:]))
    os.path.walk(os.path.abspath(root), visit, os.path.abspath(root))

if __name__ == '__main__':
    (options, arguments) = getopt.getopt(sys.argv[1:], "e:p:x:")

    prefix= ""
    for (opt, val) in options:
        if opt == '-e':
            interpreter = EditInterpreter(val)
            interpreter.cmdloop("Welcome to imagehack.")
            break
        elif opt == '-p':
            prefix = val
        elif opt == '-x':
            os.mkdir(prefix)
            if not os.path.isdir(val):
                SpecFile(val).burst()
            else:
                def walker(file, dest):
                    try:
                        SpecFile(file).burst(dest)
                    except SyntaxError:
                        print "Failed while reading", file
                        raise SystemExit, 1
                traverse(val, walker, prefix) 
            break

# End

--
                                                >>esr>>


[Prev in Thread] Current Thread [Next in Thread]
  • [freeciv-data] The resource editor, a promised, Eric S. Raymond <=