# -*- 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

PortSystem          1.0
PortGroup           cmake 1.1
PortGroup           compiler_blacklist_versions 1.0
PortGroup           github 1.0

#==============================================================================
# IMPORTANT NOTE
#
# Before updating to a new version from upstream, please test building with
# +contrib, in addition to the default. Reason being, the extra functionality
# is used by many, including our own MacPorts members. Enough so that we may
# want to enable +contrib by default at some point.
#
# Also note that upstream has occassionally broken the Contrib build, so it's
# not a given that it will compile successfully.
#
# Net-Net: If upstream breaks Contrib for a certain release, please don't
# update to it. And submit a ticket for the issue, if none exists.
#
# Thanks!
#==============================================================================

name                opencv4
conflicts           opencv4-devel
set my_name         opencv4

platforms           {darwin >= 10}
categories          graphics science
license             BSD
maintainers         {mascguy @mascguy}

description         Open Source Computer Vision Library
long_description    OpenCV (Open Source Computer Vision Library) is an \
                    open source computer vision and machine learning \
                    software library. OpenCV was built to provide a \
                    common infrastructure for computer vision \
                    applications and to accelerate the use of machine \
                    perception in the commercial products. Being a \
                    BSD-licensed product, OpenCV makes it easy for \
                    businesses to utilize and modify the code.
homepage            https://opencv.org

# OpenCV 4 fails to build on MacOS 10.8 and earlier, from 4.5.1 on.
# So for now, revert to 4.5.0 for older MacOS releases, until we can
# determine a formal fix.
if {${os.major} > 12} {
    set opencv_latest yes
} else {
    set opencv_latest no
}

# NOTE: Separate revisions maintained for Python subports, later in portfile
if {${opencv_latest}} {
    github.setup    opencv opencv 4.9.0
    # Change github.tarball_from to 'releases' or 'archive' next update
    github.tarball_from tarball
    revision        4
    epoch           1

    checksums-append \
                    ${distname}${extract.suffix} \
                    rmd160  ea327fb3ee68c75e55ab54cc185dced79d149cf5 \
                    sha256  6e7c0688d8dc9280e3fa84cd80c69825b3c4edceccc32fea924494300afc6370 \
                    size    92790830 \
} else {
    github.setup    opencv opencv 4.5.0
    # Change github.tarball_from to 'releases' or 'archive' next update
    github.tarball_from tarball
    revision        35

    checksums-append \
                    ${distname}${extract.suffix} \
                    rmd160  fadb405b7d38f829775da60a62d29368b2159ce4 \
                    sha256  03d9f7d777d8a62a5481934dbba2fd692b6cb43f1690a8546e45f9bdb1ee0863 \
                    size    90119002

    livecheck.type  none
}

master_sites        ${github.master_sites}:${github.project}
distfiles           [lindex ${distfiles} 0]:${github.project}
distname            ${my_name}-${version}
dist_subdir         ${my_name}

#------------------------------------------------------------------------------
# Python build support
#------------------------------------------------------------------------------
set default_python_branch \
                    3.13
set default_python_version \
                    [join [lrange [split ${default_python_branch} .] 0 1] ""]
set default_python_path \
                    ${prefix}/bin/python${default_python_branch}

#------------------------------------------------------------------------------
# Subport name used for staging files, etc.
#
# This is needed to support Python subports, whose names have no relation to
# the actual physical file layout.
#
# NOTE: Presently, 'parent_subport_name' matches 'name'. HOWEVER, this will
#   change once the various OpenCV-related ports are merged.
#------------------------------------------------------------------------------
set parent_subport_name \
                    ${my_name}

# recognize dylib as a valid library suffix
patchfiles-append   patch-dylib_suffix.diff

# use correct assembler syntax on ppc.
# this only adds a macro, no effect on other platforms.
patchfiles-append   patch-parallel_impl.cpp-cv_pause.diff

platform darwin {
    if {${opencv_latest}} {
        # Drop scrollwheel code, for 10.11 and earlier
        if {${os.major} < 16} {
            patchfiles-append \
                    patch-highgui-scrollwheel.diff
        }
    }
}

#worksrcdir          ${parent_subport_name}-${version}

# Claims to only need c++11 but actually uses c++14 features
# core/cvstd_wrapper.hpp:45:40: warning: variable templates are a C++14 extension [-Wc++14-extensions]
set cxx_standard    2014
compiler.cxx_standard \
                    ${cxx_standard}
cmake.set_cxx_standard \
                    yes

compiler.blacklist-append \
                    {clang < 900} \
                    {macports-clang-3.[0-9]} \
                    {macports-clang-[4-6].0}

depends_build-append \
                    port:cctools \
                    path:bin/pkg-config:pkgconfig \
                    port:python${default_python_version}

depends_lib-append  \
                    port:ade \
                    path:lib/libavcodec.dylib:ffmpeg \
                    port:imath \
                    path:include/turbojpeg.h:libjpeg-turbo \
                    port:libpng \
                    port:libquirc \
                    port:openjpeg \
                    port:openexr \
                    port:tiff \
                    port:webp \
                    port:zlib

#------------------------------------------------------------------------------
# CMake Variables
#
# When/if the CMake portgroup is extended to support more of these options,
# they can be replaced with those equivalents. For now, define them ahead of
# time, for use by configure arguments.
#------------------------------------------------------------------------------

# Define all of our base paths up-front
set opencv_install_prefix \
                    ${prefix}/libexec/${parent_subport_name}
set opencv_install_cmake \
                    ${opencv_install_prefix}/cmake
set opencv_install_include \
                    ${prefix}/include/${parent_subport_name}
set opencv_install_lib \
                    ${prefix}/lib/${parent_subport_name}

# Populate the few CMake options currently available
# TODO: Extend CMake portgroup to support more paths
cmake.install_prefix \
                    ${opencv_install_prefix}
cmake_share_module_dir \
                    ${opencv_install_cmake}
cmake.install_rpath \
                    ${opencv_install_lib}

configure.args-append \
                    -DENABLE_CONFIG_VERIFICATION:BOOL=OFF \
                    \
                    -DOPENCV_CONFIG_INSTALL_PATH=${opencv_install_cmake} \
                    -DOPENCV_BIN_INSTALL_PATH=${opencv_install_prefix}/bin \
                    -DOPENCV_SETUPVARS_INSTALL_PATH=${opencv_install_prefix}/scripts \
                    -DOPENCV_SBIN_INSTALL_PATH=${opencv_install_prefix}/sbin \
                    -DOPENCV_JAR_INSTALL_PATH=${opencv_install_prefix}/java/jar \
                    -DOPENCV_JNI_INSTALL_PATH=${opencv_install_prefix}/java/jni \
                    -DOPENCV_JNI_BIN_INSTALL_PATH=${opencv_install_prefix}/java/jni \
                    -DOPENCV_TEST_INSTALL_PATH=${opencv_install_prefix}/test/bin \
                    -DOPENCV_TEST_DATA_PATH=${opencv_install_prefix}/test/data \
                    -DOPENCV_SAMPLES_BIN_INSTALL_PATH=${opencv_install_prefix}/share/samples/bin \
                    -DOPENCV_SAMPLES_SRC_INSTALL_PATH=${opencv_install_prefix}/share/samples/src \
                    -DOPENCV_OTHER_INSTALL_PATH=${opencv_install_prefix}/share/data \
                    -DOPENCV_DOC_INSTALL_PATH=${opencv_install_prefix}/share/doc \
                    -DOPENCV_LICENSES_INSTALL_PATH=${opencv_install_prefix}/share/license \
                    -DOPENCV_INCLUDE_INSTALL_PATH=${opencv_install_include} \
                    -DOPENCV_LIB_INSTALL_PATH=${opencv_install_lib} \
                    -DOPENCV_3P_LIB_INSTALL_PATH=${opencv_install_lib}/3rdparty \
                    -DOPENCV_LIB_ARCHIVE_INSTALL_PATH=${opencv_install_lib}/static \
                    -DCMAKE_INSTALL_LIBEXECDIR=${opencv_install_prefix} \
                    -DCMAKE_INSTALL_BINDIR=${opencv_install_prefix}/bin \
                    -DCMAKE_INSTALL_SBINDIR=${opencv_install_prefix}/sbin \
                    -DCMAKE_INSTALL_SHAREDIR=${opencv_install_prefix}/share \
                    -DCMAKE_INSTALL_INCLUDEDIR=${opencv_install_include} \
                    -DCMAKE_INSTALL_LIBDIR=${opencv_install_lib} \
                    -DCMAKE_INSTALL_NAME_DIR=${opencv_install_lib} \
                    \
                    -DWITH_ADE:BOOL=ON \
                    -Dade_DIR:PATH=${prefix}/share/ade/ \
                    \
                    -DBUILD_WITH_DEBUG_INFO:BOOL=OFF \
                    -DHAVE_CXX11:BOOL=ON \
                    -DENABLE_CXX11:BOOL=ON \
                    -DENABLE_PIC:BOOL=OFF \
                    -DBUILD_SHARED_LIBS:BOOL=ON \
                    -DBUILD_opencv_apps:BOOL=ON \
                    -DBUILD_DOCS:BOOL=OFF \
                    -DBUILD_EXAMPLES:BOOL=OFF \
                    -DINSTALL_C_EXAMPLES:BOOL=ON \
                    -DINSTALL_PYTHON_EXAMPLES:BOOL=ON \
                    -DBUILD_TESTS:BOOL=OFF \
                    -DBUILD_PERF_TESTS:BOOL=OFF \
                    \
                    -DENABLE_CCACHE:BOOL=OFF \
                    -DBUILD_JAVA:BOOL=OFF \
                    -DENABLE_LTO:BOOL=OFF \
                    -DENABLE_THIN_LTO:BOOL=OFF \
                    -DENABLE_PRECOMPILED_HEADERS:BOOL=ON \
                    \
                    -DOPENCV_ENABLE_NONFREE:BOOL=OFF \
                    -DOPENCV_FORCE_3RDPARTY_BUILD:BOOL=OFF \
                    \
                    -DBUILD_ZLIB:BOOL=OFF \
                    -DBUILD_TIFF:BOOL=OFF -DWITH_TIFF:BOOL=ON \
                    -DBUILD_JASPER:BOOL=OFF -DWITH_JASPER:BOOL=OFF \
                    -DBUILD_JPEG:BOOL=OFF -DWITH_JPEG:BOOL=ON \
                    -DBUILD_OPENJPEG:BOOL=OFF -DWITH_OPENJPEG:BOOL=ON \
                    -DBUILD_PNG:BOOL=OFF -DWITH_PNG:BOOL=ON \
                    -DBUILD_OPENEXR:BOOL=OFF -DWITH_OPENEXR:BOOL=ON \
                    -DBUILD_WEBP:BOOL=OFF -DWITH_WEBP:BOOL=ON \
                    -DBUILD_TBB:BOOL=OFF -DWITH_TBB:BOOL=OFF \
                    -DBUILD_FFMPEG:BOOL=OFF -DWITH_FFMPEG:BOOL=ON \
                    \
                    -DWITH_OPENCL:BOOL=OFF \
                    -DWITH_OPENCL_SVM:BOOL=OFF \
                    -DWITH_OPENCLAMDFFT:BOOL=OFF \
                    -DWITH_OPENCLAMDBLAS:BOOL=OFF \
                    \
                    -DWITH_LAPACK:BOOL=ON \
                    \
                    -DBUILD_IPP_IW:BOOL=OFF \
                    -DBUILD_ITT:BOOL=OFF \
                    -DWITH_1394:BOOL=OFF \
                    -DWITH_AVFOUNDATION:BOOL=ON \
                    -DWITH_VTK:BOOL=OFF \
                    -DWITH_EIGEN:BOOL=OFF \
                    -DWITH_GSTREAMER:BOOL=OFF \
                    -DWITH_GTK:BOOL=OFF \
                    -DWITH_IPP:BOOL=OFF \
                    -DWITH_HALIDE:BOOL=OFF \
                    -DWITH_VULKAN:BOOL=OFF \
                    -DWITH_INF_ENGINE:BOOL=OFF \
                    -DWITH_OPENGL:BOOL=OFF \
                    -DWITH_OPENVX:BOOL=OFF \
                    -DWITH_OPENNI:BOOL=OFF \
                    -DWITH_OPENNI2:BOOL=OFF \
                    -DWITH_GDCM:BOOL=OFF \
                    -DWITH_PVAPI:BOOL=OFF \
                    -DWITH_ARAVIS:BOOL=OFF \
                    -DWITH_QT:BOOL=OFF \
                    -DWITH_HPX:BOOL=OFF \
                    -DWITH_OPENMP:BOOL=OFF \
                    -DWITH_PTHREADS_PF:BOOL=ON \
                    -DWITH_XIMEA:BOOL=OFF \
                    \
                    -DWITH_LIBREALSENSE:BOOL=OFF \
                    -DWITH_VA:BOOL=OFF \
                    -DWITH_VA_INTEL:BOOL=OFF \
                    -DWITH_MFX:BOOL=OFF \
                    -DWITH_GDAL:BOOL=OFF \
                    -DWITH_GPHOTO2:BOOL=OFF \
                    -DWITH_ITT:BOOL=OFF \
                    -DWITH_PROTOBUF:BOOL=OFF \
                    -DWITH_IMGCODEC_HDR:BOOL=ON \
                    -DWITH_IMGCODEC_SUNRASTER:BOOL=ON \
                    -DWITH_IMGCODEC_PXM:BOOL=ON \
                    -DWITH_IMGCODEC_PFM:BOOL=ON \
                    -DWITH_QUIRC:BOOL=OFF \
                    \
                    -DHAVE_QUIRC:BOOL=ON \
                    -DHAVE_COCOA:BOOL=ON \
                    \
                    -DBUILD_opencv_aruco:BOOL=ON \
                    \
                    -DBUILD_opencv_python2:BOOL=OFF \
                    -DBUILD_opencv_python3:BOOL=OFF \
                    -DOPENCV_PYTHON_SKIP_DETECTION:BOOL=OFF \
                    -DPYTHON_EXECUTABLE:FILEPATH=${default_python_path} \
                    -DPYTHON_DEFAULT_EXECUTABLE:FILEPATH=${default_python_path}

if {${name} eq ${subport}} {
    # generate pkg-config file
     configure.args-append \
                    -DOPENCV_GENERATE_PKGCONFIG=YES
}

universal_variant   no

# PCH broken when universal
# Keep around, for when universal support is fixed/enabled
if {![info exists universal_possible]} {
    set universal_possible [expr {${os.universal_supported} && [llength ${configure.universal_archs}] >= 2}]
}
if {${universal_possible} && [variant_isset universal]} {
    configure.args-replace \
                    -DENABLE_PRECOMPILED_HEADERS:BOOL=ON \
                    -DENABLE_PRECOMPILED_HEADERS:BOOL=OFF
}

if { ${configure.ccache} } {
    configure.args-replace \
                    -DENABLE_CCACHE:BOOL=OFF \
                    -DENABLE_CCACHE:BOOL=ON
}

platform darwin {
    configure.args-append \
                    -DZLIB_LIBRARY:FILEPATH=${prefix}/lib/libz.dylib

    # do not opportunistically find other LAPACK implementations
    # see cmake/OpenCVFindLAPACK.cmake
    configure.args-append \
                    -DLAPACK_IMPL=Apple \
                    -DLAPACK_LIBRARIES="-framework Accelerate" \
                    -DLAPACK_CBLAS_H=Accelerate/Accelerate.h \
                    -DLAPACK_LAPACKE_H=Accelerate/Accelerate.h

    # Do not prohibit GTK:
    patchfiles-append patch-expose-gtk-choice.diff

    if { ${configure.build_arch} in [list i386 ppc] || (${universal_possible} && [variant_isset universal] &&
        ("i386" in ${configure.universal_archs} || "ppc" in ${configure.universal_archs}))} {
        # The Accelerate ABI requires 32-bit signed integers.
        # In clapack.h, __CLPK_integer is a typedef for either
        #   int (64-bit) or long int (32-bit).
        # opencv only uses ints.
        # Casting between pointers is never recommended, but
        #   int and long int should have the same representations
        #   on 32-bit systems.
        patchfiles-append patch-32bit_accelerate.diff
    }

    # the AVFoundation backend is failing to build up to 10.8
    # it might be possible to work around or repair this on 10.7 and 10.8
    # there as a qtkit video implementation prior to the AVFoundation version
    # that is about 2016 vintage. This could possibly be resuscitated if there
    # is motivation or interest in so doing
    if {${os.major} < 13} {
        ui_debug "AVFoundation not supported on this MacOS release; disabling"
        configure.args-replace \
                    -DWITH_AVFOUNDATION:BOOL=ON \
                    -DWITH_AVFOUNDATION:BOOL=OFF
    }

    # Isolate PowerPC-specific fixes.
    platform darwin powerpc {
        # For now just disable, it is broken.
        # window_cocoa.mm: error: expected ';' before 'in'
        # window_cocoa.mm: error: no matching function for call to 'max(CGFloat&, double)'
        # window_cocoa.mm: error: ivar 'image' used by '@synthesize' declaration must be an existing ivar
        # TODO: forward-port working code from opencv3.
        patchfiles-append \
            patch-disable-cocoa.diff

        # The code uses libdispatch unconditionally.
        depends_lib-append \
            port:libdispatch-legacy
        configure.cppflags-prepend \
            -I${prefix}/libexec/dispatch/usr/include
        configure.ldflags-append \
            ${prefix}/libexec/dispatch/usr/lib/libdispatch.a

        # There are invalid conversion errors in non-Eigen fallbacks which require -fpermissive:
        # essential_solver.cpp: error: invalid conversion from 'int*' to '__CLPK_integer*' {aka 'long int*'} [-fpermissive]
        # Unfortunately, enabling Eigen variant introduces another error:
        # /System/Library/Frameworks/vecLib.framework/Headers/vecLibTypes.h:69:26:
        # error: two or more data types in declaration of 'vBool32'
        configure.cxxflags-append \
            -fpermissive

        # Cocoa is broken, enable at least GTK:
        default_variants-append \
            +gtk3
    }
}

# Python Bindings
set python_branches {3.9 3.10 3.11 3.12 3.13}
foreach python_branch ${python_branches} {
    set python_version   [join [lrange [split ${python_branch} .] 0 1] ""]
    set python_path      ${prefix}/bin/python${python_branch}
    set python_framework ${frameworks_dir}/Python.framework/Versions/${python_branch}

    subport py${python_version}-${name} {
        # NOTE: Only rev-bump subports, for major changes/additions
        if {${opencv_latest}} {
            revision 1
        } else {
            revision 18
        }

        conflicts-append \
                    py${python_version}-opencv3 \
                    py${python_version}-opencv3-devel \
                    py${python_version}-opencv4-devel

        depends_build-delete \
                    port:python${default_python_version}
        depends_lib-append \
                    port:${name} \
                    port:py${python_version}-numpy \
                    port:python${python_version}

        configure.args-replace \
                    -DBUILD_opencv_python3:BOOL=OFF \
                    -DBUILD_opencv_python3:BOOL=ON
        configure.args-replace \
                    -DBUILD_opencv_apps:BOOL=ON \
                    -DBUILD_opencv_apps:BOOL=OFF
        configure.args-replace \
                    -DBUILD_opencv_aruco:BOOL=ON \
                    -DBUILD_opencv_aruco:BOOL=OFF

        configure.args-replace \
                    -DPYTHON_EXECUTABLE:FILEPATH=${default_python_path} \
                    -DPYTHON_EXECUTABLE:FILEPATH=${python_path}
        configure.args-replace \
                    -DPYTHON_DEFAULT_EXECUTABLE:FILEPATH=${default_python_path} \
                    -DPYTHON_DEFAULT_EXECUTABLE:FILEPATH=${python_path}
        configure.args-append \
                    -DPYTHON3_EXECUTABLE=${python_path} \
                    -DPYTHON3_LIBRARY=${python_framework}/lib/libpython${python_branch}.dylib \
                    -DPYTHON3_INCLUDE_DIR=${python_framework}/Headers \
                    -DPYTHON3_PACKAGES_PATH=${python_framework}/lib/python${python_branch}/site-packages

        # Deconflict with parent port contents
        post-destroot {
            ui_debug "${subport}: python subport: removing files unrelated to Python bindings"
            foreach f [exec port -q contents ${name}] {
                delete ${destroot}${f}
            }
        }
    }
}

if {${name} eq ${subport}} {
    notes \
        "* ${subport} binaries are now prefixed with '${my_name}_', to prevent conflicts\
        with other OpenCV-related ports." \
        "* Python bindings are now implemented via subports 'pyXX-${subport}',\
        to support multiple Python versions side-by-side."

    variant eigen description {Enable eigen support} {
        depends_lib-append \
                    path:share/pkgconfig/eigen3.pc:eigen3
        configure.args-replace \
                    -DWITH_EIGEN:BOOL=OFF \
                    -DWITH_EIGEN:BOOL=ON
        configure.args-append \
                    -DEIGEN_INCLUDE_PATH:PATH=${prefix}/include/eigen3
    }

    variant gdal description {Include GDAL support} {
        depends_lib-append \
                    port:gdal
        configure.args-replace \
                    -DWITH_GDAL:BOOL=OFF \
                    -DWITH_GDAL:BOOL=ON
    }

    variant nonfree description {Include nonfree algorithms} {
        configure.args-replace \
                    -DOPENCV_ENABLE_NONFREE:BOOL=OFF \
                    -DOPENCV_ENABLE_NONFREE:BOOL=ON
    }

    variant opencl description {Enable OpenCL support} {
        pre-configure {
            if {${os.platform} eq "darwin" && ${os.major} < 11} {
                ui_error "The OpenCL variant only works with OS X 10.7 Lion or later."
                return -code error "incompatible OS X version"
            }
        }
        configure.args-replace \
                    -DWITH_OPENCL:BOOL=OFF \
                    -DWITH_OPENCL:BOOL=ON
    }

    variant openmp description {Include OpenMP support} {
        compiler.openmp_version \
                    4.0
        configure.args-replace \
                    -DWITH_OPENMP:BOOL=OFF \
                    -DWITH_OPENMP:BOOL=ON
    }

    variant openni description {Enable OpenNI support} {
        depends_lib-append \
                    port:openni
        configure.args-replace  \
                    -DWITH_OPENNI:BOOL=OFF \
                    -DWITH_OPENNI:BOOL=ON
        configure.args-append \
                    -DOPENNI_INCLUDE_DIR:PATH=${prefix}/include/ni \
                    -DOPENNI_LIB_DIR:PATH=${prefix}/lib
    }

    variant contrib description {Build OpenCV with extra modules} {
        master_sites-append \
                    https://github.com/${github.author}/${github.project}_contrib/tarball/${version}:${github.project}_contrib
        distfiles-append \
                    ${github.project}_contrib-${version}${extract.suffix}:${github.project}_contrib

        if {${opencv_latest}} {
            checksums-append \
                    ${github.project}_contrib-${version}${extract.suffix} \
                    rmd160  96e6498f333df0de8b0c43a5778ef2341fa32129 \
                    sha256  492c11ac8245d0d0daa5d616d595e34c1db762af004ed3f90ef9d4acde434ec8 \
                    size    59804362 \
        } else {
            checksums-append \
                    ${github.project}_contrib-${version}${extract.suffix} \
                    rmd160  179e9842172a67db96c976e6ab4944b826835970 \
                    sha256  f16aa7c7960e6a0d855b681d19437d4e05bc8abd6af5adf5ab86f37d1019d663 \
                    size    60120338
        }

        configure.args-delete \
                    -DWITH_PROTOBUF:BOOL=OFF
        configure.args-append \
                    -DBUILD_PROTOBUF:BOOL=OFF \
                    -DWITH_PROTOBUF:BOOL=ON \
                    -DWITH_TESSERACT:BOOL=OFF \
                    -DWITH_OGRE:BOOL=OFF

        # Regenerate protobuf files, if stale
        configure.args-append \
                    -DPROTOBUF_UPDATE_FILES:BOOL=ON

        depends_lib-append \
                    port:ceres-solver \
                    port:double-conversion \
                    port:gflags \
                    port:google-glog \
                    port:hdf5 \
                    port:protobuf3-cpp

        extract.only \
                    ${github.project}-${version}${extract.suffix} \
                    ${github.project}_contrib-${version}${extract.suffix}

        post-extract {
            move_gh_repo ${github.author}-${github.project}-* ${distname}
            move_gh_repo ${github.author}-${github.project}_contrib-* ${github.project}_contrib-${version}
        }

        pre-patch {
            delete ${worksrcpath}/${github.project}_contrib
            ln -s ${workpath}/${github.project}_contrib-${version} ${worksrcpath}/${github.project}_contrib
        }

        # Allow enabling/disabling Ogre, via CMake flag 'WITH_OGRE'
        patchfiles-append \
                    patch-contrib-ovis-ogre.diff

        configure.args-append \
                    -DOPENCV_EXTRA_MODULES_PATH=${worksrcpath}/${github.project}_contrib/modules

        # dnn_modern:
        master_sites-append     https://github.com/tiny-dnn/tiny-dnn/archive/:tiny-dnn

        distfiles-append        v1.0.0a3.tar.gz:tiny-dnn

        checksums-append        v1.0.0a3.tar.gz \
                                rmd160  1d44a0f0c3b0a6f31a333afdfb246526c42336ad \
                                sha256  e2c61ce8c5debaa644121179e9dbdcf83f497f39de853f8dd5175846505aa18b \
                                size    12885646

        configure.args-append  -DOPENCV_TINY_DNN_URL=file://${distpath}/

        # xfeatures2d/boostdesc:
        master_sites-append    https://raw.githubusercontent.com/opencv/opencv_3rdparty/34e4206aef44d50e6bbcd0ab06354b52e7466d26:boostdesc

        distfiles-append   boostdesc_bgm.i:boostdesc \
                           boostdesc_bgm_bi.i:boostdesc \
                           boostdesc_bgm_hd.i:boostdesc \
                           boostdesc_binboost_064.i:boostdesc \
                           boostdesc_binboost_128.i:boostdesc \
                           boostdesc_binboost_256.i:boostdesc \
                           boostdesc_lbgm.i:boostdesc

        checksums-append   boostdesc_bgm.i \
                               rmd160 a090147b1ff8cdb23cbb3898cb5cd9cdb181f000 \
                               sha256 c441a027f15b9b8ff6c006b0775cd86781169ebd5b6257a94bdce668010d5df5 \
                               size 14852 \
                           boostdesc_bgm_bi.i \
                               rmd160 a4f858f29a638286065aba9a7cbddf25323b35b2 \
                               sha256 3d54b2934f0de963abbce985da303254ee78eebd05eb2af517105f9b0e670566 \
                               size 14864 \
                           boostdesc_bgm_hd.i \
                               rmd160 92cadac9bd2c73ffa014fb552480ee33bf252568 \
                               sha256 4b068631287f9914c3aa5bbdab76368b01493cea494ab47f7a70d2fa4f1c3e1b \
                               size 7832 \
                           boostdesc_binboost_064.i \
                               rmd160 6567930c5f8839bb8c877201ffed07b91edbdec3 \
                               sha256 090c9cc50663df3a91f2d7c704fa664493c96c39749b4cee9ebc29a20eb680d2 \
                               size 138093 \
                           boostdesc_binboost_128.i \
                               rmd160 5c9f9171ecb5100ab7390119a02d7dd072dd35de \
                               sha256 8f3622c1f3c0a14b1f1b7b955c518e97f7ccd0e9796e1dd9e7a975aad9bb2a22 \
                               size 275322 \
                           boostdesc_binboost_256.i \
                               rmd160 27a39257b04cad5143f369fccbea5dd495c219c0 \
                               sha256 a1c778059332b4904c9ce30ed888e9dd2e44621579362e6deb20ef4f4b0cf819 \
                               size 549754 \
                           boostdesc_lbgm.i \
                               rmd160 35efe18cb9449a41af2166255a23e29822aae4e9 \
                               sha256 42f6091199242fb6d96aec2f25644cd6f5e5f2fdddd1720f3422282e88cf3cd8 \
                               size 426280

        configure.args-append  -DOPENCV_BOOSTDESC_URL=file://${distpath}/

        #xfeatures2d/vggdesc:
        master_sites-append    https://raw.githubusercontent.com/opencv/opencv_3rdparty/fccf7cd6a4b12079f73bbfb21745f9babcd4eb1d:vggdesc

        distfiles-append   vgg_generated_48.i:vggdesc \
                           vgg_generated_64.i:vggdesc \
                           vgg_generated_80.i:vggdesc \
                           vgg_generated_120.i:vggdesc

        checksums-append   vgg_generated_48.i \
                               rmd160 fdb2d976ec287c4989e9d3b6f95104a0bef9c9a4 \
                               sha256 71274a67ab0896865e27de830eda0065e387d75fe071dab4a887e2430ccb8a35 \
                               size 773330 \
                           vgg_generated_64.i \
                               rmd160 1e4cbba9038c165d53d5e9c9bdd299cde54dbd3a \
                               sha256 2746c272af82b9a839a69de151c262be55d9ef8464b268001c33f99f9f5cebbe \
                               size 915012 \
                           vgg_generated_80.i \
                               rmd160 d950552c95026ae80c6fe5b9e30037104081cca2 \
                               sha256 08fbc8cb1686b6c45032a08c98f3857ead4755116410e16c68713f4dea4cbf5c \
                               size 1012932 \
                           vgg_generated_120.i \
                               rmd160 a8e2a8e88102871c4e7d75c1f8a474a006e90aaa \
                               sha256 f05e7eb7183ecbc788bfc26cea9db7dad8585178175411b93e444acdc8fb2048 \
                               size 1257733

        configure.args-append  -DOPENCV_VGGDESC_URL=file://${distpath}/

        #face:
        master_sites-append    https://raw.githubusercontent.com/opencv/opencv_3rdparty/8afa57abc8229d611c4937165d20e2a2d9fc5a12:face

        distfiles-append   face_landmark_model.dat:face

        checksums-append   face_landmark_model.dat \
                           rmd160 3a4e4a80f2c74a6af2b36b4d74e3c6d59c347ce0 \
                           sha256 eeab592db2861a6c94d592a48456cf59945d31483ce94a6bc4d3a4e318049ba3 \
                           size 72368157

        configure.args-append  -DOPENCV_FACE_ALIGNMENT_URL=file://${distpath}/

        # wechat_qrcode
        master_sites-append    https://raw.githubusercontent.com/WeChatCV/opencv_3rdparty/a8b69ccc738421293254aec5ddb38bd523503252:wechat_qrcode

        distfiles-append   detect.caffemodel:wechat_qrcode \
                           detect.prototxt:wechat_qrcode \
                           sr.caffemodel:wechat_qrcode \
                           sr.prototxt:wechat_qrcode

        checksums-append   detect.caffemodel \
                           rmd160 d8feee1ac643117667e903f7e905b55589a545f3 \
                           sha256 cc49b8c9babaf45f3037610fe499df38c8819ebda29e90ca9f2e33270f6ef809 \
                           size 965430 \
                           detect.prototxt \
                           rmd160 948db814fd70c5064f494adab538543d215f8efb \
                           sha256 e8acfc395caf443a47f15686a9b9207b36cb8f7e6ceb8fbaf6466665e68a9466 \
                           size 42656 \
                           sr.caffemodel \
                           rmd160 04e3e208009f753afc6703f6327d34ed16f7ea95 \
                           sha256 e5d36889d8e6ef2f1c1f515f807cec03979320ac81792cd8fb927c31fd658ae3 \
                           size 23929 \
                           sr.prototxt \
                           rmd160 74ea1bccc1083ff54c081c3f998de615338e8f05 \
                           sha256 8ae41acba97e8b4a8e741ee350481e49b8e01d787193f470a4c95ee1c02d5b61 \
                           size 5984

        configure.args-append  -DOPENCV_WECHAT_QRCODE_URL=file://${distpath}/
    }

    variant qt4 conflicts qt5 description {Build with Qt4 Backend support} {
        PortGroup   qt4 1.0

        configure.args-replace \
                    -DWITH_QT:BOOL=OFF \
                    -DWITH_QT=4
    }

    variant qt5 conflicts qt4 description {Build with Qt5 Backend support} {
        PortGroup   qt5 1.0

        configure.args-replace \
                    -DWITH_QT:BOOL=OFF \
                    -DWITH_QT=5
    }

    variant gtk3 description {Build with GTK-3 Backend support} {
        depends_lib-append \
                    path:lib/pkgconfig/gtk+-3.0.pc:gtk3

        configure.args-replace \
                    -DWITH_GTK:BOOL=OFF \
                    -DWITH_GTK:BOOL=ON
    }

    variant java description {Add Java bindings} {
        PortGroup   java 1.0

        # OpenCV appears to support older Java versions,
        # and MacPorts users have requested Java 8 support:
        # see https://trac.macports.org/ticket/60193
        java.version    1.6+
        # Use latest LTS Java version as fallback
        java.fallback   openjdk11
        depends_build-append \
                    port:apache-ant
        configure.args-replace \
                    -DBUILD_JAVA:BOOL=OFF \
                    -DBUILD_JAVA:BOOL=ON
    }

    variant tbb description {Use Intel TBB} {
        depends_lib-append \
                    port:tbb
        configure.args-replace \
                    -DWITH_TBB:BOOL=OFF \
                    -DWITH_TBB:BOOL=ON
        configure.args-append \
                    -DHAVE_TBB=ON

        # NOTE: TBB 2020 (tbb port) doesn't provide cmake package and to prevent
        # from pickinkg OneTBB it uses TBBROO env to verify that cmake picks the right one
        configure.env-append \
                    TBBROOT=${prefix}/libexec/tbb
        configure.cflags-prepend \
                    -I${prefix}/libexec/tbb/include
        configure.cxxflags-prepend \
                    -I${prefix}/libexec/tbb/include
        configure.ldflags-prepend \
                    -L${prefix}/libexec/tbb/lib
    }

    variant vtk description {Include VTK support} {
        depends_lib-append \
                    port:vtk
        configure.args-replace \
                    -DWITH_VTK:BOOL=OFF \
                    -DWITH_VTK:BOOL=ON
    }

    variant tests description {Enable tests} {
        configure.args-replace \
                    -DBUILD_TESTS:BOOL=OFF \
                    -DBUILD_TESTS:BOOL=ON

        configure.args-replace \
                    -DBUILD_PERF_TESTS:BOOL=OFF \
                    -DBUILD_PERF_TESTS:BOOL=ON

        test.run        yes
        test.target     test
    }
}

# NOTE: Variant 'debug' is the only one that should be shared with Python subports
variant debug description {Build with debugging info} {
    configure.args-replace \
                    -DBUILD_WITH_DEBUG_INFO:BOOL=OFF \
                    -DBUILD_WITH_DEBUG_INFO:BOOL=ON
}

proc opencv_move_binaries {p_bin_main_dir p_bin_port_dir} {
    set bin_main_files \
        [glob -nocomplain -type f \
            -directory ${p_bin_main_dir} \
            *]
    ui_debug "opencv_move_binaries: bin_main_files: ${bin_main_files}"

    foreach f ${bin_main_files} {
        set fn [file tail ${f}]
        set f_dest "${p_bin_port_dir}/${fn}"
        ui_debug "opencv_move_binaries: moving file: ${f} -> ${f_dest}"
        move ${f} ${f_dest}
    }

    return 0
}

proc opencv_soft_link_binaries {p_bin_main_dir p_bin_port_dir p_destroot p_prefix p_subport} {
    set bin_prefix_old "opencv_"
    set bin_prefix_new "${p_subport}_"
    set bin_port_files \
        [glob -nocomplain -type f \
            -directory ${p_bin_port_dir} \
            *]
    ui_debug "opencv_soft_link_binaries: bin_port_files: ${bin_port_files}"

    # Links: Remove prefix 'opencv_', if any; add prefix '<subport>_'.
    foreach f ${bin_port_files} {
        set fn [file tail ${f}]
        set fn_new \
            [regsub ***=${bin_prefix_old} ${fn} ""]
        set f_dest \
            [regsub ***=${p_destroot} ${f} ""]
        set f_link \
            "${p_bin_main_dir}/${bin_prefix_new}${fn_new}"
        ui_debug "opencv_soft_link_binaries: soft-linking file: ${f_link} -> ${f_dest}"
        ln -s ${f_dest} ${f_link}
    }

    return 0
}

proc opencv_fix_pkgconfig {p_destroot p_prefix p_parent_subport_name} {
    set pkgconfig_file \
        "${p_destroot}${p_prefix}/lib/${p_parent_subport_name}/pkgconfig/opencv4.pc"

    if {[file exists ${pkgconfig_file}]} {
        ui_debug "opencv_fix_pkgconfig: fixing pkgconfig file ${pkgconfig_file}"

        # Fix paths
        reinplace "s|\$\{exec_prefix\}\/||g" \
            ${pkgconfig_file}
        reinplace "s|\$\{prefix\}\/||g" \
            ${pkgconfig_file}
    }

    return 0
}

proc opencv_post_destroot {} {
    global destroot
    global prefix
    global subport
    global parent_subport_name

    opencv_fix_pkgconfig \
        ${destroot} \
        ${prefix} \
        ${parent_subport_name}

    set bin_main_dir \
                    "${destroot}${prefix}/bin"
    set bin_port_dir \
                    "${destroot}${prefix}/libexec/${parent_subport_name}/bin"

    # While the various configure-related options should catch everything, one or more
    # files may be missed. If so, ensure they're moved to the opencv4 bin area.
    opencv_move_binaries \
                    ${bin_main_dir} \
                    ${bin_port_dir}

    # Create soft links for binaries, each prefixed with '<parent_subport_name>_'.
    opencv_soft_link_binaries \
                    ${bin_main_dir} \
                    ${bin_port_dir} \
                    ${destroot} \
                    ${prefix} \
                    ${parent_subport_name}
}

# modify from _resources/port1.0/group/github-1.0.tcl to avoid file tag issue
proc move_gh_repo {repo_dir_patt new_name} {
    global distfiles workpath worksrcpath
    if {(![file exists ${worksrcpath}] || ![file exists ${workpath}/${new_name}]) && \
            [llength ${distfiles}] > 0 && \
            [llength [glob -nocomplain ${workpath}/*]] > 0} {
        if {[file exists [glob -nocomplain ${workpath}/${repo_dir_patt}]] && \
            [file isdirectory [glob -nocomplain ${workpath}/${repo_dir_patt}]]} {
            move [glob ${workpath}/${repo_dir_patt}] ${workpath}/${new_name}
        } else {
            # tarball is not "${repo_dir_patt}"
            ui_error "\n\nGitHub Extract Error: \${worksrcpath} does not exist after extracting\
                distfiles. This might indicate that the author or project is different than set\
                in the Portfile due to a rename at GitHub. Please examine the extracted directory\
                in ${workpath} and try to correct the Portfile by either changing the author or\
                project or adding the worksrcdir option with the correct directory name.\n"
            return -code error "Unexpected github tarball extract."
        }
    }
}

post-extract {
    move_gh_repo ${github.author}-${github.project}-* ${distname}
}

post-destroot {
    ui_debug "${subport}: phase post-destroot running"
    opencv_post_destroot
}

if {[string match "py*" ${subport}]} {
    livecheck.type  none
}