# -*- coding: utf-8; mode: tcl; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:fenc=utf-8:ft=tcl:et:sw=4:ts=4:sts=4:nomodified

PortSystem          1.0

set basename        qt4-mac
name                ${basename}-devel
version             4.8.7
revision            8

use_xcode           yes

# set qtportlist {qt4-mac qt4-mac-devel}
set qtportlist      {qt4-mac-devel}

if {${subport} eq "${basename}-devel"} {
    conflicts-append \
                    ${basename}
}

# use the qt4 group; set 'building_qt4' so that the portgroup
# does not include certain parts
set building_qt4    1

PortGroup           qt4 1.0
PortGroup           xcodeversion 1.0
PortGroup           openssl 1.0

set branch          [qt_branch]

categories          aqua
platforms           macosx
maintainers         gmail.com:rjvbertin michaelld openmaintainer
license             {LGPL-2.1 GPL-3}

homepage            http://qt.io
description         Qt Tool Kit
long_description    {*}${description}: A cross-platform framework \
                    (headers, data, and libraries) for writing \
                    cross-platform GUI-based applications. \
                    Installs to ${qt_dir}

distname            qt-everywhere-opensource-src-${version}

master_sites        https://download.qt.io/new_archive/qt/${branch}/${version}/

checksums           rmd160  afb5e5a99388e6429faca59cb5000054feffd166 \
                    sha256  e2882295097e47fe089f8ac741a95fef47e0a73a3f3cdf21b56990638f626ea0 \
                    size    241075567

# Optional support for HFS-compression of the source and build dirs
# PortGroup           compress_workdir 1.0

minimum_xcodeversions   {8 2.5}

openssl.configure
openssl.branch      1.1

# FIXME: for some reason libmng may not get activated when `port activate qt4-mac-devel` is used
# as opposed to `sudo port install qt4-mac-devel`. This results in a bogus `Found 1 broken port`.

depends_lib-append  port:dbus \
                    path:include/turbojpeg.h:libjpeg-turbo \
                    port:libmng \
                    port:libpng \
                    port:tiff \
                    port:zlib

# Find a way to specify the OS MINOR version. For OSX 10.X, this
# value will be X. The type is this variable is integer, so we can
# use "==" and so forth for comparison.

global MINOR
set MINOR ""

# Hopefully the MACOSX_DEPLOYMENT_TARGET exists and is set by now.
# If not, last resort (which is not desirable) is to use the os.version.

if {${macosx_deployment_target} ne ""} {
    set MINOR [lindex [split ${macosx_deployment_target} "."] 1]
} else {
    set MINOR [expr [lindex [split ${os.version} "."] 0] - 4]
}

if {${subport} eq ${name} || ${subport} eq "${basename}"} {

    PortGroup           select 1.0
    select.group        qt
    select.file         ${filespath}/qt4

    ###############################################
    # Patches are used to both fix compiling on various OS versions,
    # and to enhance the functionality of QMake and its build files.
    # Some of these patches are 2-stage: use a file here, and the replace
    # a @VARIABLE@ in post-patch. There are LOTS of patches, because Qt
    # is a large, complicated system.

    # (0) Fix the testing script to properly handle both +universal as
    # well as the native arch for both CXX and CC compiling; also make
    # sure it does not create a Mac app bundle.

    patchfiles-append   patch-config.tests_unix_compile.test.diff

    # (1) Test for Precompiled-headers support (a) requires a C++
    # compiler, but configure calls it, by default, with a C compiler;
    # thus, enable testing using the C compiler. (b) to work with ccache,
    # if used.

    patchfiles-append   patch-config.tests_unix_precomp.test.diff

    # (2) fix 'configure' script: (a) to allow easy replacement of arch
    # type(s). (b) to find the correct QMAKE CXX compiler by removing
    # possibilities that include the character "$". (c) to declare, use,
    # and set QT_INSTALL_FRAMEWORKS and QMAKE_FRAMEWORKDIR_QT, both here
    # and in the resulting .qmake.cache files. (d) to allow easy
    # replacement of MACOSX_DEPLOYMENT_TARGET: build for just the user's
    # current OS. (e) add hooks for C++11 testing.

    patchfiles-append   patch-configure.diff

    # (3) (a) Tweak various scripts to allow easy replacement of
    # MACOSX_DEPLOYMENT_TARGET: build for just the user's current OS.
    # (b) Assign initial OBJECTIVE_CXXFLAGS.

    patchfiles-append   patch-mkspecs_common_g++-macx.conf.diff

    # (4) (a) Allow easy replacement of MACOSX_DEPLOYMENT_TARGET: build
    # for just the user's current OS; (b) allow QMake to use 'ccache' via,
    # e.g., "qmake && make CCACHE=ccache".

    patchfiles-append   patch-mkspecs_common_mac.conf.diff

    # (5) Place the -I path for local moc-created headers -before-
    # all other -I paths.

    patchfiles-append   patch-mkspecs_features_moc.prf.diff

    # (6) Remove Qt's LIBDIR and INCDIR from various QMake internal
    # variables, since they are already included in the user-supplied
    # LIBS and INCLUDEPATH.

    patchfiles-append   patch-mkspecs_features_qt.prf.diff

    # (7) (a) Change placement of Qt's LIBDIR and INCDIR, to always be
    # after those supplied by the user's QMake (.pro) files.  By the time
    # QMake gets to the patched function, it is creating the Makefile
    # parts to find Qt's headers and libraries, so moving these paths to
    # this location should always work. (b) If the library is QtWebKit,
    # and the build is library (no-framework), universal, and debug, then
    # the linkage is just -lQtWebKit, not -lQtWebKit_debug because the
    # debug library for 32-bit system cannot be created (too large).

    patchfiles-append   patch-mkspecs_features_qt_functions.prf.diff

    # (8) (a) Change "gcc" and "g++" to @'s for replacement in
    # post-patch; (b) add hooks for C++11.

    patchfiles-append   patch-mkspecs_common_g++-base.conf.diff

    # (9) Add default QMake variables for Objective C++.

    patchfiles-append   patch-mkspecs_objective_cxx.diff

    # (10) Add "absolute_library_soname" to the default CONFIG variables,
    # so that when a DYLIB is created, if "target.path" is set for it then
    # that path is prepended to its "install_name".

    patchfiles-append   patch-mkspecs_macx-g++_qmake.conf.diff

    # (11) Add QT_INSTALL_FRAMEWORKS and related variables to QMake, to
    # provide a default variable for the location of QMake installed
    # frameworks.

    patchfiles-append \
        patch-qmake_option.h.diff \
        patch-qmake_property.cpp.diff \
        patch-src_corelib_global_qlibraryinfo.cpp.diff \
        patch-src_corelib_global_qlibraryinfo.h.diff

    # (12) In QMake, disable default MKSPECS and FEATURES path
    # concatinations if the shell environment variable QMAKE_NO_DEFAULTS
    # is set (to anything); we use this variable in this portfile to make
    # sure only internal paths (to the build) are searched by QMake.

    patchfiles-append   patch-qmake_project.cpp.diff

    # (13a) In QMake: (a) enable correct "-framework foo,bar" parsing as
    # specified by Apple's LD; (b) disable "/Library/Frameworks" as
    # a default search path; use "PREFIX/Library/Frameworks" and replace
    # PREFIX in post-patch. Also set "PREFIX/lib" as a default library
    # search path.

    patchfiles-append   patch-qmake_generators_unix_unixmake.cpp.framework.diff

    # (13b) In QMake: fix issue for when LFLAGS and env LDFLAGS contain
    # multiple "-arch FOO" duplicate flags, which would result in output
    # such as "-arch x86_64 -arch -Xarch_x86_64 ...".

    patchfiles-append   patch-qmake_generators_unix_unixmake.cpp.fix_arch.diff

    # (14) Allow easy replacement of MACOSX_DEPLOYMENT_TARGET: build for
    # just the user's current OS.

    patchfiles-append \
        patch-qmake_qmake.pri.diff \
        patch-src_tools_bootstrap_bootstrap.pro.diff

    # (15) Fix use of CARBON, found on PPC64; does not hurt others.

    patchfiles-append \
        patch-src_3rdparty_webkit_Source_WebCore_plugins_PluginView.h.diff \
        patch-src_3rdparty_webkit_Source_WebCore_plugins_mac_PluginViewMac.mm.diff

    # (16) Fix the corewlan qmake file to use non-standard Developer SDK
    # location under 10.6 and newer, e.g., for some developers doing both
    # iOS and OSX. This patch does not change behavior for 10.4 or 10.5.
    # Also include fix to use the correct SDK.

    # patchfiles-append   patch-src_plugins_bearer_corewlan_corewlan.pro.diff

    # (17) Use the "target.path" for libdir for core libraries instead of
    # the standard QT_INSTALL_LIBS; allows us to set for library or
    # framework elsewhere and have the install still work here.

    patchfiles-append   patch-src_qbase.pri.diff

    # (18) (a) Disable explicit disabling of framework or static install;
    # i.e., install as a framework if that mode is selected, and as
    # library otherwise. (b) If installing as framework, use the new
    # QT_INSTALL_FRAMEWORKS directory; otherwise, use the old
    # QT_INSTALL_LIBS; (c) Get PKGCONFIG dependencies correct, hopefully;
    # (d) create and install .pc, .la, and .prl library description files,
    # including basic path replacement into DESTDIR; we couple this with
    # a post-patch to get the correct install location.

    patchfiles-append \
        patch-src_qt_install.pri.diff \
        patch-tools_assistant_lib_fulltextsearch_fulltextsearch.pro.diff \
        patch-tools_assistant_lib_lib.pro.diff \
        patch-tools_designer_src_components_lib_lib.pro.diff \
        patch-tools_designer_src_lib_lib.pro.diff \
        patch-tools_designer_src_uitools_uitools.pro.diff \
        patch-mkspecs_features_uitools.prf.diff

    # (19) Fix 'macdeployqt' to look for the correct plugins location by
    # default. This is paired with a "reinplace" in post-patch.

    patchfiles-append \
        patch-tools_macdeployqt_macdeployqt_main.cpp.diff

    # (20) Fix the Mac timer's use of "mach_timebase_info".

    patchfiles-append \
        patch-src_corelib_tools_qelapsedtimer-mac.cpp.diff

    # (21) Under 10.8 and 10.9: Patch to fix corelib linking.

    platform darwin {
        if {${MINOR} >= 8} {
            patchfiles-append patch-src_corelib_corelib.pro.diff
        }
    }

    # (22) Fix Framework directory in MacDeployQt tool.

    patchfiles-append \
        patch-tools_macdeployqt_shared_shared.cpp.diff

    # (23) Fix qcursor_mac; already committed upstream; see also:
    # https://trac.macports.org/ticket/48516
    # http://code.qt.io/cgit/qt/qtbase.git/commit/src/plugins/platforms/cocoa/qcocoacursor.mm?id=02ea0235216beef390e9868ff770c7a54d70db83
    # https://developer.apple.com/library/prerelease/mac/documentation/Carbon/Reference/QuartzEventServicesRef/#//apple_ref/c/func/CGEventCreateMouseEvent

    patchfiles-append \
        patch-src_gui_kernel_qcursor_mac.mm.diff

    # (24) Avoid leaving zombies when starting an inexisting executable through QProcess.
    patchfiles-append \
        qprocess-nozombies.patch

    # (25) Fix build on Leopard; see also:
    # https://trac.macports.org/ticket/43746

    patchfiles-append \
        patch-src_gui_dialogs_qfiledialog_mac.mm.diff

    # (26) Don't build with exceptions, which gives a completely ABI-compatible build.
    patchfiles-append       disable-exceptions.patch

    # (27) Prevent mouse event for deleted object
    patchfiles-append       qt4-prevent-mousevent-for-deleted-object.diff

    # (28) Build the qtconfig tool
    patchfiles-append       patch-tools-build_qtconfig.diff

    # (29) Correct issues with the handling of font weight and styles.
    patchfiles-append       patch-improve-fontweight-support2.diff \
                            patch-fontpanel.diff

    # Experimental and flaky support for colour fonts and UTF32 emojis.
    if {${os.platform} eq "darwin" && [variant_isset emojis]} {
        patchfiles-append   patch-font-emojis.diff
    }

    # (30) Prevent text zooming when pressing the Command key during inertial/passive scrolling (coasting)
    patchfiles-append       patch-avoid-unwanted-fontzooming.diff
    # (31) Mac menu items shouldn't have icons according to the HIG (and I agree).
    patchfiles-append       patch-no-icons-in-menus.diff
    # (32) Show qFatal() messages in a pop-up in addition to on the terminal, and give
    # the user the choice to exit rather than abort.
    patchfiles-append       patch-qFatal-no-abort.diff

    platform darwin {
        if {${MINOR} >= 11} {
            # (33) remove ColorSync usage from qpaintengine.
            # This patch allows for building using the 10.11 SDK, and is also
            # backward compatible with prior OS versions since it just removes API
            # usage but does not otherwise add any. This patch does roughly
            # the same thing as that from Qt5 commit b06304e16:
            # http://code.qt.io/cgit/qt/qtbase.git/commit/?id=b06304e164ba47351fa292662c1e6383c081b5ca

            patchfiles-append       patch-src_gui_painting_qpaintengine_mac.diff
        }
    }

    # Upstream patch: Better handling of invalid font tables
    # (patch (27) in mainstream port:qt4-mac).
    patchfiles-append       patch-invalid-fnt-table-handling.diff

    # (u28) Fix pointer comparison with 0
    # These error out on clang 4.0, whereas they didn't in 3.9 .
    # Addresses ticket https://trac.macports.org/ticket/54183
    patchfiles-append       patch-fix_pointer_comparison_to_0.diff

    # (u29) Backport of Qt5 patch to fix an issue with null bytes in
    # QSetting strings (QTBUG-56124).
    patchfiles-append       patch-qsettings-null.diff

    ## NB: I'm skipping (u30), fixes for 10.4 "Tiger"!

    # (u31) Patch to fix build on macOS High Sierra
    patchfiles-append       patch-qt4-versions-without-underscores.diff

    # (u32) Fix default thread stack size on Mac OS X (QTBUG-49607)
    # https://bugreports.qt.io/secure/attachment/52520/patch-qthread-stacksize.diff
    # Note that Qt 5.10 and later implement QThreadPool:stackSize to set
    # the stack size (QTBUG-2568).
    patchfiles-append       patch-qthread-stacksize.diff

    # (u33) Add possibility to set a custom global thread pool.
    patchfiles-append       patch-qt-custom-threadpool.diff

    # Work around issue (probably) introduced by a newer harfbuzz version.
    patchfiles-append       patch-harfbuzz-support.diff

    # (u34) Various from NiXos
    # see also < https://trac.macports.org/ticket/55932 >
    # and < https://github.com/NixOS/nixpkgs/tree/master/pkgs/development/libraries/qt-4.x/4.8 >
    # (a) Allow use of libressl as well as openssl.
    patchfiles-append patch-allow_libressl.diff

    # (b) Allow parallel qmake building.
    # Normally qmake is built using a single thread/job.
    patchfiles-append patch-parallelize_qmake_build.diff

    # (c) Fix unix makefile generation to augment this specific variable
    # ('ret'), not overwrite it – this matches the other uses of
    # the specific variable in that area, especially that in the 'if' statement.
    patchfiles-append patch-qmake_generators_unix_unixmake.cpp.diff

    # (d) Fix to not call qsettings before constructing a qapplication,
    # because it causes a dead-lock.
    patchfiles-append patch-src_corelib_io_qsettings.cpp.diff

    # (e) Fix to properly use QFixed as a type rather than a constructor
    # (I think). Without this fix, the build errors out on Clang 5.
    patchfiles-append patch-src_gui_text_qfontengine_coretext.mm.diff

    # Control the default graphicsssystem via qtconfig.
    patchfiles-append patch-graphicssystem-via-qtconfig.diff

    # Support openssl 1.0 or openssl 1.1.
    patchfiles-append patch-support-openssl11.diff

## NB: for a while I ran the following change to QSslSocketBackendPrivate::initSslContext() ,
## no recollection why but it caused lower-grade secure connections to be used:
# @@ -267,15 +273,19 @@ init_context:
#  #endif
#          break;
#      case QSsl::SslV3:
# +#ifndef OPENSSL_NO_SSL3
#          ctx = q_SSL_CTX_new(client ? q_SSLv3_client_method() : q_SSLv3_server_method());
# +#else
# +        ctx = 0; // SSL 3 not supported by the system, but chosen deliberately -> error
# +#endif
#          break;
# -    case QSsl::SecureProtocols: // SslV2 will be disabled below
# -    case QSsl::TlsV1SslV3: // SslV2 will be disabled below
#      case QSsl::AnyProtocol:
# -    default:
#          ctx = q_SSL_CTX_new(client ? q_SSLv23_client_method() : q_SSLv23_server_method());
#          break;
#      case QSsl::TlsV1:
# +    case QSsl::SecureProtocols:
# +    case QSsl::TlsV1SslV3:
# +    default:
#          ctx = q_SSL_CTX_new(client ? q_TLSv1_client_method() : q_TLSv1_server_method());
#          break;
#      <CURLY_BRACE>
# (The <CURLY_BRACE> token has to be replaced with the obvious character; stupid TCL can't
# ignore curly braces in comments...

}

# (27) QTKit no longer exists as of macOS 10.12 (Sierra).
# https://trac.macports.org/ticket/52332
platform darwin {
    if {${MINOR} >= 12} {
        patchfiles-append patch-src_gui_kernel_qmime_mac.cpp.diff
    }
}

###############################################

# disable CCACHE for now (ticket #34856)

configure.ccache no

## The main port that installs Qt4:
if {${subport} eq "${name}" || ${subport} eq "${basename}" || ${subport} eq "${name}-x11"} {
    # PortGroup save_configure_cmd 1.0

    # Find a way to specify the SDK to use; Qt will use the 10.4u by
    # default which won't work on 10.6 since it is not supported. Allow
    # the user to specify the SDK if desired.

    global SDK
    set SDK ${configure.sdkroot}
    if {${SDK} eq ""} {
        # Set SDK version depending on OS version
        set sdk_version ""
        if {${MINOR} == 4} {
            # OSX 10.4 requires an additional 'u'
            set sdk_version "10.4u"
        } else {
            set sdk_version "10.${MINOR}"
        }
        if {[vercmp ${xcodeversion} 4.3] < 0} {
            set SDK ${developer_dir}/SDKs/MacOSX${sdk_version}.sdk
        } else {
            set SDK ${developer_dir}/Platforms/MacOSX.platform/Developer/SDKs/MacOSX${sdk_version}.sdk
        }
    }
    # On Leopard and Snow Leopard with libc++ForOlderSystems
    # installed, SDK must be unset as we can only use system libraries
    # also, a missing library link must be replaced for build to
    # succeed: <https://trac.macports.org/ticket/51844>
    platform darwin {
        if {${os.major} == 9 || ${os.major} == 10} {
            if {${configure.cxx_stdlib} eq "libc++"} {
                set SDK ""
                configure.ldflags-append "-lobjc"
                # patchfiles-delete patch-src_plugins_bearer_corewlan_corewlan.pro.diff
            }
        }
    }

    post-patch {
        # Set ARCHES in configure (per the third patchfile above), for
        # building QMake. Join any 2 or more arch entries with the GCC
        # arch flag (join does not affect a single entry). First "-arch"
        # is already in place in the 'configure' script (since there has
        # to be at least 1 arch).

        set ARCHES ""
        if {[variant_exists universal] && [variant_isset universal]} {
            set ARCHES [join ${universal_archs} " -arch "]
        } else {
            set ARCHES ${build_arch}
        }
        reinplace "s|@ARCHES@|${ARCHES}|g" ${worksrcpath}/configure

        # Set MACOSX_DEPLOYMENT_TARGET version in various places. These
        # were all patched in (2) above, and can be easily changed or
        # overridden by the user in a project-local qmake .pro script.

        set TARGET "10.${MINOR}"
        foreach fixfile {configure mkspecs/common/g++-macx.conf \
                         mkspecs/common/mac.conf qmake/qmake.pri \
                         src/tools/bootstrap/bootstrap.pro } {
            reinplace "s|@MACOSX_DEPLOYMENT_TARGET@|${TARGET}|g" \
                ${worksrcpath}/${fixfile}
        }

        # Fix OS version on Bearer CoreWLAN QMake file.

        reinplace "s|@MACOSX_VERSION_MINOR@|${MINOR}|g" \
            ${worksrcpath}/src/plugins/bearer/corewlan/corewlan.pro

        # Ensure that correct C/C++ compilers are used.

        reinplace "s|@CXX@|${configure.cxx}|" \
            ${worksrcpath}/mkspecs/common/g++-base.conf
        reinplace "s|@CC@|${configure.cc}|"  \
            ${worksrcpath}/mkspecs/common/g++-base.conf

        # Fix the corewlan .pro file to use the correct developer SDK.

        reinplace "s,@DEVELOPER_SDK@,${SDK},g" \
            ${worksrcpath}/src/plugins/bearer/corewlan/corewlan.pro

        # Fix 'macdeployqt' to look for the correct
        # plugins location by default.

        reinplace "s,@QT_PLUGINS_DIR@,${qt_plugins_dir},g" \
            ${worksrcpath}/tools/macdeployqt/macdeployqt/main.cpp

        # Fix PREFIX in QMake makefile generator.

        reinplace "s,@PREFIX@,${qt_dir},g" \
            ${worksrcpath}/qmake/generators/unix/unixmake.cpp

        # If no debug, then do not even build debug code.

        if {![variant_isset debug]} {
            foreach fixfile { src/qbase.pri \
                              src/3rdparty/webkit/Source/WebKit.pri \
                              src/imports/qimportbase.pri \
                              src/plugins/qpluginbase.pri \
                              tools/designer/src/components/lib/lib.pro \
                              tools/designer/src/lib/lib.pro \
                              tools/designer/src/plugins/activeqt/activeqt.pro \
                              tools/designer/src/plugins/plugins.pri \
                              tools/designer/src/uitools/uitools.pro \
                              src/3rdparty/webkit/Source/WebKit/qt/declarative/declarative.pro } {
                reinplace "/+=/s@debug_and_release@@g" \
                    ${worksrcpath}/${fixfile}
            }
        }

        # Clean up for the following copy steps, in case we're being called in incremental.
        # fashion.
        delete ${worksrcpath}/mkspecs/features/c++11.prf ${worksrcpath}/config.tests/mac/c++11                          \
            ${worksrcpath}/mkspecs/features/mac/objective_cxx.prf ${worksrcpath}/mkspecs/features/mac/split_sources.prf \
            ${worksrcpath}/config.tests/mac/fconstant_cfstrings.test ${worksrcpath}/config.tests/mac/objc_block         \
            ${worksrcpath}/config.tests/mac/cpath ${worksrcpath}/config.tests/mac/library_path

        # Copy C++11 files into place, if that variant is set.

        if {[variant_isset cxx11]} {
            copy ${filespath}/c++11.prf ${worksrcpath}/mkspecs/features
            copy ${filespath}/c++11 ${worksrcpath}/config.tests/mac
        }

        # Copy Objective C/CXX files into place.

        copy ${filespath}/objective_cxx.prf \
            ${worksrcpath}/mkspecs/features/mac
        copy ${filespath}/split_sources.prf \
            ${worksrcpath}/mkspecs/features/mac

        # Copy extra compiler tests into place; these are patched into
        # the configure script to the area before qmake is built. If any
        # fail, configure will fail quickly.

        copy ${filespath}/fconstant_cfstrings.test \
            ${worksrcpath}/config.tests/mac
        copy ${filespath}/objc_block \
            ${worksrcpath}/config.tests/mac
        copy ${filespath}/cpath \
            ${worksrcpath}/config.tests/mac
        copy ${filespath}/library_path \
            ${worksrcpath}/config.tests/mac
    }

    # Block various compilers:
    #
    # * The build process requires -Xarch, -fconstant-cfstring, and
    # Objective-C(++) blocks (^), which are not supported with vanilla GCC
    # as installed by MacPorts but are supported by all versions of CLANG
    # (both MacPorts' and Apple's).
    #
    # * Some older versions of CLANG do not honor the CPATH
    # environment variables, which is required for compiling
    # this port when using MacPorts. The versions seem to be: MacPorts
    # CLANG 2.9 or earlier, and Apple CLANG 318.0.58 or older.
    #
    # * Some older versions of CLANG do not honor the LIBRARY_PATH
    # environment variables, which is required for compiling
    # this port when using MacPorts. The versions seem to be: MacPorts
    # CLANG 3.0 or earlier, and Apple CLANG 318.0.61 or older.
    #
    # * qt4-creator-mac fails to build with GCC <= 4.0.
    #
    # See also:
    # < http://llvm.org/bugs/show_bug.cgi?id=8971 >,
    # < https://trac.macports.org/ticket/30271 >,
    # < https://trac.macports.org/ticket/31076 >,
    # < https://trac.macports.org/ticket/31638 >,
    # < https://trac.macports.org/ticket/37868 >, and
    # < https://trac.macports.org/ticket/40422 >.
    #
    # NOTE: qt4-mac augments the standard Qt4 configure script with
    # pre-qmake-build tests for CPATH, LIBRARY_PATH, -Xarch,
    # -fconstant-cfstring, Objective-C(++) blocks, and, if requested,
    # C++11. The script will error out quickly if the compiler does not
    # seem to provide support for any one of these properties, no matter
    # this blacklist.

    compiler.blacklist-append { clang <= 318.0.61 } \
        gcc-3.3 *gcc-4.0 macports-gcc* \
        macports-clang-2.9 macports-clang-3.0

    # --prefix is not recognized.
    configure.pre_args-delete       --prefix=${prefix}
    configure.args

    # --disable-dependency-tracking is not recognized.
    configure.universal_args-delete --disable-dependency-tracking

    # Clear all arch-oriented flags since somehow they impact how qmake is
    # created, which in turn messes up LDFLAGS in most created Makefiles.

    configure.ld_archflags
    configure.cc_archflags
    configure.cxx_archflags
    configure.universal_ldflags
    configure.universal_cflags
    configure.universal_cxxflags
    configure.universal_cppflags
    configure.march
    configure.mtune

    configure.ldflags-append    ${configure.optflags}
#    if {[variant_isset LTO]} {
        # certain components do not support LTO:
#        patchfiles-append       patch-no-lto.diff \
                                patch-lto-no-sse4.diff

        # Deactivate 3DNOW support. SSE4 support also needs to be disabled because of
        # the same clang bug, but we do that with patches. Doing it here would also disable
        # AVX support.
#        configure.args-append       -no-3dnow
#    }

    # Use compiler.cpath and compiler.library_path for all -I and -L
    # entries, so-as to avoid conflicts with already-installed headers and
    # libraries (giving preference to internal-to-this-port first). CPATH
    # is used instead of -I to avoid conflicts with other ports.
    #
    # See also:
    # < https://trac.macports.org/ticket/15219 >,
    # < https://trac.macports.org/ticket/18723 >, and
    # < https://trac.macports.org/ticket/25321 >.

    # Set the default paths to include those for SQLITE3 and DBUS-1.

    set header_path [ list ${prefix}/include/dbus-1.0 \
                           ${prefix}/lib/dbus-1.0/include \
                           ${prefix}/include ]

    set library_path [ list ${prefix}/lib ]

    # Set up things for an out-of-source build:
    default configure.dir   {${workpath}/build}
    default build.dir       {${workpath}/build}
    default configure.cmd   {../${worksrcdir}/configure}
#     set qmake_cache_path    ${worksrcpath}/.qmake.cache
    set qmake_cache_path    ${build.dir}/.qmake.cache

    # -dbus-linked prevends qt4 from trying to dynamically load libdbus-1,
    #     which it is not able to find in ${prefix}.
    #
    # -openssl-linked ensures that the MacPorts openssl is used.
    #
    # -framework ensures that this port is installed as frameworks
    #     (collections of {library, headers, resources}); in
    #     post-destroot, link headers and libraries from the frameworks
    #     into non-framework locations as if "-no-framework" were
    #     specified. Some dependent projects will not work properly if Qt
    #     is installed as libraries by default, thus make it so #1.
    #
    # -no-phonon ensures that Qt does not install the 3rd-parth Phonon
    #     port or its backend to QuickTime 7; Phonon is now installed via
    #     the 'phonon' port, which is more up to date than that provided
    #     by Qt.
    # 20151003 : -prefix ${prefix} instead of -prefix ${qt_dir} (as with Qt5) would be
    # great, but will lead to frameworks in ${prefix}/Library/Frameworks instead
    # of in ${qt_dir}/Library/Frameworks ...

    configure.args-append                                     \
        -v                                                    \
        -confirm-license                                      \
        -opensource                                           \
        -prefix          ${qt_dir}                            \
        -bindir          ${qt_bins_dir}                       \
        -libdir          ${qt_libs_dir}                       \
        -docdir          ${qt_docs_dir}                       \
        -headerdir       ${qt_includes_dir}                   \
        -plugindir       ${qt_plugins_dir}                    \
        -importdir       ${qt_imports_dir}                    \
        -datadir         ${qt_data_dir}                       \
        -translationdir  ${qt_translations_dir}               \
        -sysconfdir      ${qt_sysconf_dir}                    \
        -examplesdir     ${qt_examples_dir}                   \
        -demosdir        ${qt_demos_dir}                      \
        -openssl-linked                                       \
        -I [openssl::include_dir]                             \
        -dbus-linked                                          \
        -fast                                                 \
        -optimized-qmake                                      \
        -no-pch                                               \
        -framework                                            \
        -no-phonon                                            \
        -no-phonon-backend                                    \
        -fontconfig -system-freetype                          \
        --jobs=${build.jobs}

    # Adding "-L[openssl::lib_dir] -lssl -lcrypto" to LDFLAGS can have surprising
    # results if someone (the compiler driver?) decides to re-arrange the arguments.
    # Refer the desired libraries using their full path and all will be well.
    configure.env-append \
        "OPENSSL_LIBS=[openssl::lib_dir]/libssl.dylib [openssl::lib_dir]/libcrypto.dylib"

#     configure.args-append      -qpa cocoa

    # Stop configure script from searching for SQL Drivers
    #    not available from MacPorts.

    foreach driver {db2 ibase oci tds} {
        configure.args-append   -no-sql-${driver}
    }

    # Disable all remaining SQL Drivers.  These are available via
    # the ports qt4-mac-*-plugin.
    # The sqlite3 plugin ("sqlite") has been re-absorbed into the main port however.

    configure.args-append -system-sqlite
    depends_lib-append port:sqlite3
    foreach driver {mysql odbc psql sqlite2} {
        configure.args-append -no-sql-${driver}
    }

    configure.args-append   -no-exceptions

    pre-configure {

        # Use the corrected CPATH and LIBRARY_PATH for build.

        compiler.cpath [join ${header_path} :]
        compiler.library_path [join ${library_path} :]

        # For 10.4 or 10.5 32-bit PPC, build as Carbon only, not Cocoa.
        # Notice, we build as Cocoa on 10.6.8 PPC.

        if {${MINOR} == 4} {

            configure.args-append -carbon

            # Required linking flags?

            configure.ldflags-append -lcrypto -ldbus-1 -ljpeg -llcms \
                -lssl -lz

        } elseif {${MINOR} == 5 &&
                  [llength ${qt_arch_types}] == 1 &&
                  [lsearch -exact ${qt_arch_types} ppc] == 0} {

            configure.args-append -carbon
        }

        # Set the arch type(s) to use, in Qt-speak.

        configure.args-append -arch \"${qt_arch_types}\"

        # Check to see if not compiling for the native machine hardware
        # (e.g., compiling for just i386 but CPU is x86_64); optimization
        # of QMake does not work in this circumstance.

        if {[lsearch -exact ${qt_arch_types} ${os.arch}] == -1} {

            ui_msg "qt_arch_types=${qt_arch_types} but os.arch==${os.arch} ; ignoring and building optimised qmake anyway"
            # Not building for native arch: disable optimizing qmake
            # configure.args-delete -optimized-qmake

        } elseif {${MINOR} == 6 &&
                  [llength ${qt_arch_types}] == 1 &&
                  [lsearch -exact ${qt_arch_types} x86] == 0} {

            # Disable qmake optimization on 10.6 i386.
            configure.args-delete -optimized-qmake
        }

        # On Leopard and Snow Leopard with libc++ForOlderSystems
        # installed, SDK must be unset as we can only use system libraries
        # also, a missing library link must be replaced for build to
        # succeed: <https://trac.macports.org/ticket/51844>
        platform darwin {
            if {${os.major} == 9 || ${os.major} == 10} {
                if {${configure.cxx_stdlib} eq "libc++"} {
                    set SDK ""
                    configure.ldflags-append "-lobjc"
                }
            }
        }

        # Set the SDK, if it was found and exists.
        if {[file exists ${SDK}]} {
            configure.args-append -sdk ${SDK}
        }

        # Set which pkg-config to use.

        configure.env-append PKG_CONFIG=${prefix}/bin/pkg-config

        # Set which stdlib to use; clang only.
        if {[string match *clang* ${configure.compiler}]} {
            configure.env-append QMAKE_STDLIB="-stdlib=${configure.cxx_stdlib}"
            configure.ldflags-append -stdlib=${configure.cxx_stdlib}
        }
        configure.env-append    MAKEFLAGS=-j${build.jobs}
    }

#    configure.save_configure_cmd "install log"

    post-configure {

        # Remove any '-I' and '-L' string from the *FLAGS for SQLITE,
        # DBUS, ODBC, and OPENSSL, so that what remains are just non-I/L
        # flags; these paths are in compiler.cpath and
        # compiler.library_path. The header and library paths for all
        # the other variants are not used by 'configure', and are already
        # included in the compiler.cpath and compiler.library_path
        # . during the 'build' stage, 'make' will rebuild the Makefiles
        # that depend on any of these changed files. These patches are
        # sufficient to make sure local (to this build) paths are searched
        # first, and then system paths last (via the compiler.X settings).
        # Ideally, 'qmake' – either via its mkspecs files or the
        # project's build files – would distinguish between "local" and
        # "system" includes & libraries.

        # SQLITE
        reinplace "/SQLITE/s@-I${prefix}/\[^ \]*include\[^ \]*@@g" \
            ${build.dir}/.qmake.cache
        reinplace "/SQLITE/s@-L${prefix}/\[^ \]*lib\[^ \]*@@g" \
            ${build.dir}/.qmake.cache
        # DBUS
        reinplace "/DBUS/s@-I${prefix}/\[^ \]*include\[^ \]*@@g" \
            ${build.dir}/.qmake.cache
        reinplace "/DBUS/s@-L${prefix}/\[^ \]*lib\[^ \]*@@g" \
            ${build.dir}/.qmake.cache
        # OPENSSL
        reinplace "/OPENSSL/s@-I${prefix}/\[^ \]*include\[^ \]*@@g" \
            ${build.dir}/.qmake.cache
        reinplace "/OPENSSL/s@-L${prefix}/\[^ \]*lib\[^ \]*@@g" \
            ${build.dir}/.qmake.cache
        # ODBC
        reinplace "/ODBC/s@-I${prefix}/\[^ \]*include\[^ \]*@@g" \
            ${build.dir}/.qmake.cache
        reinplace "/ODBC/s@-L${prefix}/\[^ \]*lib\[^ \]*@@g" \
            ${build.dir}/.qmake.cache
        # Attempt to add our ObjC/++ compiler flags to .qmake.cache.
        if {![catch {set fd [open "${build.dir}/.qmake.cache" "a"]} err]} {
            puts ${fd} "QMAKE_OBJECTIVE_CFLAGS += ${configure.objcflags}"
            puts ${fd} "QMAKE_OBJECTIVE_CXXFLAGS += ${configure.objcxxflags}"
            close ${fd}
            unset fd
        } else {
            ui_warning "Couldn't add our ObjC/++ compiler flags to .qmake.cache!"
            if {![variant_isset cxx11]} {
                ui_warning "(The build will probably fail if your compiler uses C++11 or newer by default)"
            }
        }

        if {![catch {set fd [open "${workpath}/.macports.${subport}.configure.info" "w"]} err]} {
            foreach var [array names ::env] {
                puts ${fd} "${var}=$::env(${var})"
            }
            puts ${fd} "[join [lrange [split ${configure.env} " "] 0 end] "\n"]\n"
            puts ${fd} "cd ${worksrcpath}"
            if {[info exists configure.post_args]} {
                puts ${fd} "${configure.cmd} ${configure.pre_args} ${configure.args} ${configure.post_args}"
            } else {
                puts ${fd} "${configure.cmd} ${configure.pre_args} ${configure.args}"
            }
            if {[file exists "${configure.dir}/.qmake.cache"]} {
                puts ${fd} "## ${configure.dir}/.qmake.cache:"
                close ${fd}
                system "cat \"${configure.dir}/.qmake.cache\" >> \"${workpath}/.macports.${subport}.configure.info\""
            } else {
                close ${fd}
            }
            unset fd
        }
    }

    pre-build {
        # Use the corrected CPATH and LIBRARY_PATH for build.
        compiler.cpath [join ${header_path} :]
        compiler.library_path [join ${library_path} :]
    }

    # Do not use DESTDIR directly in the destroot command; Qt uses DISTDIR
    # internally for other purposes, and instead uses INSTALL_ROOT for
    # the additional install root prefix.

    destroot.post_args

    pre-destroot {
        # This isn't really nice if the user has 2nd thoughts and wants to install those html files after all
        # (and knows how to get port to redo an install without cleaning and rebuilding everything).
        # Let's hope that happens rarely enough to prefer speeding up the destroot step for the others.
        if {![variant_isset htmldocs]} {
            if {[file exists ${worksrcpath}/doc/html/images]} {
                ui_msg "cleaning out ${worksrcpath}/doc/html per your request"
                delete file ${worksrcpath}/doc/html/images ${worksrcpath}/doc/html/scripts ${worksrcpath}/doc/html/style
                eval file delete [glob ${worksrcpath}/doc/html/*.html]
                eval file delete [glob ${worksrcpath}/doc/html/qt.*]
            }
        }
    }

    post-destroot {

        set destroot_qt ${destroot}${qt_dir}

        # Fix .pc and .prl files by changing ${worksrcpath}\${prefix} to
        # ${qt_dir}\${prefix} ("\" means 'take away'). Cannot use
        # "find -E" since it is not necessarily portable.

        regsub ${prefix} ${worksrcpath} "" from_dir
        regsub ${prefix} ${qt_dir} "" to_dir
        foreach fixfile [exec find ${destroot_qt} -name "*.pc"] {
            reinplace -q "s|${from_dir}|${to_dir}|g" ${fixfile}
        }
        foreach fixfile [exec find ${destroot_qt} -name "*.prl"] {
            reinplace -q "s|${from_dir}|${to_dir}|g" ${fixfile}
        }

        # Fix .pc files

        foreach fixfile [exec find ${destroot_qt} -name "*.pc"] {

            # Remove Libs.private; they can mess up linking

            reinplace -q "/Libs\.private/d" ${fixfile}

            # Use ${prefix} correctly

            # RJVB:
            # Don't replace ${prefix} (e.g. /opt/local) with \${prefix}
            # unless ${qt_dir} == ${prefix} (but I don't see the point at all...)
            if {${prefix} eq ${qt_dir}} {
                reinplace -q "s|${prefix}/|\${prefix}/|g" ${fixfile}
            }

            # Fix libdir

            reinplace -q "/libdir=/s|Library/Frameworks|lib|" ${fixfile}

            # Fix Libs: to use -L instead of -F

            reinplace -q "/Libs:/s|-F|-L|" ${fixfile}

            # Fix Libs: to use -lQt* instead of "-framework Qt*"
            # Depends on whether for release or debug

            set fn [lindex [split ${fixfile} /] end]

            if {[lsearch -regexp ${fn} debug] == 0} {

                # Debug; need to add that string to all Qt dependency libraries.
                reinplace -q "/Libs:/s|-framework Qt\\(\[^ \]*\\)|-lQt\\1_debug|" \
                    ${fixfile}

            } else {

                # No debug; just replace
                reinplace -q "/Libs:/s|-framework Qt|-lQt|" ${fixfile}
            }
        }

        # Move .pc files from ${qt_frameworks_dir}/pkgconfig to
        # ${qt_pkg_config_dir}

        file delete -force ${destroot}${qt_pkg_config_dir}
        xinstall -m 755 -d ${destroot}${qt_libs_dir}
    #    move ${destroot}${qt_frameworks_dir}/pkgconfig \
    #        ${destroot}${qt_libs_dir}
    # RJVB: ${destroot}${qt_libs_dir} is NOT always equal to ${qt_pkg_config_dir} !!
        move ${destroot}${qt_frameworks_dir}/pkgconfig \
            ${destroot}${qt_pkg_config_dir}
        # qt_pkg_config_dir==${prefix}/lib/pkgconfig; make a symlink to that place in
        # ${qt_libs_dir} so that 3rd party .pc files end up where pkg-config can find them ...
        ln -s ${qt_pkg_config_dir} ${destroot}${qt_libs_dir}/pkgconfig

        # Move .la files from ${qt_frameworks_dir} to ${qt_libs_dir}

        foreach laf [glob ${destroot}/${qt_frameworks_dir}/*.la] {
            move ${laf} ${destroot}${qt_libs_dir}
        }

        # Remove -L entries from .prl and .la files.

        foreach fixfile [exec find ${destroot_qt} -name "*.prl"] {
            reinplace -q "/QMAKE_PRL_LIBS/s|-L\[^ \]*||g" ${fixfile}
        }
        foreach fixfile [exec find ${destroot_qt} -name "*.la"] {
            reinplace -q "/dependency_libs/s|-L\[^ \]*||g" ${fixfile}
        }

        # Remove redundant -F entries from .prl and .la files.

        foreach fixfile [exec find ${destroot_qt} -name "*.prl"] {
            reinplace -q "/QMAKE_PRL_LIBS/s|-F\[^ \]*|FREPLACEME|1" \
                ${fixfile}
            reinplace -q "/QMAKE_PRL_LIBS/s|-F\[^ \]*||g" ${fixfile}
            reinplace -q "s|FREPLACEME|-F${prefix}/${qt_frameworks_dir_rel}|1" \
                ${fixfile}
            # Also remove the QMAKE_PRL_BUILD_DIR lines.
            reinplace -q "/QMAKE_PRL_BUILD_DIR/d" ${fixfile}
        }
        foreach fixfile [exec find ${destroot_qt} -name "*.la"] {
            reinplace -q "/dependency_libs/s|-F\[^ \]*|FREPLACEME|1" \
                ${fixfile}
            reinplace -q "/dependency_libs/s|-F\[^ \]*||g" ${fixfile}
            reinplace -q "s|FREPLACEME|-F${prefix}/${qt_frameworks_dir_rel}|1" \
                ${fixfile}
        }

        # Get Qt's version numbers

        set qt_vers [split ${version} "."]
        set qt_major [lindex ${qt_vers} 0]
        set qt_minor [lindex ${qt_vers} 1]
        set qt_patch [lindex ${qt_vers} 2]

        # Link includes and libraries for each actual installed framework

        # Make sure that qt_includes_dir exist; apparently it will not have been created at this point,
        # despite the -headerdir ${qt_includes_dir} argument to configure. Because of doing a framework build?
        exec mkdir -p ${destroot}${qt_includes_dir}
        foreach fixfile [exec find ${destroot}${qt_frameworks_dir} \
                             -name "*.framework" | \
                             sed -e "s@${destroot}@@g"] {

            set tf_full [strsed ${fixfile} {s@\\.framework@@}]
            set tf [strsed ${tf_full} {g@.*\/@@}]

            # Special for QtWebKit entries
            set t_minor ${qt_minor}
            set is_QtWebKit 0
            if {[string compare ${tf} QtWebKit] == 0} {
                set t_minor 9
                set is_QtWebKit 1
            }

            # Link headers into ${qt_includes_dir}, removing directories if they are already there first.
            set inc_file ${destroot}${qt_includes_dir}/${tf}
            if {[file exists ${inc_file}]} {
                file delete -force ${inc_file}
            }

            ln -s ${tf_full}.framework/Headers ${inc_file}

            # Link libraries into ${qt_libs_dir}, all 4 number variants.
            set dr_qt_libs_dir ${destroot}${qt_libs_dir}

            ln -s ${tf_full}.framework/${tf} ${dr_qt_libs_dir}/lib${tf}.dylib
            ln -s ${tf_full}.framework/${tf} ${dr_qt_libs_dir}/lib${tf}.${qt_major}.dylib
            ln -s ${tf_full}.framework/${tf} ${dr_qt_libs_dir}/lib${tf}.${qt_major}.${t_minor}.dylib
            ln -s ${tf_full}.framework/${tf} ${dr_qt_libs_dir}/lib${tf}.${qt_major}.${t_minor}.${qt_patch}.dylib

            # Copy .prl file, then correct it for library usage.
            copy ${destroot}${tf_full}.framework/${tf}.prl ${dr_qt_libs_dir}/lib${tf}.prl

            # Fix TARGET in .prl file.
            reinplace -q "/QMAKE_PRL_TARGET/s|Qt\\(\[^ \]*\\)|libQt\\1.${qt_major}.${t_minor}.${qt_patch}.dylib|" ${dr_qt_libs_dir}/lib${tf}.prl

            # Fix PRL_LIBS -F -> -L in .prl file.
            reinplace -q "/QMAKE_PRL_LIBS/s|-F${qt_frameworks_dir}|-L${qt_libs_dir}|" ${dr_qt_libs_dir}/lib${tf}.prl

            # Fix "-framework Qt*" -> "-lQt*" in .prl file.
            reinplace -q "/QMAKE_PRL_LIBS/s|-framework Qt|-lQt|g" \
                ${dr_qt_libs_dir}/lib${tf}.prl

            # Fix up .la files to work with ${prefix}/lib entries.
            # Rename .la file.
            move ${dr_qt_libs_dir}/${tf}.la ${dr_qt_libs_dir}/lib${tf}.la

            # Fix "name that we can dlopen" in .la file.
            reinplace -q "s|dlname=''|dlname='lib${tf}.${qt_major}.${t_minor}.${qt_patch}.dylib'|" ${dr_qt_libs_dir}/lib${tf}.la

            # Fix "names of this library" in .la file.
            reinplace -q "s|library_names='\[^'\]*'|library_names='lib${tf}.${qt_major}.${t_minor}.${qt_patch}.dylib lib${tf}.${qt_major}.${t_minor}.dylib lib${tf}.${qt_major}.dylib lib${tf}.dylib'|" \
                ${dr_qt_libs_dir}/lib${tf}.la

            # Fix "name of the static archive"; there is none in .la file.
            reinplace -q "s|old_library='\[^'\]*'|old_library=''|" \
                ${dr_qt_libs_dir}/lib${tf}.la

            # Fix "libraries that this one depends upon" in .la file.
            reinplace -q "/dependency_libs/s|-F${qt_frameworks_dir}|-L${qt_libs_dir}|"  ${dr_qt_libs_dir}/lib${tf}.la
            reinplace -q "/dependency_libs/s|-framework Qt|-lQt|g" ${dr_qt_libs_dir}/lib${tf}.la
            reinplace -q "/dependency_libs/s| ${worksrcpath}\[^ \]*||g" ${dr_qt_libs_dir}/lib${tf}.la
            reinplace -q "/dependency_libs/s| -lwebcore||" ${dr_qt_libs_dir}/lib${tf}.la
            reinplace -q "/dependency_libs/s| -ljscore||" ${dr_qt_libs_dir}/lib${tf}.la

            # Fix "directory that this library needs to be installed in" in .la file.
            reinplace -q "/libdir/s|${qt_frameworks_dir}|${qt_libs_dir}|" \
                ${dr_qt_libs_dir}/lib${tf}.la

            # Deal with debug files
            if {[variant_isset debug]} {
                # But not if QtWebKit and +universal, since that one does
                # not exist (the 32-bit version of the debug library is
                # larger than fits into the 32-bit filespace).

                if {[variant_isset debug] && ${is_QtWebKit}} {
                    continue
                }

                # Link libraries into ${qt_libs_dir}, all 4 number variants.
                ln -s ${tf_full}.framework/${tf}_debug ${dr_qt_libs_dir}/lib${tf}_debug.dylib
                ln -s ${tf_full}.framework/${tf}_debug ${dr_qt_libs_dir}/lib${tf}_debug.${qt_major}.dylib
                ln -s ${tf_full}.framework/${tf}_debug ${dr_qt_libs_dir}/lib${tf}_debug.${qt_major}.${t_minor}.dylib
                ln -s ${tf_full}.framework/${tf}_debug ${dr_qt_libs_dir}/lib${tf}_debug.${qt_major}.${t_minor}.${qt_patch}.dylib

                # Copy .prl file, then correct it for library usage.
                copy ${destroot}${tf_full}.framework/${tf}_debug.prl ${dr_qt_libs_dir}/lib${tf}_debug.prl

                # Fix TARGET in .prl file.
                reinplace -q "/QMAKE_PRL_TARGET/s|Qt\\(\[^ \]*\\)|libQt\\1.${qt_major}.${t_minor}.${qt_patch}.dylib|" ${dr_qt_libs_dir}/lib${tf}_debug.prl

                # Fix PRL_LIBS -F -> -L in .prl file.
                reinplace -q "/QMAKE_PRL_LIBS/s|-F${qt_frameworks_dir}|-L${qt_libs_dir}|" ${dr_qt_libs_dir}/lib${tf}_debug.prl

                # Fix "-framework Qt*" -> "-lQt*_debug" in .prl file.
                reinplace -q "/QMAKE_PRL_LIBS/s|-framework Qt\\(\[^ \]*\\)|-lQt\\1_debug|g" ${dr_qt_libs_dir}/lib${tf}_debug.prl

                # Fix up .la files to work with ${prefix}/lib entries.
                # Rename .la file
                move ${dr_qt_libs_dir}/${tf}_debug.la \
                    ${dr_qt_libs_dir}/lib${tf}_debug.la

                # Fix "name that we can dlopen" in .la file.
                reinplace -q "s|dlname=''|dlname='lib${tf}_debug.${qt_major}.${t_minor}.${qt_patch}.dylib'|" ${dr_qt_libs_dir}/lib${tf}_debug.la

                # Fix "names of this library" in .la file.
                reinplace -q "s|library_names='\[^'\]*'|library_names='lib${tf}_debug.${qt_major}.${t_minor}.${qt_patch}.dylib lib${tf}_debug.${qt_major}.${t_minor}.dylib lib${tf}_debug.${qt_major}.dylib lib${tf}_debug.dylib'|" \
                    ${dr_qt_libs_dir}/lib${tf}_debug.la

                # Fix "name of the static archive"; there is none in .la file.
                reinplace -q "s|old_library='\[^'\]*'|old_library=''|" ${dr_qt_libs_dir}/lib${tf}_debug.la

                # Fix "libraries that this one depends upon" in .la file.
                reinplace -q "/dependency_libs/s|-F${qt_frameworks_dir}|-L${qt_libs_dir}|" ${dr_qt_libs_dir}/lib${tf}_debug.la
                reinplace -q "/dependency_libs/s|-framework Qt\\(\[^ \]*\\)|-lQt\\1_debug|g" ${dr_qt_libs_dir}/lib${tf}_debug.la
                reinplace -q "/dependency_libs/s| ${worksrcpath}\[^ \]*||g" ${dr_qt_libs_dir}/lib${tf}_debug.la
                reinplace -q "/dependency_libs/s| -lwebcored||" ${dr_qt_libs_dir}/lib${tf}_debug.la
                reinplace -q "/dependency_libs/s| -ljscored||" ${dr_qt_libs_dir}/lib${tf}_debug.la

                # Fix "directory that this library needs to be installed in" in .la file.
                reinplace -q "/libdir/s|${qt_frameworks_dir}|${qt_libs_dir}|" ${dr_qt_libs_dir}/lib${tf}_debug.la
            }
        }

        # Install documentation.
        xinstall -m 755 -d ${worksrcpath}/${qt_docs_dir}
        xinstall -m 644 -W ${worksrcpath} \
            INSTALL LGPL_EXCEPTION.txt LICENSE.FDL \
            LICENSE.GPL3 LICENSE.LGPL README \
            ${destroot}${qt_docs_dir}

        # Install private headers needed by QtCreator.
        foreach {src_dir include_dir} \
        {corelib QtCore gui QtGui script QtScript declarative QtDeclarative} {
            set dest_dir ${destroot}${qt_frameworks_dir}/${include_dir}.framework/Headers/private
            xinstall -m 755 -d ${dest_dir}
            set files [exec find ${worksrcpath}/src/${src_dir} -type f -name "*_p.h"]
            eval xinstall -m 644 [split ${files}] ${dest_dir}
        }

        # Move .apps into the applications_dir, and link each .apps'
        # executable back into ${qt_bins_dir}

        set dr_qt_apps_dir ${destroot}${qt_apps_dir}
        set dr_qt_bins_dir ${destroot}${qt_bins_dir}

        xinstall -m 755 -d ${dr_qt_apps_dir}
        foreach app [glob ${dr_qt_bins_dir}/*.app] {

            # Remove the leading stuff
            set app [lindex [split ${app} /] end]

            # Move the .app
            move ${dr_qt_bins_dir}/${app} ${dr_qt_apps_dir}
            # link it back
            ln -s ${qt_apps_dir}/${app} ${dr_qt_bins_dir}

            # Provide a proxy to the app's executable; symlinks won't
            # be accepted by qtchooser if the user has that port installed.
            set texe [strsed ${app} {g@\.app@@}]
            set appProxy ${dr_qt_bins_dir}/[string tolower ${texe}]
            copy ${filespath}/appProxy.sh ${appProxy}
            reinplace "s|@BUNDLEEXEC@|${qt_apps_dir}/${app}/Contents/MacOS/${texe}|g" ${appProxy}
        }

        file delete -force ${destroot}${qt_apps_dir}/examples

        # Move tests to ${qt_data_dir}.
        # barracuda: God knows why this is inconsistent, out of the blue this dir may be missing...
        xinstall -m 755 -d ${destroot}${qt_data_dir}
        if {[file exists ${destroot_qt}/tests/qt4]} {
            move ${destroot_qt}/tests/qt4 ${destroot}${qt_data_dir}/tests
        }

        # Install ${qt_includes_dir}/Qt if not already and it exists in
        # the build, for support of legacy projects.
        if {![file exists ${destroot}${qt_includes_dir}/Qt] &&
            [file exists ${worksrcpath}/include/Qt]} {

            # Copy the Qt headers directory
            copy ${worksrcpath}/include/Qt ${destroot}${qt_includes_dir}
        }

        # Link in Resource to ${qt_libs_dir}
        ln -s ${qt_frameworks_dir}/QtGui.framework/Resources \
            ${destroot}${qt_libs_dir}

        ln -s ${qt_qmake_cmd} ${destroot}/${prefix}/bin/qmake-qt${qt_major}
        ln -s ${qt_moc_cmd} ${destroot}/${prefix}/bin/moc-qt${qt_major}
        ln -s ${qt_uic_cmd} ${destroot}/${prefix}/bin/uic-qt${qt_major}
        ln -s ${qt_lrelease_cmd} ${destroot}/${prefix}/bin/lrelease-qt${qt_major}
        if {[variant_isset KDE]} {
            # Expose KDE4 styles to Qt4:
            ln -s ${prefix}/lib/kde4/plugins/styles ${destroot}${qt_plugins_dir}/
        }
        if {![variant_isset exceptions ]} {
            # Building with -no-exceptions will add a section to QtCore/qconfig.h that has to be removed
            # given that we did NOT build QtCore WITHOUT exceptions...
            exec patch -d ${destroot}${qt_frameworks_dir} -Np0 -i ${filespath}/qconfig-remove-EXCEPTIONS.diff
        }
    }

    variant odbc description {Enable iODBC SQL Driver} {
        depends_lib-append \
            port:libiodbc

        configure.args-delete -no-sql-odbc
        configure.args-append -plugin-sql-odbc
    }

    variant raster description {Use raster graphics system by default} {
        configure.args-append -graphicssystem raster
    }

    configure.args-append -nomake demos
    configure.args-append -nomake examples

    variant debug description {Build both release and debug library} {}

    if {[variant_isset debug]} {
        configure.args-append -debug-and-release -declarative-debug
    } else {
        configure.args-append -release -no-declarative-debug -DNDEBUG
    }

    variant openvg description {Build with *experimental* support for OpenVG} {
        depends_lib-append \
            port:mesa

        pre-configure {
            # Set OpenVG arg, for both testing and building
            configure.env-append QMAKE_OPENVG_ARG=-lOpenVG
        }
    }

    variant cxx11 description {Add library support for C++11 (EXPERIMENTAL; does not work with libc++)} {
        # Block compilers that do not support C++11. This variant seems to
        # work with MacPorts' clang 3.0 or newer and Apple clang newer
        # than 318.0.58 (but, not that version, which is already blocked).

        compiler.blacklist-append \
            *gcc-4.0 *gcc-4.2

        pre-fetch {
            # This variant does not work with Clang libc++
            if {[info exists configure.cxx_stdlib] &&
                ${configure.cxx_stdlib} eq "libc++" &&
                [string match *clang* ${configure.cxx}]} {

                ui_msg "\nERROR: C++11 support for Qt4 is not available when using Clang and libc++.\n"
                error "unsupported platform for C++11 support"
            }
        }

        pre-extract {
            ui_msg "\nWARNING: You have enabled C++11 support for Qt4, which is EXPERIMENTAL. Qt's libraries and applications (not including QMake) will be compiled using C++11. That said, C++11 will NOT be enabled by default when using QMake. You can enable C++11 by specifying, e.g. \'CONFIG += c++11\', in any QMake build file.\n"
        }

        # Patches for C++11 only
        patchfiles-append patch-cxx11.diff

        # Have configure test for C++11; our hooks
        # will error out if C++11 is not found.
        configure.args-append -c++11
    }

    if {[variant_isset cxx11]} {
        configure.compiler_standard 2011
    } else {
        compiler.cxx_standard 1998
        configure.cxxflags-append -std=gnu++98
        configure.objcxxflags-append -std=gnu++98
    }

    variant htmldocs description {Install HTML documentation (>200Mb)} {}

    post-activate {
        ui_msg "NOTE: Qt database plugins for mysql55, postgresql91 and sqlite2 are NOT installed by this port\; they are installed by qt4-mac-*-plugin instead."
    }

    variant KDE description {Include RJVB's patches for use with KDE} {
        patchfiles-append   qt4-deactivate-menurole-heuristics.patch \
                            debug-negative-qtimerint.patch \
                            silence-qfilesystemwatcher.patch \
                            patch-QAction_isEnabled.diff \
                            patch-enable-dumpObjectInfo.diff \
                            patch-qkqueuefilesystemwatcher_addPaths.diff \
                            patch-mute-inactive-painter-msgs.diff
    }

    variant exceptions description {build using exceptions internally (useless, but traditional)} {
        patchfiles-delete       disable-exceptions.patch
        configure.args-delete   -no-exceptions
    }

    variant harfbuzz conflicts emojis description {Use HarfBuzz to do text layout by default instead of Core Text when possible.} {
        # Qt uses an internal (tweaked?) copy of harfbuzz
        configure.args-append   -harfbuzz
    }

    variant emojis conflicts harfbuzz description {Highly experimental, flaky and hardly functional support for color fonts and emojis} {}
}

foreach parp ${qtportlist} {
    foreach subp {demos examples} {
        subport ${parp}-${subp} {
            description                 Qt ${subp}
            long_description            ${description}

            depends_lib-append          port:${parp}
            PortGroup                   qmake 1.0

            pre-configure {
                configure.args-append   CONFIG+=\"${qt_arch_types}\"
            }

            extract.post_args           | tar -xf - ${distname}/${subp}

            default configure.dir       {${workpath}/build}
            configure.pre_args-append   -spec ${qt_mkspecs_dir}/${qt_qmake_spec} ../${worksrcdir}/${subp}/${subp}.pro
            default build.dir           {${workpath}/build}

            if {${subp} eq "demos"} {
                patchfiles-append       patch-build-qtdemo.diff
                notes-append "It is recommended to install ${parp}-examples too"
            } elseif {${subp} eq "examples"} {
                patchfiles-append       patch-examples-tools.diff
            }
        }
    }
}

# The following is redundant, since we support hierarchical PG search from local and rsync repos.
# However, keep it here just in case.
# post-activate {
#     set pdir [file dirname ${filespath}]
#     set resdir [file normalize "${pdir}/../../_resources/port1.0/group"]
#     set pgroup_files {"qt4-1.0.tcl"}
#     ui_msg "Don't forget to copy the following file(s) into your main port tree's _resources directory:"
#     foreach pg ${pgroup_files} {
#         ui_msg "\t${resdir}/${pg}"
#     }
#     ui_msg "(That's probably ${prefix}/var/macports/sources/rsync.macports.org/release/ports/_resources/port1.0/group"
#     ui_msg "or ${prefix}/var/macports/sources/svn.macports.org/trunk/dports/_resources/port1.0/group)"
# }

livecheck.type      regex
livecheck.url       http://download.qt.io/official_releases/qt/${branch}/
livecheck.regex     >(\[0-9.\]+)/<

# kate: backspace-indents true; indent-pasted-text true; indent-width 4; keep-extra-spaces true; remove-trailing-spaces modified; replace-tabs true; replace-tabs-save true; syntax Tcl/Tk; tab-indents true; tab-width 4;
