cmake_minimum_required(VERSION 3.18)
project(qtexengine)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTOUIC ON)

set(QT_MODULES Core PrintSupport Widgets)
if (${PREFER_QT})
    set(V ${PREFER_QT})
    find_package(Qt${V} COMPONENTS ${QT_MODULES} REQUIRED)
else ()
    find_package(Qt6 COMPONENTS ${QT_MODULES} QUIET)
    if (${Qt6_FOUND})
        set(V 6)
    else ()
        find_package(Qt5 COMPONENTS ${QT_MODULES} REQUIRED)
        set(V 5)
    endif ()
endif ()

# if this project is not configured as a subproject
if (CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
    message(STATUS "Found Qt: ${Qt${V}Core_VERSION}")
    foreach (module IN LISTS QT_MODULES)
        get_target_property(module_path Qt${V}::${module} LOCATION)
        message(STATUS "Found ${module}: ${module_path}")
    endforeach ()
endif ()

set(SOURCES
    src/QTeXPaintDevice.cpp
    src/QTeXPaintEngine.cpp)

set(HEADERS
    include/qtexengine_compat.h
    include/QTeXEngine.h)

if (MSVC)
    add_compile_options($<$<CXX_COMPILER_ID:MSVC>:/MP>)
endif ()

add_library(qtexengine_static STATIC ${SOURCES} ${HEADERS})
if (MSVC AND BUILD_SHARED_LIBS)
    add_definitions(-DQTEXENGINE_EXPORTS=1)
    set_target_properties(qtexengine_static PROPERTIES OUTPUT_NAME "qtexengine_static")
else ()
    set_target_properties(qtexengine_static PROPERTIES OUTPUT_NAME "qtexengine")
endif ()
target_include_directories(qtexengine_static PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
foreach (module IN LISTS QT_MODULES)
    target_link_libraries(qtexengine_static PUBLIC Qt${V}::${module})
endforeach ()

if (BUILD_SHARED_LIBS)
    add_library(qtexengine_shared SHARED $<TARGET_OBJECTS:qtexengine_static>)
    set_target_properties(qtexengine_shared PROPERTIES OUTPUT_NAME "qtexengine")
    target_include_directories(qtexengine_shared PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
    foreach (module IN LISTS QT_MODULES)
        target_link_libraries(qtexengine_shared PUBLIC Qt${V}::${module})
    endforeach ()
endif ()

# if this project is not configured as a subproject
if (CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
    include(GNUInstallDirs)
    install(TARGETS qtexengine_static
        LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})
    if (BUILD_SHARED_LIBS)
        install(TARGETS qtexengine_shared
            LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})
    endif ()
    install(FILES ${HEADERS}
        DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/qtexengine)
endif ()
