# This script generates the PyQt configuration and generates the Makefiles.
#
# Copyright (c) 2004
# 	Riverbank Computing Limited <info@riverbankcomputing.co.uk>
# 
# This file is part of PyQt.
# 
# This copy of PyQt is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2, or (at your option) any later
# version.
# 
# PyQt is supplied in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
# 
# You should have received a copy of the GNU General Public License along with
# PyQt; see the file LICENSE.  If not, write to the Free Software Foundation,
# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.


import sys
import os
import string
import glob
import getopt
import shutil
import py_compile

import sipconfig


# Initialise the globals.
pyqt_version = 0x030d00
pyqt_version_str = "3.13"

sip_min_v3_version = 0x030a02
sip_min_v4_version = 0x040000

pyqt_modules = ["qt"]
qt_sip_flags = []
qtext_sip_flags = []
qtpe_sip_flags = []
qsci_version = 0
disabled_classes = []

if sys.platform == "win32":
    qsci_define = "QEXTSCINTILLA_DLL"
else:
    qsci_define = ""

# Get the SIP configuration.
sipcfg = sipconfig.Configuration()

if sipcfg.qt_version == 0:
    sipconfig.error("SIP has been built with Qt support disabled.")

# Command line options.
opt_pyqtbindir = sipcfg.default_bin_dir
opt_pyqtmoddir = sipcfg.default_mod_dir
opt_pyqtsipdir = sipcfg.default_sip_dir
opt_qtpetag = None
opt_qsciincdir = sipcfg.qt_inc_dir
opt_qscilibdir = sipcfg.qt_lib_dir
opt_static = 0
opt_debug = 0
opt_concat = 0
opt_split = 1
opt_releasegil = 0
opt_tracing = 0
opt_verbose = 0


def usage(rcode = 2):
    """Display a usage message and exit.

    rcode is the return code passed back to the calling process.
    """
    print "Usage:"
    print "    python configure.py [-h] [-a tag] [-b dir] [-c] [-d dir] [-g] [-j #] [-k] [-n dir] [-o dir] [-r] [-s] [-u] [-v dir] [-w]"
    print "where:"
    print "    -h      display this help message"
    print "    -a tag  explicitly enable the qtpe module"
    print "    -b dir  where pyuic and pylupdate will be installed [default %s]" % opt_pyqtbindir
    print "    -c      concatenate each module's C/C++ source files"
    print "    -d dir  where the PyQt modules will be installed [default %s]" % opt_pyqtmoddir
    print "    -g      always release the GIL (SIP v3.x behaviour)"
    print "    -j #    split the concatenated C++ source files into # pieces [default 1]"
    print "    -k      build the PyQt modules as static libraries"
    print "    -n dir  the directory containing the QScintilla header files [default %s]" % opt_qsciincdir
    print "    -o dir  the directory containing the QScintilla library [default %s]" % opt_qscilibdir
    print "    -r      generate code with tracing enabled [default disabled]"
    print "    -s      QScintilla is a static library and not a DLL (Windows only)"
    print "    -u      build with debugging symbols"
    print "    -v dir  where the PyQt .sip files will be installed [default %s]" % opt_pyqtsipdir
    print "    -w      don't suppress compiler output during configuration"

    sys.exit(rcode)


def inform_user():
    """Tell the user the option values that are going to be used.
    """
    sipconfig.inform("These PyQt modules will be built: %s." % string.join(pyqt_modules))
    sipconfig.inform("Support for these Qt classes has been disabled: %s." % string.join(disabled_classes))
    sipconfig.inform("The PyQt modules will be installed in %s." % opt_pyqtmoddir)
    sipconfig.inform("The PyQt .sip files will be installed in %s." % opt_pyqtsipdir)

    if sipcfg.qt_version >= 0x020000:
        sipconfig.inform("pyuic will be installed in %s." % opt_pyqtbindir)

    if sipcfg.qt_version >= 0x030000:
        sipconfig.inform("pylupdate will be installed in %s." % opt_pyqtbindir)


def create_config(module, template):
    """Create the PyQt configuration module so that it can be imported by build
    scripts.

    module is the module file name.
    template is the template file name.
    """
    sipconfig.inform("Creating %s..." % module)

    content = {
        "pyqt_version":       pyqt_version,
        "pyqt_version_str":   pyqt_version_str,
        "pyqt_bin_dir":       opt_pyqtbindir,
        "pyqt_mod_dir":       opt_pyqtmoddir,
        "pyqt_sip_dir":       opt_pyqtsipdir,
        "pyqt_modules":       pyqt_modules,
        "pyqt_qt_sip_flags":  qt_sip_flags
    }

    if "qtaxcontainer" in pyqt_modules:
        content["pyqt_qtaxcontainer_sip_flags"] = qt_sip_flags

    if "qtcanvas" in pyqt_modules:
        content["pyqt_qtcanvas_sip_flags"] = qt_sip_flags

    if "qtext" in pyqt_modules:
        content["pyqt_qtext_sip_flags"] = qtext_sip_flags

        # These are internal.
        content["_pyqt_qscintilla_defines"] = qsci_define
        content["_pyqt_qscintilla_inc_dir"] = opt_qsciincdir
        content["_pyqt_qscintilla_lib_dir"] = opt_qscilibdir

    if "qtgl" in pyqt_modules:
        content["pyqt_qtgl_sip_flags"] = qt_sip_flags

    if "qtnetwork" in pyqt_modules:
        content["pyqt_qtnetwork_sip_flags"] = qt_sip_flags

    if "qtpe" in pyqt_modules:
        content["pyqt_qtpe_sip_flags"] = qtpe_sip_flags

    if "qtsql" in pyqt_modules:
        content["pyqt_qtsql_sip_flags"] = qt_sip_flags

    if "qttable" in pyqt_modules:
        content["pyqt_qttable_sip_flags"] = qt_sip_flags

    if "qtui" in pyqt_modules:
        content["pyqt_qtui_sip_flags"] = qt_sip_flags

    if "qtxml" in pyqt_modules:
        content["pyqt_qtxml_sip_flags"] = qt_sip_flags

    sipconfig.create_config_module(module, template, content)


def compile_qt_program(name, define=None, include_dir=None, lib_dir=None, lib=None, opengl=0, python=0):
    """Compile a simple Qt application.

    name is the name of the single source file.
    define is a name to add to the list of preprocessor defines.
    include_dir is the name of a directory to add to the list of include
    directories.
    lib_dir is the name of a directory to add to the list of library
    directories.
    lib is the name of a library to add to the list of libraries.
    opengl is set if the application uses OpenGL.
    python is set if the application #includes Python.h.

    Returns the name of the executable suitable for running or None if it
    wasn't created.
    """
    makefile = sipconfig.ProgramMakefile(sipcfg, console=1, qt=1, warnings=0, opengl=opengl, python=python)

    if define:
        makefile.extra_defines.append(define)

    if include_dir:
        makefile.extra_include_dirs.append(include_dir)

    if lib_dir:
        makefile.extra_lib_dirs.append(lib_dir)

    if lib:
        makefile.extra_libs.append(lib)

    exe, build = makefile.build_command(name)

    # Make sure the executable file doesn't exist.
    try:
        os.remove(exe)
    except OSError:
        pass

    if not opt_verbose and hasattr(os, "popen4"):
        fin, fout = os.popen4(build)

        # Read stdout and stderr until there is no more output.
        lout = fout.readline()
        while lout:
            lout = fout.readline()

        fin.close()
        fout.close()

        try:
            os.wait()
        except AttributeError:
            pass
    else:
        os.system(build)

    if not os.access(exe, os.X_OK):
        return None

    if sys.platform != "win32":
        exe = "./" + exe

    return exe


def check_qscintilla():
    """See if QScintilla can be found and what its version is.
    """
    # Find the QScintilla header files.
    sciglobal = os.path.join(opt_qsciincdir, "qextscintillaglobal.h")

    if os.access(sciglobal, os.F_OK):
        # Get the QScintilla version number.
        global qsci_version

        qsci_version, sciversstr = sipconfig.read_version(sciglobal, "QScintilla", "QSCINTILLA_VERSION", "QSCINTILLA_VERSION_STR")

        if glob.glob(os.path.join(opt_qscilibdir, "*qscintilla*")):
            sipconfig.inform("QScintilla %s is being used." % sciversstr)

            # If we find a snapshot then set a negative version number as a
            # special case.
            if sciversstr[:8] == "snapshot":
                qsci_version = -1
        else:
            sipconfig.inform("The QScintilla library could not be found in %s and so the qtext module will not be built. If QScintilla is installed then use the -o argument to explicitly specify the correct directory." % opt_qscilibdir)
    else:
        sipconfig.inform("qextscintillaglobal.h could not be found in %s and so the qtext module will not be built. If QScintilla is installed then use the -n argument to explicitly specify the correct directory." % opt_qsciincdir)


def check_module(mname, incfile, ctor, define=None, include_dir=None, lib_dir=None, lib=None, opengl=0):
    """See if a module can be built and, if so, add it to the global list of
    modules.

    mname is the name of the module.
    incfile is the name of the include file needed for the test.
    ctor is the C++ constructor of the class being used for the test.
    define is a name to add to the list of preprocessor defines.
    include_dir is the name of a directory to add to the list of include
    directories.
    lib_dir is the name of a directory to add to the list of library
    directories.
    lib is the name of a library to add to the list of libraries.
    opengl is set if the application uses OpenGL.
    """
    # Check the module's main .sip file exists.
    if os.access(os.path.join("sip", mname, mname + "mod.sip"), os.F_OK):
        sipconfig.inform("Checking to see if the %s module should be built..." % mname)

        if check_class(incfile, ctor, define, include_dir, lib_dir, lib, opengl):
            pyqt_modules.append(mname)


def check_class(incfile, ctor, define=None, include_dir=None, lib_dir=None, lib=None, opengl=0):
    """Return non-zero if a class is available.

    incfile is the name of the include file needed for the test.
    ctor is the C++ constructor of the class.
    define is a name to add to the list of preprocessor defines.
    include_dir is the name of a directory to add to the list of include
    directories.
    lib_dir is the name of a directory to add to the list of library
    directories.
    lib is the name of a library to add to the list of libraries.
    opengl is set if the application uses OpenGL.
    """
    cfgtest = "cfgtest.cpp"

    f = open(cfgtest, "w")

    f.write("""#include <%s>

int main(int argc, char **argv)
{
    new %s;
}
""" % (incfile, ctor))

    f.close()

    return compile_qt_program(cfgtest, define, include_dir, lib_dir, lib, opengl)


def check_plugin(cname, incfile):
    """Return non-zero if a class that might be a plugin is in the main Qt
    library.

    cname is the name of the class.
    incfile is the name of the include file needed for the test.
    """
    sipconfig.inform("Checking to see if the %s class is built in..." % cname)

    return check_class(incfile, cname + "()")


def create_features_file(name):
    """Create the features file.

    name is the name of the features file in the current directory.
    """
    # The features that a given Qt configuration may or may not support.  Note
    # that STYLE_WINDOWSXP and ASSISTANTCLIENT require special handling.
    flist = ["ACTION", "CLIPBOARD", "CODECS", "COLORDIALOG", "DATASTREAM",
             "DIAL", "DNS", "DOM", "DRAGANDDROP", "ICONVIEW", "IMAGE_TEXT",
             "INPUTDIALOG", "FILEDIALOG", "FONTDATABASE", "FONTDIALOG",
             "MESSAGEBOX", "MIMECLIPBOARD",
             "NETWORKPROTOCOL", "NETWORKPROTOCOL_FTP", "NETWORKPROTOCOL_HTTP",
             "PICTURE", "PRINTDIALOG", "PRINTER", "PROGRESSDIALOG",
             "PROPERTIES",
             "SEMIMODAL", "SIZEGRIP", "SOUND", "SPLITTER", "STYLE_CDE",
             "STYLE_INTERLACE", "STYLE_MOTIF", "STYLE_MOTIFPLUS",
             "STYLE_PLATINUM", "STYLE_SGI", "STYLE_WINDOWS",
             "TABDIALOG", "TABLE", "TABLEVIEW", "TRANSFORMATIONS",
             "TRANSLATION", "WIZARD", "WORKSPACE"]

    # Generate the program which will generate the features file.
    f = open("mkfeatures.cpp", "w")

    f.write(
"""#include <Python.h>
#include <stdio.h>
#include <qglobal.h>
#include <qapplication.h>

int main(int argc,char **argv)
{
    FILE *fp;
    QApplication app(argc,argv,0);

    if ((fp = fopen("%s","w")) == NULL)
    {
        printf("Unable to create '%s'\\n");
        return 1;
    }

#if !defined(WITH_THREAD) || !defined(QT_THREAD_SUPPORT)
    fprintf(fp,"-x Qt_THREAD_SUPPORT\\n");
#endif

#if !defined(Q_WS_WIN) || QT_VERSION < 0x030000 || defined(QT_NO_STYLE_WINDOWSXP)
    fprintf(fp,"-x Qt_STYLE_WINDOWSXP\\n");
#endif
""" % (name, name))

    for feat in flist:
        f.write(
"""
#if defined(QT_NO_%s)
    fprintf(fp,"-x Qt_%s\\n");
#endif
""" % (feat, feat))

    # Disable QAssistantClient for the Professional Edition.
    if "QAssistantClient" in disabled_classes:
        f.write(
"""
    fprintf(fp,"-x Qt_ASSISTANTCLIENT\\n");
""")

    f.write(
"""
    fclose(fp);

    return 0;
}
""")

    f.close()

    # Build the program.
    exe = compile_qt_program("mkfeatures.cpp", include_dir=sipcfg.py_inc_dir, python=1)
    if not exe:
        sipconfig.error("Unable to build mkfeatures utility.")

    os.system(exe)

    # Check the file was created.
    if not os.access(name, os.F_OK):
        sipconfig.error("There was an error creating the features file.")

    # Check what features have been implemented as plugins and disable them.
    plugins = [("STYLE_CDE",       "qcdestyle.h",       "QCDEStyle"),
               ("STYLE_INTERLACE", "qinterlacestyle.h", "QInterlaceStyle"),
               ("STYLE_MOTIF",     "qmotifstyle.h",     "QMotifStyle"),
               ("STYLE_MOTIFPLUS", "qmotifplusstyle.h", "QMotifPlusStyle"),
               ("STYLE_PLATINUM",  "qplatinumstyle.h",  "QPlatinumStyle"),
               ("STYLE_SGI",       "qsgistyle.h",       "QSGIStyle"),
               ("STYLE_WINDOWSXP", "qwindowsxpstyle.h", "QWindowsXPStyle"),
               ("STYLE_WINDOWS",   "qwindowsstyle.h",   "QWindowsStyle")]

    f = open(name, "a")

    for (feat, incfile, cname) in plugins:
        if not check_plugin(cname, incfile):
            f.write("-x Qt_%s\n" % feat)
            disabled_classes.append(cname)

    f.close()


def get_feature_flags():
    """Return the list of SIP flags that exclude unsupported Qt features.
    """
    featfile = "features"

    # Create the features file if it doesn't exist.
    if os.access(featfile,os.F_OK):
        sipconfig.inform("Using existing features file.")
    else:
        sipconfig.inform("Creating features file...")
        create_features_file(featfile)

    # Parse the features file.
    ff = open(featfile, "r")

    flags = []

    line = ff.readline()
    while line:
        flags.extend(string.split(line))
        line = ff.readline()

    return flags


def set_sip_flags():
    """Set the SIP platform, version and feature flags.
    """
    # Handle the features.
    qt_sip_flags.extend(get_feature_flags())

    # Handle the platform tag.
    if opt_qtpetag:
        plattag = "WS_QWS"
    elif sys.platform == "win32":
        plattag = "WS_WIN"
    elif sys.platform == "darwin":
        plattag = "WS_MACX"
    else:
        plattag = "WS_X11"

    qt_sip_flags.append("-t")
    qt_sip_flags.append(plattag)

    # Handle the Qt version tag.
    qttags = {
        0x020000: "Qt_1_43",
        0x020100: "Qt_2_00",
        0x020200: "Qt_2_1_0",
        0x020300: "Qt_2_2_0",
        0x020301: "Qt_2_3_0",
        0x030000: "Qt_2_3_1",
        0x030001: "Qt_3_0_0",
        0x030002: "Qt_3_0_1",
        0x030004: "Qt_3_0_2",
        0x030005: "Qt_3_0_4",
        0x030006: "Qt_3_0_5",
        0x030100: "Qt_3_0_6",
        0x030101: "Qt_3_1_0",
        0x030102: "Qt_3_1_1",
        0x030200: "Qt_3_1_2",
        0x030300: "Qt_3_2_0",
        0x040000: "Qt_3_3_0"
    }

    qt_sip_flags.append("-t")
    qt_sip_flags.append(sipconfig.version_to_sip_tag(sipcfg.qt_version, qttags, "Qt"))

    # The flags so far are common.
    for f in qt_sip_flags:
        qtext_sip_flags.append(f)
        qtpe_sip_flags.append(f)

    # Handle the QScintilla version tag.
    if qsci_version:
        qscitags = {
            0x010100: "QScintilla_1_0",
            0x010200: "QScintilla_1_1",
            0x010300: "QScintilla_1_2",
            0x010400: "QScintilla_1_3",
            0x020000: "QScintilla_1_4"
        }

        qtext_sip_flags.append("-t")
        qtext_sip_flags.append(sipconfig.version_to_sip_tag(qsci_version, qscitags, "QScintilla"))

    # Handle the Qtopia tag.
    if opt_qtpetag:
        qtpe_sip_flags.append("-t")
        qtpe_sip_flags.append(opt_qtpetag)


def generate_code(mname, imports=None, extra_cflags=None, extra_cxxflags=None, extra_define=None, extra_include_dir=None, extra_lflags=None, extra_lib_dir=None, extra_lib=None, opengl=0, sip_flags=None):
    """Generate the code for a module.

    mname is the name of the module.
    imports is the list of PyQt modules that this one %Imports.
    extra_cflags is a string containing additional C compiler flags.
    extra_cxxflags is a string containing additional C++ compiler flags.
    extra_define is a name to add to the list of preprocessor defines.
    extra_include_dir is the name of a directory to add to the list of include
    directories.
    extra_lflags is a string containing additional linker flags.
    extra_lib_dir is the name of a directory to add to the list of library
    directories.
    extra_lib is the name of an extra library to add to the list of libraries.
    opengl is set if the module needs OpenGL support.
    sip_flags is the list of sip flags to use instead of the defaults.
    """
    sipconfig.inform("Generating the C++ source for the %s module..." % mname)

    try:
        shutil.rmtree(mname)
    except:
        pass

    try:
        os.mkdir(mname)
    except:
        sipconfig.error("Unable to create the %s directory." % mname)

    # Build the SIP command line.
    argv = [sipcfg.sip_bin]

    if sip_flags is None:
        sip_flags = qt_sip_flags

    argv.extend(sip_flags)

    if opt_concat:
        argv.append("-j")
        argv.append(str(opt_split))

    if opt_tracing:
        argv.append("-r")

    if opt_releasegil:
        argv.append("-g")

    argv.append("-c")
    argv.append(mname)

    buildfile = os.path.join(mname, mname + ".sbf")
    argv.append("-b")
    argv.append(buildfile)

    argv.append("-I")
    argv.append("sip")

    # SIP assumes POSIX style path separators.
    argv.append(string.join(["sip", mname, mname + "mod.sip"], "/"))

    os.system(string.join(argv))

    # Check the result.
    if not os.access(buildfile, os.F_OK):
        sipconfig.error("Unable to create the C++ code.")

    # Compile the Python stub.
    if sipcfg.sip_version < 0x040000:
        sipconfig.inform("Compiling %s.py..." % mname)
        py_compile.compile(os.path.join(mname, mname + ".py"), os.path.join(mname, mname + ".pyc"))

    # Generate the Makefile.
    sipconfig.inform("Creating the Makefile for the %s module..." % mname)

    installs = []

    if sipcfg.sip_version >= 0x040000:
        warnings = 1
    else:
        warnings = 0
        installs.append([[mname + ".py", mname + ".pyc"], opt_pyqtmoddir])

    sipfiles = []

    for s in glob.glob("sip/" + mname + "/*.sip"):
        sipfiles.append(os.path.join("..", "sip", mname, os.path.basename(s)))

    installs.append([sipfiles, os.path.join(opt_pyqtsipdir, mname)])

    makefile = sipconfig.SIPModuleMakefile(
        configuration=sipcfg,
        build_file=mname + ".sbf",
        dir=mname,
        install_dir=opt_pyqtmoddir,
        installs=installs,
        qt=1,
        opengl=opengl,
        warnings=warnings,
        static=opt_static,
        debug=opt_debug
    )

    if extra_cflags:
        makefile.extra_cflags.append(extra_cflags)

    if extra_cxxflags:
        makefile.extra_cxxflags.append(extra_cxxflags)

    if extra_define:
        makefile.extra_defines.append(extra_define)

    if extra_include_dir:
        makefile.extra_include_dirs.append(extra_include_dir)

    if extra_lflags:
        makefile.extra_lflags.append(extra_lflags)

    if extra_lib_dir:
        makefile.extra_lib_dirs.append(extra_lib_dir)

    if extra_lib:
        makefile.extra_libs.append(extra_lib)

    if sipcfg.sip_version < 0x040000 and imports:
        # Inter-module links.
        for im in imports:
            makefile.extra_lib_dirs.insert(0, os.path.join("..", im))
            makefile.extra_libs.insert(0, makefile.module_as_lib(im))

    makefile.generate()


def check_license():
    """Handle the validation of the PyQt license.
    """
    try:
        import license
        ltype = license.LicenseType
        lname = license.LicenseName

        try:
            lfile = license.LicenseFile
        except AttributeError:
            lfile = None
    except ImportError:
        ltype = None

    if ltype is None:
        ltype = "GPL"
        lname = "GNU General Public License"
        lfile = None

    sipconfig.inform("This is the %s version of PyQt %s (licensed under the %s) for Python %s on %s." % (ltype, pyqt_version_str, lname, string.split(sys.version)[0], sys.platform))

    # Common checks.
    if ltype == "GPL" and sys.platform == "win32":
        error("You cannot use the GPL version of PyQt under Windows.")

    try:
        qted = sipcfg.qt_edition
    except AttributeError:
        qted = None

    if qted:
        if (qted == "free" and ltype != "GPL") or (qted != "free" and ltype == "GPL"):
            sipconfig.error("This version of PyQt and the %s edition of Qt have incompatible licenses." % qted)

    # Confirm the license.
    print
    print "Type 'L' to view the license."
    print "Type 'yes' to accept the terms of the license."
    print "Type 'no' to decline the terms of the license."
    print

    while 1:
        try:
            resp = raw_input("Do you accept the terms of the license? ")
        except:
            resp = ""

        resp = string.lower(string.strip(resp))

        if resp == "yes":
            break

        if resp == "no":
            sys.exit(0)

        if resp == "l":
            os.system("more LICENSE")

    # If there should be a license file then check it is where it should be.
    if lfile:
        if os.access(os.path.join("sip", lfile), os.F_OK):
            sipconfig.inform("Found the license file %s." % lfile)
        else:
            sipconfig.error("Please copy the license file %s to the sip directory." % lfile)


def create_makefiles():
    """Create the additional Makefiles.
    """
    subdirs = pyqt_modules[:]

    if sipcfg.qt_version >= 0x030000:
        # The Professional Edition needs special handling.
        prof = (sipcfg.qt_edition == "professional")

        sipconfig.inform("Creating pyuic Makefile...")

        if prof or "qtxml" not in pyqt_modules:
            buildfile= "pyuic-prof.sbf"

            for xml in ("qdom.cpp", "qxml.cpp"):
                shutil.copyfile(sipcfg.qt_dir + "/src/xml/" + xml, "pyuic3/" + xml)
        else:
            buildfile= "pyuic.sbf"

        makefile = sipconfig.ProgramMakefile(
            configuration=sipcfg,
            build_file=buildfile,
            dir="pyuic3",
            install_dir=opt_pyqtbindir,
            console=1,
            qt=1,
            warnings=1
        )

        makefile.extra_defines.append("UIC")
        makefile.extra_defines.append("QT_INTERNAL_XML")

        if prof or "qtxml" not in pyqt_modules:
            makefile.extra_defines.append("QT_MODULE_XML")

        if sipcfg.qt_version < 0x030100:
            makefile.extra_include_dirs.append(sipcfg.qt_dir + "/src/3rdparty/zlib")

        makefile.generate()
        subdirs.append("pyuic3")

        sipconfig.inform("Creating pylupdate Makefile...")

        if prof or "qtxml" not in pyqt_modules:
            buildfile= "pylupdate-prof.sbf"

            shutil.copyfile(sipcfg.qt_dir + "/src/xml/qxml.cpp", "pylupdate3/qxml.cpp")
        else:
            buildfile= "pylupdate.sbf"

        makefile = sipconfig.ProgramMakefile(
            configuration=sipcfg,
            build_file=buildfile,
            dir="pylupdate3",
            install_dir=opt_pyqtbindir,
            console=1,
            qt=1,
            warnings=1
        )

        makefile.extra_defines.append("QT_INTERNAL_XML")

        if prof or "qtxml" not in pyqt_modules:
            makefile.extra_defines.append("QT_MODULE_XML")

        makefile.generate()
        subdirs.append("pylupdate3")
    elif sipcfg.qt_version >= 0x020000:
        sipconfig.inform("Creating pyuic Makefile...")

        makefile = sipconfig.ProgramMakefile(
            configuration=sipcfg,
            build_file="pyuic.sbf",
            dir="pyuic2",
            install_dir=opt_pyqtbindir,
            console=1,
            qt=1,
            warnings=1
        )

        makefile.extra_defines.append("UIC")
        makefile.extra_include_dirs.append(sipcfg.qt_dir + "/src/3rdparty/zlib")

        makefile.generate()
        subdirs.append("pyuic2")

    sipconfig.inform("Creating top level Makefile...")

    sipconfig.ParentMakefile(
        configuration=sipcfg,
        subdirs=subdirs,
        installs=("pyqtconfig.py", opt_pyqtmoddir)
    ).generate()


def main(argv):
    """Create the configuration module module.

    argv is the list of command line arguments.
    """
    try:
        optlist, args = getopt.getopt(argv[1:], "ha:b:cd:gj:kn:o:rsuv:w")
    except getopt.GetoptError:
        usage()

    global opt_pyqtbindir, opt_pyqtmoddir, opt_pyqtsipdir
    global opt_qtpetag, opt_static, opt_debug, opt_concat, opt_releasegil
    global opt_split, opt_tracing, opt_verbose
    global opt_qsciincdir, opt_qscilibdir, qsci_define

    for opt, arg in optlist:
        if opt == "-h":
            usage(0)
        elif opt == "-a":
            opt_qtpetag = arg
        elif opt == "-b":
            opt_pyqtbindir = arg
        elif opt == "-c":
            opt_concat = 1
        elif opt == "-d":
            opt_pyqtmoddir = arg
        elif opt == "-g":
            opt_releasegil = 1
        elif opt == "-j":
            try:
                opt_split = int(arg)
            except:
                usage()
        elif opt == "-k":
            opt_static = 1
        elif opt == "-n":
            opt_qsciincdir = arg
        elif opt == "-o":
            opt_qscilibdir = arg
        elif opt == "-r":
            opt_tracing = 1
        elif opt == "-s":
            qsci_define = ""
        elif opt == "-u":
            opt_debug = 1
        elif opt == "-v":
            opt_pyqtsipdir = arg
        elif opt == "-w":
            opt_verbose = 1

    if args:
        usage()

    check_license()

    sipconfig.inform("SIP %s is being used." % sipcfg.sip_version_str)

    # Check SIP is new enough.
    if sipcfg.sip_version_str[:8] != "snapshot":
        minv = None

        if sipcfg.sip_version >= 0x040000:
            if sipcfg.sip_version < sip_min_v4_version:
                minv = sip_min_v4_version
        else:
            if sipcfg.sip_version < sip_min_v3_version:
                minv = sip_min_v3_version

        if minv:
            sipcfg.error("This version of PyQt requires SIP v%s or later" % sipcfg.version_to_string(minv))

    # Check for QScintilla.
    check_qscintilla()

    # Check which modules to build.
    check_module("qtcanvas", "qcanvas.h", "QCanvas()")
    check_module("qtnetwork", "qsocket.h", "QSocket()")
    check_module("qttable", "qtable.h", "QTable()")
    check_module("qtxml", "qdom.h", "QDomImplementation()")
    check_module("qtgl", "qgl.h", "QGLWidget()", opengl=1)

    if sipcfg.qt_version >= 0x030000:
        check_module("qtui", "qwidgetfactory.h", "QWidgetFactory()", lib="qui")

        if sipcfg.qt_edition in ("enterprise", "free"):
            check_module("qtsql", "qsql.h", "QSql()")

            if sys.platform == "win32" and sipcfg.sip_version >= 0x040200:
                check_module("qtaxcontainer", "qaxobject.h", "QAxObject()", lib="qaxcontainer")

    if qsci_version:
        check_module("qtext", "qextscintillabase.h", "QextScintillaBase()", define=qsci_define, include_dir=opt_qsciincdir, lib_dir=opt_qscilibdir, lib="qscintilla")

    if opt_qtpetag:
        pyqt_modules.append("qtpe")

    qtmod_lib = ""

    # For MIPS we can't link against libqassistantclient.a right now, as
    # it's not being build with -Wa,-xgot.
    if os.environ.get('DEB_BUILD_ARCH') in ['mips', 'mipsel']:
        disabled_classes.append("QAssistantClient")
    elif sipcfg.qt_version >= 0x030100:
        sipconfig.inform("Checking to see if the QAssistantClient class is available...")

        if check_class("qassistantclient.h", "QAssistantClient(\"foo\")", lib="qassistantclient"):
            qtmod_lib = "qassistantclient"
        else:
            disabled_classes.append("QAssistantClient")

    # Set the SIP platform, version and feature flags.
    set_sip_flags()

    # Tell the user what's been found.
    inform_user()

    # For SIP v3 on AIX we need an extra linker flag for the qt module as the
    # table of contents (TOC) is greater than 64KB.
    if sipcfg.sip_version < 0x040000 and string.find(sys.platform, "aix") == 0:
        qtmod_lflags = "-Wl,-bbigtoc"
    else:
        qtmod_lflags = ""

    # For MIPS we need an extra compiler flag for the qt module as we
    # exceed the GOT table size
    if os.environ.get('DEB_BUILD_ARCH') in ['mips', 'mipsel']:
        debian_cflags = "-Wa,-xgot"
    else:
        debian_cflags = None

    # Generate the code.
    generate_code("qt", extra_lflags=qtmod_lflags, extra_lib=qtmod_lib, extra_cxxflags=debian_cflags, extra_cflags=debian_cflags)

    if "qtext" in pyqt_modules:
        generate_code("qtext", imports=["qt"], extra_define=qsci_define, extra_include_dir=opt_qsciincdir, extra_lib_dir=opt_qscilibdir, extra_lib="qscintilla", sip_flags=qtext_sip_flags)

    if "qtgl" in pyqt_modules:
        generate_code("qtgl", imports=["qt"], opengl=1)

    if "qtpe" in pyqt_modules:
        generate_code("qtpe", imports=["qt"], extra_lib="qpe", sip_flags=qtpe_sip_flags)

    if "qtsql" in pyqt_modules:
        generate_code("qtsql", imports=["qt", "qttable"])

    if "qtui" in pyqt_modules:
        generate_code("qtui", imports=["qt"], extra_lib="qui")

    if "qtaxcontainer" in pyqt_modules:
        generate_code("qtaxcontainer", imports=["qt"], extra_lib="qaxcontainer")

    # The rest don't need special handling.
    for m in ("qtcanvas", "qtnetwork", "qttable", "qtxml"):
        if m in pyqt_modules:
            generate_code(m, imports=["qt"])

    # Create the additional Makefiles.
    create_makefiles()

    # Install the configuration module.
    create_config("pyqtconfig.py", "pyqtconfig.py.in")


###############################################################################
# The script starts here.
###############################################################################

if __name__ == "__main__":
    try:
        main(sys.argv)
    except SystemExit:
        raise
    except:
        print \
"""An internal error occured.  Please report all the output from the program,
including the following traceback, to support@riverbankcomputing.co.uk.
"""
        raise
