cmake_minimum_required(VERSION 3.21)

# Single source of truth for the version: the macros in SDL2_gfxPrimitives.h.
file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/SDL2_gfxPrimitives.h" _sdl2gfx_version_lines
     REGEX "^#define[ \t]+SDL2_GFXPRIMITIVES_(MAJOR|MINOR|MICRO)[ \t]+[0-9]+")
foreach(_part MAJOR MINOR MICRO)
    string(REGEX REPLACE ".*SDL2_GFXPRIMITIVES_${_part}[ \t]+([0-9]+).*" "\\1" _sdl2gfx_${_part} "${_sdl2gfx_version_lines}")
endforeach()

project(SDL2_gfx
    VERSION ${_sdl2gfx_MAJOR}.${_sdl2gfx_MINOR}.${_sdl2gfx_MICRO}
    DESCRIPTION "Graphics primitives, rotozoomer, framerate control and image filters for SDL2"
    HOMEPAGE_URL "https://github.com/ferzkopp/SDL2_gfx"
    LANGUAGES C)

include(GNUInstallDirs)
include(CMakePackageConfigHelpers)

set(SDL2GFX_SDL_REQUIRED_VERSION 2.0.18)

option(SDL2GFX_SHARED  "Build the shared SDL2_gfx library" ON)
option(SDL2GFX_STATIC  "Build the static SDL2_gfx library" OFF)
option(SDL2GFX_INSTALL "Generate install rules" ${PROJECT_IS_TOP_LEVEL})
option(SDL2GFX_DEMOS   "Build the interactive demo programs" ${PROJECT_IS_TOP_LEVEL})
option(SDL2GFX_TESTS   "Build the automated tests (CTest)" ${PROJECT_IS_TOP_LEVEL})
option(SDL2GFX_WERROR  "Treat compiler warnings as errors" OFF)
option(SDL2GFX_ANALYZE "Run the MSVC code analyzer (/analyze) on the library sources" OFF)
option(SDL2GFX_FUZZ    "Build libFuzzer targets; instruments everything with AddressSanitizer" OFF)
option(SDL2GFX_BENCH   "Build the benchmark program" ${PROJECT_IS_TOP_LEVEL})
option(SDL2GFX_DOCS    "Add the 'docs' target (Doxygen HTML) if Doxygen is found" ${PROJECT_IS_TOP_LEVEL})
option(SDL2GFX_LEGACY_COLOR_BYTE_ORDER
    "...Color functions decode the color in memory byte order (behavior up to 1.0.4) instead of 0xRRGGBBAA" OFF)

if(SDL2GFX_FUZZ)
    # Instrument the library and all executables (tests then also run under ASan).
    if(MSVC)
        add_compile_options(/fsanitize=address)
        add_link_options(/INCREMENTAL:NO)
    else()
        add_compile_options(-fsanitize=address,undefined -fno-omit-frame-pointer -fno-sanitize-recover=undefined)
        add_link_options(-fsanitize=address,undefined)
    endif()
endif()

if(NOT SDL2GFX_SHARED AND NOT SDL2GFX_STATIC)
    message(FATAL_ERROR "Enable at least one of SDL2GFX_SHARED or SDL2GFX_STATIC")
endif()

if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
    set(CMAKE_BUILD_TYPE RelWithDebInfo CACHE STRING "Build type" FORCE)
endif()

if(PROJECT_IS_TOP_LEVEL)
    # Executables and DLLs side by side so demos/tests run without PATH changes.
    set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin")
endif()
set(SDL2GFX_RUNTIME_DIR "${PROJECT_BINARY_DIR}/bin")

find_package(SDL2 ${SDL2GFX_SDL_REQUIRED_VERSION} CONFIG REQUIRED)
if(TARGET SDL2::SDL2)
    set(SDL2GFX_SDL_TARGET SDL2::SDL2)
else()
    set(SDL2GFX_SDL_TARGET SDL2::SDL2-static)
endif()

# Files that demos and tests need next to their executables: the SDL2 DLL (Windows) and the sample
# images. Copied by a single target to avoid parallel copies of the same files.
file(GLOB SDL2GFX_TEST_DATA CONFIGURE_DEPENDS "${PROJECT_SOURCE_DIR}/test/data/*.bmp")
set(_sdl2gfx_runtime_files ${SDL2GFX_TEST_DATA})
get_target_property(_sdl2gfx_sdl_type ${SDL2GFX_SDL_TARGET} TYPE)
if(WIN32 AND _sdl2gfx_sdl_type STREQUAL "SHARED_LIBRARY")
    list(APPEND _sdl2gfx_runtime_files "$<TARGET_FILE:${SDL2GFX_SDL_TARGET}>")
endif()
if(MSVC AND SDL2GFX_FUZZ)
    # MSVC AddressSanitizer runtime, so instrumented programs also start outside a VS dev shell.
    get_filename_component(_sdl2gfx_cl_dir "${CMAKE_C_COMPILER}" DIRECTORY)
    file(GLOB _sdl2gfx_asan_dll "${_sdl2gfx_cl_dir}/clang_rt.asan_dynamic-x86_64.dll")
    list(APPEND _sdl2gfx_runtime_files ${_sdl2gfx_asan_dll})
endif()
add_custom_target(sdl2gfx_runtime
    COMMAND ${CMAKE_COMMAND} -E make_directory "${SDL2GFX_RUNTIME_DIR}"
    COMMAND ${CMAKE_COMMAND} -E copy_if_different ${_sdl2gfx_runtime_files} "${SDL2GFX_RUNTIME_DIR}"
    COMMENT "Copying SDL2 runtime and sample images to ${SDL2GFX_RUNTIME_DIR}"
    VERBATIM)

set(SDL2GFX_PUBLIC_HEADERS
    SDL2_framerate.h
    SDL2_gfxPrimitives.h
    SDL2_imageFilter.h
    SDL2_rotozoom.h)
set(SDL2GFX_SOURCES
    SDL2_framerate.c
    SDL2_gfxPrimitives.c
    SDL2_gfxPrimitives_font.h
    SDL2_imageFilter.c
    SDL2_rotozoom.c)

# Warning and hardening flags shared by the library, tests and demos.
add_library(sdl2gfx_build_flags INTERFACE)
if(MSVC)
    target_compile_options(sdl2gfx_build_flags INTERFACE /W4 /sdl /guard:cf $<$<BOOL:${SDL2GFX_WERROR}>:/WX>)
    target_link_options(sdl2gfx_build_flags INTERFACE /guard:cf)
    target_compile_definitions(sdl2gfx_build_flags INTERFACE _CRT_SECURE_NO_WARNINGS)
else()
    target_compile_options(sdl2gfx_build_flags INTERFACE
        -Wall -Wextra -Wshadow -Wpointer-arith -Wstrict-prototypes
        -fstack-protector-strong
        $<$<NOT:$<CONFIG:Debug>>:-U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2>
        $<$<BOOL:${SDL2GFX_WERROR}>:-Werror>)
endif()

set(SDL2GFX_TARGETS)

function(sdl2gfx_configure_library target)
    target_sources(${target} PRIVATE ${SDL2GFX_SOURCES} ${SDL2GFX_PUBLIC_HEADERS})
    target_include_directories(${target} PUBLIC
        $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>
        $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/SDL2>
        $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>)
    target_link_libraries(${target}
        PUBLIC ${SDL2GFX_SDL_TARGET}
        PRIVATE $<BUILD_INTERFACE:sdl2gfx_build_flags>)
    if(UNIX)
        target_link_libraries(${target} PRIVATE m)
    endif()
    set_target_properties(${target} PROPERTIES C_STANDARD 99 C_STANDARD_REQUIRED ON C_EXTENSIONS OFF)
    if(SDL2GFX_LEGACY_COLOR_BYTE_ORDER)
        target_compile_definitions(${target} PRIVATE SDL2_GFX_LEGACY_COLOR_BYTE_ORDER)
    endif()
    if(MSVC AND SDL2GFX_ANALYZE)
        target_compile_options(${target} PRIVATE /analyze /analyze:external-)
    endif()
endfunction()

if(SDL2GFX_SHARED)
    add_library(SDL2_gfx SHARED)
    sdl2gfx_configure_library(SDL2_gfx)
    target_compile_definitions(SDL2_gfx PRIVATE DLL_EXPORT INTERFACE LIBSDL2_GFX_DLL_IMPORT)
    # Only functions declared in the public headers are exported (BLD-001)
    set_target_properties(SDL2_gfx PROPERTIES EXPORT_NAME SDL2_gfx RUNTIME_OUTPUT_DIRECTORY "${SDL2GFX_RUNTIME_DIR}"
        C_VISIBILITY_PRESET hidden)
    if(UNIX AND NOT APPLE)
        # Same SONAME as the former autotools build (libtool -release 1.0): libSDL2_gfx-1.0.so.0.
        # It names the ABI series, not the project version: change it only for an incompatible ABI.
        # The file version must keep increasing (1.0.4 installed libSDL2_gfx-1.0.so.0.0.2).
        set_target_properties(SDL2_gfx PROPERTIES
            OUTPUT_NAME "SDL2_gfx-1.0"
            SOVERSION 0
            VERSION 0.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH})
    endif()
    add_library(SDL2_gfx::SDL2_gfx ALIAS SDL2_gfx)
    list(APPEND SDL2GFX_TARGETS SDL2_gfx)
endif()

if(SDL2GFX_STATIC)
    add_library(SDL2_gfx-static STATIC)
    sdl2gfx_configure_library(SDL2_gfx-static)
    # Avoid a name clash with the DLL import library on Windows.
    set_target_properties(SDL2_gfx-static PROPERTIES
        OUTPUT_NAME $<IF:$<BOOL:${MSVC}>,SDL2_gfx-static,SDL2_gfx>
        EXPORT_NAME SDL2_gfx-static
        POSITION_INDEPENDENT_CODE ON)
    add_library(SDL2_gfx::SDL2_gfx-static ALIAS SDL2_gfx-static)
    list(APPEND SDL2GFX_TARGETS SDL2_gfx-static)
endif()

if(SDL2GFX_DEMOS)
    add_subdirectory(demo)
endif()

if(SDL2GFX_TESTS)
    enable_testing()
    add_subdirectory(test)
endif()

if(SDL2GFX_TESTS OR SDL2GFX_FUZZ)
    add_subdirectory(fuzz)
endif()

if(SDL2GFX_BENCH)
    add_subdirectory(bench)
endif()

# API documentation: cmake --build --preset <preset> --target docs -> <build>/docs/html (not installed).
# Doxygen warnings (e.g. undocumented public symbols) fail the target.
if(SDL2GFX_DOCS)
    find_package(Doxygen OPTIONAL_COMPONENTS dot)
    if(DOXYGEN_FOUND)
        set(SDL2GFX_DOCS_OUTPUT "${PROJECT_BINARY_DIR}/docs")
        if(TARGET Doxygen::dot)
            set(SDL2GFX_DOCS_HAVE_DOT YES)
            get_filename_component(SDL2GFX_DOCS_DOT_PATH "${DOXYGEN_DOT_EXECUTABLE}" DIRECTORY)
        else()
            set(SDL2GFX_DOCS_HAVE_DOT NO)
            set(SDL2GFX_DOCS_DOT_PATH "")
        endif()
        configure_file(docs/Doxyfile.in "${PROJECT_BINARY_DIR}/Doxyfile" @ONLY)
        add_custom_target(docs
            COMMAND Doxygen::doxygen "${PROJECT_BINARY_DIR}/Doxyfile"
            WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}"
            COMMENT "Generating API documentation in ${SDL2GFX_DOCS_OUTPUT}/html"
            VERBATIM)
    else()
        message(STATUS "Doxygen not found: no 'docs' target")
    endif()
endif()
if(SDL2GFX_INSTALL)
    set(SDL2GFX_CMAKE_DIR "${CMAKE_INSTALL_LIBDIR}/cmake/SDL2_gfx")

    install(TARGETS ${SDL2GFX_TARGETS} EXPORT SDL2_gfxTargets
        RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
        LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
        ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR})
    install(FILES ${SDL2GFX_PUBLIC_HEADERS} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/SDL2)
    install(FILES LICENSE DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/licenses/SDL2_gfx)
    if(MSVC AND SDL2GFX_SHARED)
        install(FILES $<TARGET_PDB_FILE:SDL2_gfx> DESTINATION ${CMAKE_INSTALL_BINDIR} OPTIONAL)
    endif()

    install(EXPORT SDL2_gfxTargets NAMESPACE SDL2_gfx:: DESTINATION ${SDL2GFX_CMAKE_DIR})
    configure_package_config_file(cmake/SDL2_gfxConfig.cmake.in
        "${PROJECT_BINARY_DIR}/SDL2_gfxConfig.cmake"
        INSTALL_DESTINATION ${SDL2GFX_CMAKE_DIR})
    write_basic_package_version_file("${PROJECT_BINARY_DIR}/SDL2_gfxConfigVersion.cmake"
        COMPATIBILITY SameMajorVersion)
    install(FILES
        "${PROJECT_BINARY_DIR}/SDL2_gfxConfig.cmake"
        "${PROJECT_BINARY_DIR}/SDL2_gfxConfigVersion.cmake"
        DESTINATION ${SDL2GFX_CMAKE_DIR})

    if(SDL2GFX_SHARED AND UNIX AND NOT APPLE)
        # Development symlink so that "-lSDL2_gfx" (pkg-config) resolves to the versioned library.
        install(CODE "file(CREATE_LINK \"$<TARGET_FILE_NAME:SDL2_gfx>\"
            \"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}/libSDL2_gfx${CMAKE_SHARED_LIBRARY_SUFFIX}\" SYMBOLIC)")
    endif()

    set(SDL2GFX_PC_LIB SDL2_gfx)
    if(NOT SDL2GFX_SHARED AND MSVC)
        set(SDL2GFX_PC_LIB SDL2_gfx-static)
    endif()
    configure_file(cmake/SDL2_gfx.pc.in "${PROJECT_BINARY_DIR}/SDL2_gfx.pc" @ONLY)
    install(FILES "${PROJECT_BINARY_DIR}/SDL2_gfx.pc" DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig)
endif()
