#----------------------------------------------------------------------
# Name:        wx.build.config
# Purpose:     Most of the contents of this module used to be located 
#              in wxPython's setup.py script.  It was moved here so
#              it would be installed with the rest of wxPython and
#              could therefore be used by the setup.py for other
#              projects that needed this same info and functionality
#              (most likely in order to be compatible with wxPython.)
#
#              This split from setup.py is still fairly rough, and
#              some things may still get shuffled back and forth,
#              refactored, etc.  Please send me any comments and
#              suggestions about this.
#
# Author:      Robin Dunn
#
# Created:     23-March-2004
# RCS-ID:      $Id$
# Copyright:   (c) 2004 by Total Control Software
# Licence:     wxWindows license
#----------------------------------------------------------------------

import sys, os, glob, fnmatch, tempfile
import subprocess
import re

EGGing = 'bdist_egg' in sys.argv or 'egg_info' in sys.argv
if not EGGing:
    from distutils.core import setup, Extension
else:
    # EXPERIMENTAL Egg support...
    try:
        import ez_setup
        ez_setup.use_setuptools()
        from setuptools import setup, Extension
    except ImportError:
        print "Setuptools must be installed to build an egg"
        sys.exit(1)

from distutils.file_util import copy_file
from distutils.dir_util  import mkpath
from distutils.dep_util  import newer
from distutils.spawn     import spawn

import distutils.command.install
import distutils.command.install_data
import distutils.command.install_headers
import distutils.command.clean

from cfg_version import *

#----------------------------------------------------------------------
# flags and values that affect this script
#----------------------------------------------------------------------

DESCRIPTION      = "Cross platform GUI toolkit for Python"
AUTHOR           = "Robin Dunn"
AUTHOR_EMAIL     = "Robin Dunn <robin@alldunn.com>"
URL              = "http://wxPython.org/"
DOWNLOAD_URL     = "http://wxPython.org/download.php"
LICENSE          = "wxWidgets Library License (LGPL derivative)"
PLATFORMS        = "WIN32,OSX,POSIX"
KEYWORDS         = "GUI,wx,wxWindows,wxWidgets,cross-platform,awesome"

LONG_DESCRIPTION = """\
wxPython is a GUI toolkit for Python that is a wrapper around the
wxWidgets C++ GUI library.  wxPython provides a large variety of
window types and controls, all implemented with a native look and
feel (by using the native widgets) on the platforms upon which it is
supported.
"""

CLASSIFIERS      = """\
Development Status :: 6 - Mature
Environment :: MacOS X :: Carbon
Environment :: Win32 (MS Windows)
Environment :: X11 Applications :: GTK
Intended Audience :: Developers
License :: OSI Approved
Operating System :: MacOS :: MacOS X
Operating System :: Microsoft :: Windows :: Windows 98/2000/XP/Vista
Operating System :: POSIX
Programming Language :: Python
Topic :: Software Development :: User Interfaces
"""

## License :: OSI Approved :: wxWidgets Library Licence


# Config values below this point can be reset on the setup.py command line.

BUILD_GLCANVAS = 1 # If true, build the contrib/glcanvas extension module
BUILD_STC = 1      # If true, build the contrib/stc extension module
BUILD_GIZMOS = 1   # Build a module for the gizmos contrib library
BUILD_DLLWIDGET = 0# Build a module that enables unknown wx widgets
                   # to be loaded from a DLL and to be used from Python.

                   # Internet Explorer wrapper (experimental)
BUILD_ACTIVEX = (os.name == 'nt')


CORE_ONLY = 0      # if true, don't build any of the above

PREP_ONLY = 0      # Only run the prepatory steps, not the actual build.

USE_SWIG = 0       # Should we actually execute SWIG, or just use the
                   # files already in the distribution?

SWIG = "swig"      # The swig executable to use.

BUILD_RENAMERS = 0 # Should we build the renamer modules too?

FULL_DOCS = 0      # Some docstrings are split into a basic docstring and a
                   # details string.  Setting this flag to 1 will
                   # cause the two strings to be combined and output
                   # as the full docstring.

UNICODE = 1        # This will pass the 'wxUSE_UNICODE' flag to SWIG and
                   # will ensure that the right headers are found and the
                   # right libs are linked.

UNDEF_NDEBUG = 1   # Python 2.2 on Unix/Linux by default defines NDEBUG,
                   # and distutils will pick this up and use it on the
                   # compile command-line for the extensions.  This could
                   # conflict with how wxWidgets was built.  If NDEBUG is
                   # set then wxWidgets' __WXDEBUG__ setting will be turned
                   # off.  If wxWidgets was actually built with it turned
                   # on then you end up with mismatched class structures,
                   # and wxPython will crash.

NO_SCRIPTS = 0     # Don't install the tool scripts
NO_HEADERS = 0     # Don't install the wxPython *.h and *.i files

INSTALL_MULTIVERSION = 1 # Install the packages such that multiple versions
                   # can co-exist.  When turned on the wx and wxPython
                   # pacakges will be installed in a versioned subdir
                   # of site-packages, and a *.pth file will be
                   # created that adds that dir to the sys.path.  In
                   # addition, a wxselect.py module will be installed
                   # to site-pacakges that will allow applications to
                   # choose a specific version if more than one is
                   # installed.
                   
FLAVOUR = ""       # Optional flavour string to be appended to VERSION
                   # in MULTIVERSION installs

EP_ADD_OPTS = 1    # When doing MULTIVERSION installs the wx port and
                   # ansi/unicode settings can optionally be added to the
                   # subdir path used in site-packages

EP_FULL_VER = 0    # When doing MULTIVERSION installs the default is to
                   # put only 2 or 3 (depending on stable/unstable) of
                   # the version compnonents into the "extra path"
                   # subdir of site-packages.  Setting this option to
                   # 1 will cause the full 4 components of the version
                   # number to be used instead.
                                      
WX_CONFIG = None   # Usually you shouldn't need to touch this, but you can set
                   # it to pass an alternate version of wx-config or alternate
                   # flags, eg. as required by the .deb in-tree build.  By
                   # default a wx-config command will be assembled based on
                   # version, port, etc. and it will be looked for on the
                   # default $PATH.

SYS_WX_CONFIG = None # When installing an in tree build, setup.py uses wx-config
                     # for two different purposes.  First, to determine the prefix
                     # where files will be installed, and secondly, to initialise
                     # build_options.py with the correct options for it.
                     # WX_CONFIG is used for the first task.  SYS_WX_CONFIG may
                     # be set independently, to the value that should appear in
                     # build_options.py, if it is different to that.  The default
                     # is to use the value of WX_CONFIG.

WXPORT = 'gtk2'    # On Linux/Unix there are several ports of wxWidgets available.
                   # Setting this value lets you select which will be used for
                   # the wxPython build.  Possibilities are 'gtk', 'gtk2',
                   # 'gtk3', and 'x11'.  Currently only gtk2, and gtk3 work.

BUILD_BASE = "build" # Directory to use for temporary build files.
                     # This name will be appended to if the WXPORT or
                     # the UNICODE flags are set to non-standard
                     # values.  See below.


CONTRIBS_INC = ""  # A dir to add as an -I flag when compiling the contribs


# Some MSW build settings

MONOLITHIC = 0     # The core wxWidgets lib can be built as either a
                   # single monolithic DLL or as a collection of DLLs.
                   # This flag controls which set of libs will be used
                   # on Windows.  (For other platforms it is automatic
                   # via using wx-config.)

                   # Version part of wxWidgets LIB/DLL names
WXDLLVER = '%d%d' % (VER_MAJOR, VER_MINOR)


COMPILER = 'msvc'  # Used to select which compiler will be used on
                   # Windows.  This not only affects distutils, but
                   # also some of the default flags and other
                   # assumptions in this script.  Current supported
                   # values are 'msvc' and 'mingw32'

WXPY_SRC = '.'  # Assume we're in the source tree already, but allow the
                # user to change it, particularly for extension building.

ARCH = ''       # If this is set, add an -arch XXX flag to cflags
                # Only tested (and presumably, needed) for OS X universal
                # binary builds created using lipo.


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

def msg(text):
    if hasattr(sys, 'setup_is_main') and sys.setup_is_main:
        print text


def opj(*args):
    path = os.path.join(*args)
    return os.path.normpath(path)


def libFlag():
    if not debug:
        rv = ''
    else:
        rv = 'd'
    if UNICODE:
        rv = 'u' + rv
    return rv


#----------------------------------------------------------------------
# Some other globals
#----------------------------------------------------------------------

PKGDIR = 'wx'
wxpExtensions = []
DATA_FILES = []
CLEANUP = []

force = '--force' in sys.argv or '-f' in sys.argv
debug = '--debug' in sys.argv or '-g' in sys.argv
cleaning = 'clean' in sys.argv


# change the PORT default for wxMac
if sys.platform[:6] == "darwin":
    WXPORT = 'osx_carbon'

# and do the same for wxMSW, just for consistency
if os.name == 'nt':
    WXPORT = 'msw'

WXPYTHON_TYPE_TABLE = '_wxPython_table'

#----------------------------------------------------------------------
# Check for build flags on the command line
#----------------------------------------------------------------------

# Boolean (int) flags
for flag in [ 'BUILD_ACTIVEX', 'BUILD_DLLWIDGET',
              'BUILD_GIZMOS', 'BUILD_GLCANVAS', 'BUILD_STC',     
             'CORE_ONLY', 'PREP_ONLY', 'USE_SWIG', 'UNICODE',
             'UNDEF_NDEBUG', 'NO_SCRIPTS', 'NO_HEADERS', 'BUILD_RENAMERS',
             'FULL_DOCS', 'INSTALL_MULTIVERSION', 'EP_ADD_OPTS', 'EP_FULL_VER',
             'MONOLITHIC', ]:
    for x in range(len(sys.argv)):
        if sys.argv[x].find(flag) == 0:
            pos = sys.argv[x].find('=') + 1
            if pos > 0:
                vars()[flag] = eval(sys.argv[x][pos:])
                sys.argv[x] = ''

# String options
for option in ['WX_CONFIG', 'SYS_WX_CONFIG', 'WXDLLVER', 'BUILD_BASE',
               'WXPORT', 'SWIG', 'CONTRIBS_INC', 'WXPY_SRC', 'FLAVOUR',
               'VER_FLAGS', 'ARCH', 'COMPILER',
               ]:
    for x in range(len(sys.argv)):
        if sys.argv[x].find(option) == 0:
            pos = sys.argv[x].find('=') + 1
            if pos > 0:
                vars()[option] = sys.argv[x][pos:]
                sys.argv[x] = ''

sys.argv = filter(None, sys.argv)


#----------------------------------------------------------------------
# some helper functions
#----------------------------------------------------------------------

def Verify_WX_CONFIG():
    """ Called below for the builds that need wx-config, if WX_CONFIG
        is not set then determines the flags needed based on build
        options and searches for wx-config on the PATH.  
    """
    # if WX_CONFIG hasn't been set to an explicit value then construct one.
    global WX_CONFIG
    if WX_CONFIG is None:
        WX_CONFIG='wx-config'
        port = WXPORT
        if port == "x11":
            port = "x11univ"
        flags =  ' --toolkit=%s' % port
        flags += ' --unicode=%s' % (UNICODE and 'yes' or 'no')
        flags += ' --version=%s.%s' % (VER_MAJOR, VER_MINOR)

        searchpath = os.environ["PATH"]
        for p in searchpath.split(':'):
            fp = os.path.join(p, 'wx-config')
            if os.path.exists(fp) and os.access(fp, os.X_OK):
                # success
                msg("Found wx-config: " + fp)
                msg("    Using flags: " + flags)
                WX_CONFIG = fp + flags
                if hasattr(sys, 'setup_is_main') and not sys.setup_is_main:
                    WX_CONFIG += " 2>/dev/null "
                break
        else:
            msg("ERROR: WX_CONFIG not specified and wx-config not found on the $PATH")
            # should we exit?

        # TODO:  execute WX_CONFIG --list and verify a matching config is found
    


def getWxConfigValue(flag):
    cmd = "%s --version=%s.%s  %s" % (WX_CONFIG, VER_MAJOR, VER_MINOR, flag)
    value = os.popen(cmd, 'r').read()[:-1]
    return value


def run_swig(files, dir, gendir, package, USE_SWIG, force, swig_args,
             swig_deps=[], add_under=False):
    """Run SWIG the way I want it done"""

    if USE_SWIG and not os.path.exists(os.path.join(dir, gendir)):
        os.mkdir(os.path.join(dir, gendir))

    sources = []

    if add_under:  pre = '_'
    else:          pre = ''
        
    for file in files:
        basefile = os.path.splitext(file)[0]
        i_file   = os.path.join(dir, file)
        py_file  = os.path.join(dir, gendir, pre+basefile+'.py')
        cpp_file = os.path.join(dir, gendir, pre+basefile+'_wrap.cpp')

        if add_under:
            interface = ['-interface', '_'+basefile+'_']
        else:
            interface = []
            
        sources.append(cpp_file)

        if not cleaning and USE_SWIG:
            for dep in swig_deps:
                # this may fail for external builds, but it's not 
                # a fatal error, so keep going.
                try:
                    if newer(dep, py_file) or newer(dep, cpp_file):
                        force = 1
                        break
                except:
                    pass

            if force or newer(i_file, py_file) or newer(i_file, cpp_file):
                ## we need forward slashes here, even on win32
                #cpp_file = opj(cpp_file) #'/'.join(cpp_file.split('\\'))
                #i_file = opj(i_file)     #'/'.join(i_file.split('\\'))

                if BUILD_RENAMERS:
                    xmltemp = tempfile.mktemp('.xml')

                    # First run swig to produce the XML file, adding
                    # an extra -D that prevents the old rename
                    # directives from being used
                    cmd = [ swig_cmd ] + swig_args + \
                          [ '-DBUILDING_RENAMERS', '-xmlout', xmltemp ] + \
                          ['-I'+dir, '-o', cpp_file, i_file]
                    msg(' '.join(cmd))
                    spawn(cmd)

                    # Next run build_renamers to process the XML
                    myRenamer = BuildRenamers()
                    myRenamer.run(dir, pre+basefile, xmltemp)
                    os.remove(xmltemp)

                # Then run swig for real
                cmd = [ swig_cmd ] + swig_args + interface + \
                      ['-I'+dir, '-o', cpp_file, i_file]
                msg(' '.join(cmd))
                spawn(cmd)


        # copy the generated python file to the package directory
        copy_file(py_file, package, update=not force, verbose=0)
        CLEANUP.append(opj(package, os.path.basename(py_file)))

    return sources


def swig_version():
    # It may come on either stdout or stderr, depending on the
    # version, so read both.
    p = subprocess.Popen(SWIG + ' -version', shell=True, universal_newlines=True,
                 stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stext = p.stdout.read() + p.stderr.read()
    import re
    match = re.search(r'[0-9]+\.[0-9]+\.[0-9]+$', stext, re.MULTILINE)
    if not match:
        raise RuntimeError('SWIG version not found')
    SVER = match.group(0)
    return SVER


# Specializations of some distutils command classes
class wx_smart_install_data(distutils.command.install_data.install_data):
    """need to change self.install_dir to the actual library dir"""
    def run(self):
        install_cmd = self.get_finalized_command('install')
        self.install_dir = getattr(install_cmd, 'install_lib')
        return distutils.command.install_data.install_data.run(self)


class wx_extra_clean(distutils.command.clean.clean):
    """
    Also cleans stuff that this setup.py copies itself.  If the
    --all flag was used also searches for .pyc, .pyd, .so files
    """
    def run(self):
        from distutils import log
        from distutils.filelist import FileList
        global CLEANUP

        distutils.command.clean.clean.run(self)

        if self.all:
            fl = FileList()
            fl.include_pattern("*.pyc", 0)
            fl.include_pattern("*.pyd", 0)
            fl.include_pattern("*.so", 0)
            CLEANUP += fl.files

        for f in CLEANUP:
            if os.path.isdir(f):
                try:
                    if not self.dry_run and os.path.exists(f):
                        os.rmdir(f)
                    log.info("removing '%s'", f)
                except IOError:
                    log.warn("unable to remove '%s'", f)

            else:
                try:
                    if not self.dry_run and os.path.exists(f):
                        os.remove(f)
                    log.info("removing '%s'", f)
                except IOError:
                    log.warn("unable to remove '%s'", f)



# The Ubuntu Python adds a --install-layout option to distutils that
# is used in our package build.  If we detect that the current
# distutils does not have it then make sure that it is removed from
# the command-line options, otherwise the build will fail.
for item in distutils.command.install.install.user_options:
    if item[0] == 'install-layout=':
        break
else:
    for arg in sys.argv:
        if arg.startswith('--install-layout'):
            sys.argv.remove(arg)
            break



class wx_install(distutils.command.install.install):
    """
    Turns off install_path_file
    """
    def initialize_options(self):
        distutils.command.install.install.initialize_options(self)
        self.install_path_file = 0


class wx_install_headers(distutils.command.install_headers.install_headers):
    """
    Install the header files to the WXPREFIX, with an extra dir per
    filename too
    """
    def initialize_options(self):
        self.root = None
        distutils.command.install_headers.install_headers.initialize_options(self)

    def finalize_options(self):
        self.set_undefined_options('install', ('root', 'root'))
        distutils.command.install_headers.install_headers.finalize_options(self)

    def run(self):
        if os.name == 'nt':
            return
        headers = self.distribution.headers
        if not headers:
            return

        root = self.root
        #print "WXPREFIX is %s, root is %s" % (WXPREFIX, root)
        # hack for universal builds, which append i386/ppc
        # to the root
        if root is None or WXPREFIX.startswith(os.path.dirname(root)):
            root = ''
        for header, location in headers:
            install_dir = os.path.normpath(root +
                                           WXPREFIX +
                                           '/include/wx-%d.%d/wx' % (VER_MAJOR, VER_MINOR) +
                                           location)
            self.mkpath(install_dir)
            (out, _) = self.copy_file(header, install_dir)
            self.outfiles.append(out)



def build_locale_dir(destdir, verbose=1):
    """Build a locale dir under the wxPython package for MSW"""
    moFiles = glob.glob(opj(WXDIR, 'locale', '*.mo'))
    for src in moFiles:
        lang = os.path.splitext(os.path.basename(src))[0]
        #dest = opj(destdir, lang)
        dest = opj(destdir, lang, 'LC_MESSAGES')
        mkpath(dest, verbose=verbose)
        copy_file(src, opj(dest, 'wxstd.mo'), update=1, verbose=verbose)
        CLEANUP.append(opj(dest, 'wxstd.mo'))
        CLEANUP.append(dest)


def build_locale_list(srcdir):
    # get a list of all files under the srcdir, to be used for install_data
    def walk_helper(lst, dirname, files):
        for f in files:
            filename = opj(dirname, f)
            if not os.path.isdir(filename):
                lst.append( (dirname, [filename]) )
    file_list = []
    os.path.walk(srcdir, walk_helper, file_list)
    return file_list


def find_data_files(srcdir, *wildcards, **kw):
    # get a list of all files under the srcdir matching wildcards,
    # returned in a format to be used for install_data
    
    def walk_helper(arg, dirname, files):
        if '.svn' in dirname:
            return
        names = []
        lst, wildcards = arg
        for wc in wildcards:
            wc_name = opj(dirname, wc)
            for f in files:
                filename = opj(dirname, f)
                
                if fnmatch.fnmatch(filename, wc_name) and not os.path.isdir(filename):
                    names.append(filename)
        if names:
            lst.append( (dirname, names ) )

    file_list = []
    recursive = kw.get('recursive', True)
    if recursive:
        os.path.walk(srcdir, walk_helper, (file_list, wildcards))
    else:
        walk_helper((file_list, wildcards),
                    srcdir,
                    [os.path.basename(f) for f in glob.glob(opj(srcdir, '*'))])
    return file_list


def makeLibName(name):
    if os.name == 'posix' or COMPILER == 'mingw32':
        libname = '%s_%s-%s' % (WXBASENAME, name, WXRELEASE)
    elif name:
        libname = 'wxmsw%s%s_%s' % (WXDLLVER, libFlag(), name)
    else:
        libname = 'wxmsw%s%s' % (WXDLLVER, libFlag())
    return [libname]


def findLib(name, libdirs):
    name = makeLibName(name)[0]
    if os.name == 'posix' or COMPILER == 'mingw32':
        lflags = getWxConfigValue('--libs')
        lflags = lflags.split()
        
        # if wx-config --libs output does not start with -L, wx is
        # installed with a standard prefix and wx-config does not
        # output these libdirs because they are already searched by
        # default by the compiler and linker.
        if lflags[0][:2] != '-L':  
            dirs = libdirs + ['/usr/lib', '/usr/local/lib']
        else:
            dirs = libdirs
        name = 'lib'+name
    else:
        dirs = libdirs[:]
    for d in dirs:
        p = os.path.join(d, name)
        if glob.glob(p+'*') != []:
            return True
    return False


def removeDuplicates(seq):
    # This code causes problems on OS X as we do need some duplicates
    # there...  TODO: are there actually times when having duplicates hurts us?
##     seen = {}
##     result = []
##     for item in seq:
##         if item in seen:
##             continue
##         seen[item] = 1
##         result.append(item)
##     return result
    return seq


def adjustCFLAGS(cflags, defines, includes):
    '''Extract the raw -I, -D, and -U flags and put them into
       defines and includes as needed.'''
    newCFLAGS = []
    for flag in cflags:
        if flag[:2] == '-I':
            includes.append(flag[2:])
        elif flag[:2] == '-D':
            flag = flag[2:]
            if flag.find('=') == -1:
                defines.append( (flag, None) )
            else:
                defines.append( tuple(flag.split('=')) )
        elif flag[:2] == '-U':
            defines.append( (flag[2:], ) )
        else:
            newCFLAGS.append(flag)
    return removeDuplicates(newCFLAGS)



def adjustLFLAGS(lflags, libdirs, libs):
    '''Extract the -L and -l flags and put them in libdirs and libs as needed'''
    newLFLAGS = []
    for flag in lflags:
        if flag[:2] == '-L':
            libdirs.append(flag[2:])
        elif flag[:2] == '-l':
            libs.append(flag[2:])
        else:
            newLFLAGS.append(flag)
    return removeDuplicates(newLFLAGS) 



def getExtraPath(shortVer=True, addOpts=False, addRelease=True):
    """Get the dirname that wxPython will be installed under."""

    if shortVer:
        # short version, just Major.Minor
        ep = "wx-%d.%d" % (VER_MAJOR, VER_MINOR)
         
        # plus release if minor is odd
        if addRelease and VER_MINOR % 2 == 1:
            ep += ".%d" % VER_RELEASE
            
    else:
        # long version, full version 
        ep = "wx-%d.%d.%d.%d" % (VER_MAJOR, VER_MINOR, VER_RELEASE, VER_SUBREL)

    if addOpts:
        port = WXPORT
        if port == "msw": port = "win32"
        #ep += "-%s-%s" % (WXPORT, (UNICODE and 'unicode' or 'ansi'))
        # no more ansi builds, so no need to include chartype in the path any more
        ep += '-' + WXPORT
        
    if FLAVOUR:
        ep += "-" + FLAVOUR

    return ep


def getoutput(cmd):
    sp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = None
    output = sp.stdout.read()
    if sys.version_info > (3,):
        output = output.decode('utf-8')  # TODO: is utf-8 okay here?
    output = output.rstrip()
    rval = sp.wait()
    if rval:
        # Failed!
        print("Command '%s' failed with exit code %d." % (cmd, rval))
        sys.exit(rval)
    return output

def getVisCVersion():
    text = getoutput("cl.exe")
    if 'Version 13' in text:
        return '71'
    if 'Version 15' in text:
        return '90'
    # TODO: Add more tests to get the other versions...
    else:
        return 'UNKNOWN'
 
#----------------------------------------------------------------------
# These functions and class are copied from distutils in Python 2.5
# and then grafted back into the distutils modules so we can change
# how the -arch and -isysroot compiler args are handled.  Basically if
# -arch is specified in our compiler args then we need to strip all of
# the -arch and -isysroot args provided by Python.

import distutils.unixccompiler
import distutils.sysconfig
from distutils.errors import DistutilsExecError, CompileError

def _darwin_compiler_fixup(compiler_so, cc_args):
    """
    This function will strip '-isysroot PATH' and '-arch ARCH' from the
    compile flags if the user has specified one of them in extra_compile_flags.

    This is needed because '-arch ARCH' adds another architecture to the
    build, without a way to remove an architecture. Furthermore GCC will
    barf if multiple '-isysroot' arguments are present.
    
    Robin: I've further modified our copy of this function to check if there
    is a -isysroot flag in the CC/CXX values in the environment. If so then we
    want to make sure that we keep that one and strip the others, instead of
    stripping it and leaving Python's.
    """
    
    ccHasSysroot = '-isysroot' in os.environ.get('CC', '') \
                 or '-isysroot' in os.environ.get('CXX', '')
    
    stripArch = stripSysroot = 0

    compiler_so = list(compiler_so)
    kernel_version = os.uname()[2] # 8.4.3
    major_version = int(kernel_version.split('.')[0])

    if major_version < 8:
        # OSX before 10.4.0, these don't support -arch and -isysroot at
        # all.
        stripArch = stripSysroot = True
    else:
        stripArch = '-arch' in cc_args
        stripSysroot = '-isysroot' in cc_args or stripArch or ccHasSysroot

    if stripArch:
        while 1:
            try:
                index = compiler_so.index('-arch')
                # Strip this argument and the next one:
                del compiler_so[index:index+2]
            except ValueError:
                break

    if stripSysroot:
        try:
            index = 0
            if ccHasSysroot:
                index = compiler_so.index('-isysroot') + 1
            index = compiler_so.index('-isysroot', index)
            # Strip this argument and the next one:
            del compiler_so[index:index+2]
        except ValueError:
            pass

    # Check if the SDK that is used during compilation actually exists, 
    # the universal build requires the usage of a universal SDK and not all
    # users have that installed by default.
    sysroot = None
    if '-isysroot' in cc_args:
        idx = cc_args.index('-isysroot')
        sysroot = cc_args[idx+1]
    elif '-isysroot' in compiler_so:
        idx = compiler_so.index('-isysroot')
        sysroot = compiler_so[idx+1]

    if sysroot and not os.path.isdir(sysroot):
        from distutils import log
        log.warn("Compiling with an SDK that doesn't seem to exist: %s",
                sysroot)
        log.warn("Please check your Xcode installation")

    return compiler_so


def _darwin_compiler_fixup_24(compiler_so, cc_args):
    compiler_so = _darwin_compiler_fixup(compiler_so, cc_args)
    return compiler_so, cc_args


class MyUnixCCompiler(distutils.unixccompiler.UnixCCompiler):
    def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
        compiler_so = self.compiler_so
        if sys.platform == 'darwin':           
            compiler_so = _darwin_compiler_fixup(compiler_so, cc_args + extra_postargs)
        # Mandriva / Mageia Hack ------------------------------------
        #self.linker_so = [el for el in self.linker_so if el != '-Wl,--no-undefined']
        #compiler_so = [el for el in compiler_so if el != '-Werror=format-security']
        # Mandriva / Mageia Hack ------------------------------------
        try:
            self.spawn(compiler_so + cc_args + [src, '-o', obj] +
                       extra_postargs)
        except DistutilsExecError, msg:
            raise CompileError, msg


_orig_parse_makefile = distutils.sysconfig.parse_makefile
def _parse_makefile(filename, g=None):
    rv = _orig_parse_makefile(filename, g)

    # If a different deployment target is specified in the
    # environment then make sure it is put in the global
    # config dict.
    if os.getenv('MACOSX_DEPLOYMENT_TARGET'):
        val = os.getenv('MACOSX_DEPLOYMENT_TARGET')
        rv['MACOSX_DEPLOYMENT_TARGET'] = val
        rv['CONFIGURE_MACOSX_DEPLOYMENT_TARGET'] = val

    return rv


distutils.unixccompiler.UnixCCompiler = MyUnixCCompiler
distutils.unixccompiler._darwin_compiler_fixup = _darwin_compiler_fixup
distutils.unixccompiler._darwin_compiler = _darwin_compiler_fixup_24
distutils.sysconfig.parse_makefile = _parse_makefile


#----------------------------------------------------------------------
# Another hack-job for the CygwinCCompiler class, this time replacing
# the _compile function with one that will pass the -I flags to windres.

import distutils.cygwinccompiler
from distutils.errors import DistutilsExecError, CompileError

def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
    if ext == '.rc' or ext == '.res':
        # gcc needs '.res' and '.rc' compiled to object files !!!
        try:
            #self.spawn(["windres", "-i", src, "-o", obj])
            self.spawn(["windres", "-i", src, "-o", obj] +
                       [arg for arg in cc_args if arg.startswith("-I")] )
        except DistutilsExecError, msg:
            raise CompileError, msg
    else: # for other files use the C-compiler
        try:
            self.spawn(self.compiler_so + cc_args + [src, '-o', obj] +
                       extra_postargs)
        except DistutilsExecError, msg:
            raise CompileError, msg

distutils.cygwinccompiler.CygwinCCompiler._compile = _compile


#----------------------------------------------------------------------
# Yet another distutils hack, this time for the msvc9compiler.  There
# is a bug in at least version distributed with Python 2.6 where it
# adds '/pdb:None' to the linker command-line, but that just results
# in a 'None' file being created instead of putting the debug info
# into the .pyd files as expected.  So we'll strip out that option via
# a monkey-patch of the msvc9compiler.MSVCCompiler.initialize method.

if os.name == 'nt' and  COMPILER == 'msvc' and sys.version_info >= (2,6):
    import distutils.msvc9compiler
    _orig_initialize = distutils.msvc9compiler.MSVCCompiler.initialize

    def _initialize(self, *args, **kw):
        rv = _orig_initialize(self, *args, **kw)
        try:
            self.ldflags_shared_debug.remove('/pdb:None')
        except ValueError:
            pass
        return rv

    distutils.msvc9compiler.MSVCCompiler.initialize = _initialize


#----------------------------------------------------------------------
# sanity checks

if CORE_ONLY:
    BUILD_GLCANVAS = 0
    BUILD_STC = 0
    BUILD_GIZMOS = 0
    BUILD_DLLWIDGET = 0
    BUILD_ACTIVEX = 0


if UNICODE and WXPORT not in ['msw', 'gtk2', 'gtk3', 'osx_carbon', 'osx_cocoa']:
    raise SystemExit, "UNICODE mode not currently supported on this WXPORT: "+WXPORT


if CONTRIBS_INC:
    CONTRIBS_INC = [ CONTRIBS_INC ]
else:
    CONTRIBS_INC = []

if WXPORT != 'msw':
    # make sure we only use the compiler value on MSW builds
    COMPILER=None

WXPLAT2 = None

#----------------------------------------------------------------------
# Setup some platform specific stuff
#----------------------------------------------------------------------

if os.name == 'nt' and  COMPILER == 'msvc':
    # Set compile flags and such for MSVC.  These values are derived
    # from the wxWidgets makefiles for MSVC, other compilers settings
    # will probably vary...
    if os.environ.has_key('WXWIN'):
        WXDIR = os.environ['WXWIN']
    else:
        if os.path.exists('..\\wxWidgets'):
            WXDIR = '..\\wxWidgets'  # assumes in parallel SVN tree
        else:
            WXDIR = '..'  # assumes wxPython is subdir
        msg("WARNING: WXWIN not set in environment. Assuming '%s'" % WXDIR)
    WXPLAT = '__WXMSW__'
    GENDIR = 'msw'

    if os.environ.get('CPU', None) in ['AMD64', 'X64']:
        VCDLL = 'vc%s_x64_dll' % getVisCVersion()
    else:
        VCDLL = 'vc%s_dll' % getVisCVersion()
        
    includes = ['include', 'src',
                opj(WXDIR, 'lib', VCDLL, 'msw'  + libFlag()),
                opj(WXDIR, 'include'),
                opj(WXDIR, 'contrib', 'include'),
                ]

    defines = [ ('WIN32', None),
                ('_WINDOWS', None),

                (WXPLAT, None),
                ('WXUSINGDLL', '1'),

                ('SWIG_TYPE_TABLE', WXPYTHON_TYPE_TABLE),
                ('SWIG_PYTHON_OUTPUT_TUPLE', None),
                ('SWIG_PYTHON_SILENT_MEMLEAK', None),
                ('WXP_USE_THREAD', '1'),
                ('ISOLATION_AWARE_ENABLED', None),
                ]

    if UNDEF_NDEBUG:
        defines.append( ('NDEBUG',) )  # using a 1-tuple makes it do an undef

    if UNICODE:
        defines.append( ('wxUSE_UNICODE', 1) )

    libs = []
    libdirs = [ opj(WXDIR, 'lib', VCDLL) ]
    if MONOLITHIC:
        libs += makeLibName('')
    else:
        libs += [ 'wxbase' + WXDLLVER + libFlag(), 
                 'wxbase' + WXDLLVER + libFlag() + '_net',
                 'wxbase' + WXDLLVER + libFlag() + '_xml',
                 makeLibName('core')[0],
                 makeLibName('adv')[0],
                 makeLibName('html')[0],
                 ]

    libs += ['kernel32', 'user32', 'gdi32', 'comdlg32',
             'winspool', 'winmm', 'shell32', 'oldnames', 'comctl32',
             'odbc32', 'ole32', 'oleaut32', 'uuid', 'rpcrt4',
             'advapi32', 'wsock32']

    cflags = [ '/Gy',
               '/EHsc',
               # '/GX-'  # workaround for internal compiler error in MSVC on some machines
               ]
    lflags = None

    # Other MSVC flags...
    # Uncomment these to have debug info for all kinds of builds
    #cflags += ['/Od', '/Z7']
    #lflags = ['/DEBUG', ]


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

elif os.name == 'posix' or COMPILER == 'mingw32':
    if os.environ.has_key('WXWIN'):
        WXDIR = os.environ['WXWIN']
    else:
        if os.path.exists('../wxWidgets'):
            WXDIR = '../wxWidgets'  # assumes in parallel SVN tree
        else:
            WXDIR = '..'  # assumes wxPython is subdir
        msg("WARNING: WXWIN not set in environment. Assuming '%s'" % WXDIR)
    includes = ['include', 'src']
    defines = [('SWIG_TYPE_TABLE', WXPYTHON_TYPE_TABLE),
               ('SWIG_PYTHON_OUTPUT_TUPLE', None),
               ('SWIG_PYTHON_SILENT_MEMLEAK', None),
               ('WXP_USE_THREAD', '1'),
               ]
    if UNDEF_NDEBUG:
        defines.append( ('NDEBUG',) )  # using a 1-tuple makes it do an undef

    Verify_WX_CONFIG()

    libdirs = []
    libs = []

    # If you get unresolved symbol errors on Solaris and are using gcc, then
    # uncomment this block to add the right flags to the link step and build
    # again.
    ## if os.uname()[0] == 'SunOS':
    ##     import commands
    ##     libs.append('gcc')
    ##     libdirs.append(commands.getoutput("gcc -print-search-dirs | grep '^install' | awk '{print $2}'")[:-1])

    cflags = getWxConfigValue('--cxxflags')
    cflags = cflags.split()
    if debug:
        cflags.append('-ggdb')
        cflags.append('-O0')
    else:
        cflags.append('-O3')

    lflags = getWxConfigValue('--libs')
    MONOLITHIC = (lflags.find("_xrc") == -1)
    lflags = lflags.split()

    WXBASENAME = getWxConfigValue('--basename')
    WXRELEASE  = getWxConfigValue('--release')
    WXPREFIX   = getWxConfigValue('--prefix')


    if sys.platform[:6] == "darwin":
        WXPLAT = '__WXMAC__'
    
        if WXPORT == 'osx_carbon':
        # Flags and such for a Darwin (Max OS X) build of Python
            GENDIR = 'osx_carbon'
            WXPLAT2 = '__WXOSX_CARBON__'
        else:
            GENDIR = 'osx_cocoa'
            WXPLAT2 = '__WXOSX_COCOA__'

        libs = ['stdc++']
        NO_SCRIPTS = 1
        if ARCH != "":
            splitArch = "-arch " + re.sub(","," -arch ",ARCH)
            cflags.extend(splitArch.split(' '))
            lflags.extend(splitArch.split(' '))

        if not os.environ.get('CC') or not os.environ.get('CXX'):
            os.environ["CXX"] = getWxConfigValue('--cxx')
            os.environ["CC"]  = getWxConfigValue('--cc')

            # We want to use the linker command from wx to make sure
            # we get the right sysroot, but we also need to ensure that
            # the other linker flags that distutils wants to use are
            # included as well.
            LDSHARED = distutils.sysconfig.get_config_var('LDSHARED').split()
            # remove the compiler command
            del LDSHARED[0]
            # remove any -sysroot flags and their arg
            while 1:
                try:
                    index = LDSHARED.index('-isysroot')
                    # Strip this argument and the next one:
                    del LDSHARED[index:index+2]
                except ValueError:
                    break            
            LDSHARED = ' '.join(LDSHARED)
            # Combine with wx's ld command and stash it in the env
            # where distutils will get it later.
            LDSHARED = getWxConfigValue('--ld').replace(' -o', '') + ' ' + LDSHARED
            os.environ["LDSHARED"]  = LDSHARED

    else:
        # Set flags for other Unix type platforms
        GENDIR = WXPORT

        if WXPORT == 'gtk':
            WXPLAT = '__WXGTK__'
            portcfg = os.popen('gtk-config --cflags', 'r').read()[:-1]
            BUILD_BASE = BUILD_BASE + '-' + WXPORT
        elif WXPORT == 'gtk2':
            WXPLAT = '__WXGTK__'
            GENDIR = 'gtk' # no code differences so use the same generated sources
            portcfg = os.popen('pkg-config gtk+-2.0 --cflags', 'r').read()[:-1]
        elif WXPORT == 'gtk3':
            WXPLAT = '__WXGTK__'
            GENDIR = 'gtk' # no code differences so use the same generated sources
            portcfg = os.popen('pkg-config gtk+-3.0 --cflags', 'r').read()[:-1]
        elif WXPORT == 'x11':
            WXPLAT = '__WXX11__'
            portcfg = ''
            BUILD_BASE = BUILD_BASE + '-' + WXPORT
        elif WXPORT == 'msw':
            WXPLAT = '__WXMSW__'
            GENDIR = 'msw'
            portcfg = ''
        else:
            raise SystemExit, "Unknown WXPORT value: " + WXPORT

        cflags += portcfg.split()

        # Some distros (e.g. Mandrake) put libGLU in /usr/X11R6/lib, but
        # wx-config doesn't output that for some reason.  For now, just
        # add it unconditionally but we should really check if the lib is
        # really found there or wx-config should be fixed.
        if WXPORT != 'msw':
            libdirs.append("/usr/X11R6/lib")


    # Move the various -I, -D, etc. flags we got from the *config scripts
    # into the distutils lists.
    cflags = adjustCFLAGS(cflags, defines, includes)
    lflags = adjustLFLAGS(lflags, libdirs, libs)

    if debug and WXPORT == 'msw' and COMPILER != 'mingw32':
        defines.append( ('_DEBUG', None) )
        
##     from pprint import pprint
##     print 'cflags:',; pprint(cflags)
##     print 'defines:',; pprint(defines)
##     print 'includes:',; pprint(includes)
##     print
##     print 'lflags:',; pprint(lflags)
##     print 'libdirs:',; pprint(libdirs)
##     print 'libs:',; pprint(libs)
##     print
##     sys.exit()
    
#----------------------------------------------------------------------
else:
    raise Exception('Sorry, platform not supported...')


#----------------------------------------------------------------------
# build options file
#----------------------------------------------------------------------

if SYS_WX_CONFIG is None:
    SYS_WX_CONFIG = WX_CONFIG

build_options_template = """
UNICODE=%d
UNDEF_NDEBUG=%d
INSTALL_MULTIVERSION=%d
FLAVOUR="%s"
EP_ADD_OPTS=%d
EP_FULL_VER=%d
WX_CONFIG="%s"
WXPORT="%s"
MONOLITHIC=%d
""" % (UNICODE, UNDEF_NDEBUG, INSTALL_MULTIVERSION, FLAVOUR, EP_ADD_OPTS,
       EP_FULL_VER, SYS_WX_CONFIG, WXPORT, MONOLITHIC)

try: 
    from build_options import *
except:
    build_options_file = os.path.join(os.path.dirname(__file__), "build_options.py")
    if not os.path.exists(build_options_file):
        try:
            myfile = open(build_options_file, "w")
            myfile.write(build_options_template)
            myfile.close()
        except:
            print "WARNING: Unable to create build_options.py."
    

#----------------------------------------------------------------------
# post platform setup checks and tweaks, create the full version string
#----------------------------------------------------------------------

if os.path.exists('DAILY_BUILD'):
    VER_FLAGS += '.b' + open('DAILY_BUILD').read().strip()

VERSION = "%s.%s.%s.%s%s" % (VER_MAJOR, VER_MINOR, VER_RELEASE,
                             VER_SUBREL, VER_FLAGS)


#----------------------------------------------------------------------
# SWIG defaults
#----------------------------------------------------------------------

# *.i files could live in the wxWidgets/wxPython/src dir, or in 
# a subdirectory of the devel package. Let's specify both 
# dirs as includes so we don't have to guess which is correct.
 
wxfilesdir = ""
i_subdir = opj("include", getExtraPath(addRelease=False), "wx", "wxPython", "i_files")
if os.name != "nt":
    wxfilesdir = opj(WXPREFIX, i_subdir)
else:
    wxfilesdir = opj(WXPY_SRC, i_subdir)

i_files_includes = [ '-I' + opj(WXPY_SRC, 'src'),
                     '-I' + wxfilesdir ]

swig_cmd = SWIG
swig_force = force
swig_args = ['-c++',
             #'-Wall',
             '-python',
             '-new_repr',
             '-modern',
             '-D'+WXPLAT,
             ]
if WXPLAT2:
    swig_args.append('-D' + WXPLAT2)
    
swig_args += i_files_includes

if USE_SWIG:
    SVER = swig_version()
    if int(SVER[-2:]) >= 29:
        swig_args += [ '-fastdispatch',
                       '-fvirtual',
                       '-fastinit',
                       '-fastunpack',
                       #'-outputtuple',  Currently setting this with a -D define above
                       ]
             
if UNICODE:
    swig_args.append('-DwxUSE_UNICODE')

if FULL_DOCS:
    swig_args.append('-D_DO_FULL_DOCS')
    

swig_deps = [ opj(WXPY_SRC, 'src/my_typemaps.i'),
              opj(WXPY_SRC, 'src/pyfragments.swg'),
              ]

depends = [ #'include/wx/wxPython/wxPython.h',
            #'include/wx/wxPython/wxPython_int.h',
            #'src/pyclasses.h',
            ]

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

