cmake_minimum_required(VERSION 3.16)
project(reaktor VERSION 0.11.0 LANGUAGES C CXX)

if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
    set(_reaktor_top ON)
else()
    set(_reaktor_top OFF)
endif()
option(REAKTOR_SAMPLES "Build the samples" ${_reaktor_top})
option(REAKTOR_TESTS "Build the tests" ${_reaktor_top})

set(CMAKE_C_STANDARD 99)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if(_reaktor_top AND NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
    set(CMAKE_BUILD_TYPE Release CACHE STRING "" FORCE)
endif()

if(MSVC)
    set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreadedDLL" CACHE STRING "")
endif()

set(TP "${CMAKE_CURRENT_SOURCE_DIR}/external")

option(REAKTOR_SHARED "Also build a shared libreaktor, and link the samples to it" OFF)
set(REAKTOR_SHARED_SDL OFF)
if(REAKTOR_SHARED)
    if(NOT UNIX OR EMSCRIPTEN)
        message(FATAL_ERROR "REAKTOR_SHARED is for Linux, the BSDs and macOS")
    endif()
    set(CMAKE_POSITION_INDEPENDENT_CODE ON)
    if(NOT APPLE)
        set(REAKTOR_SHARED_SDL ON)
    endif()
endif()
if(REAKTOR_SHARED_SDL)
    set(REAKTOR_SDL SDL3::SDL3-shared)
else()
    set(REAKTOR_SDL SDL3::SDL3-static)
endif()
set(SDL_SHARED       ${REAKTOR_SHARED_SDL} CACHE BOOL "" FORCE)
set(SDL_STATIC       ON  CACHE BOOL "" FORCE)
set(SDL_TESTS        OFF CACHE BOOL "" FORCE)
set(SDL_EXAMPLES     OFF CACHE BOOL "" FORCE)
set(SDL_TEST_LIBRARY OFF CACHE BOOL "" FORCE)
set(SDL_INSTALL      OFF CACHE BOOL "" FORCE)
foreach(sub AUDIO JOYSTICK HAPTIC HIDAPI SENSOR CAMERA POWER OFFSCREEN)
    set(SDL_${sub} OFF CACHE BOOL "" FORCE)
endforeach()
# Off: the software renderer is the default, and with the GPU API built in,
# SDL loads Vulkan and its drivers even for that renderer (PERFORMANCE.md).
# An application that runs its own shaders turns it on.
option(REAKTOR_SHADERS "An application's own shaders: SDL's GPU API and its renderer, --renderer sdl-gpu" OFF)
set(SDL_GPU ${REAKTOR_SHADERS} CACHE BOOL "" FORCE)
set(SDL_TRAY ON CACHE BOOL "" FORCE)

foreach(drv RENDER_D3D RENDER_VULKAN VULKAN)
    set(SDL_${drv} OFF CACHE BOOL "" FORCE)
endforeach()
if(REAKTOR_SHADERS AND UNIX AND NOT APPLE AND NOT EMSCRIPTEN)
    set(SDL_VULKAN ON CACHE BOOL "" FORCE)
endif()
set(_renderers_all direct3d11 direct3d12 opengl opengles2)
if(WIN32)
    set(_renderers_default direct3d11 direct3d12)
    set(_renderers_here ${_renderers_all})
elseif(UNIX AND NOT APPLE AND NOT EMSCRIPTEN)
    set(_renderers_default "")
    set(_renderers_here opengl opengles2)
else()
    set(_renderers_default "")
    set(_renderers_here "")
endif()
set(REAKTOR_RENDERERS "" CACHE STRING
    "Renderers built beside software, as --renderer names them: direct3d11, direct3d12, opengl, opengles2; empty for the platform's default, none for software only")
set_property(CACHE REAKTOR_RENDERERS PROPERTY STRINGS "" none ${_renderers_all})

# A build directory from before the list keeps the renderers its two
# switches, REAKTOR_SDL_D3D and REAKTOR_SDL_GL, had chosen.
if(NOT REAKTOR_RENDERERS AND (DEFINED REAKTOR_SDL_D3D OR DEFINED REAKTOR_SDL_GL))
    set(_old "")
    if(NOT DEFINED REAKTOR_SDL_D3D OR REAKTOR_SDL_D3D)
        list(APPEND _old direct3d11 direct3d12)
    endif()
    if(REAKTOR_SDL_GL)
        list(APPEND _old opengl opengles2)
    endif()
    if(NOT _old)
        set(_old none)
    endif()
    unset(REAKTOR_SDL_D3D CACHE)
    unset(REAKTOR_SDL_GL CACHE)
    string(REPLACE ";" "," _old_shown "${_old}")
    if(_old STREQUAL "none" OR NOT _old STREQUAL "${_renderers_default}")
        set(REAKTOR_RENDERERS "${_old}" CACHE STRING "" FORCE)
        message(WARNING "REAKTOR_SDL_D3D and REAKTOR_SDL_GL are now REAKTOR_RENDERERS; this build keeps REAKTOR_RENDERERS=${_old_shown}")
    else()
        message(STATUS "REAKTOR_SDL_D3D and REAKTOR_SDL_GL are now REAKTOR_RENDERERS; this build has the default")
    endif()
endif()

string(REPLACE "," ";" _renderers "${REAKTOR_RENDERERS}")
string(REPLACE "," ", " _renderers_shown "${REAKTOR_RENDERERS}")
if(_renderers MATCHES "^(ON|OFF|TRUE|FALSE|YES|NO|Y|N|1|0)$")
    message(FATAL_ERROR "REAKTOR_RENDERERS lists renderers, it is not a switch: direct3d11, direct3d12, opengl, opengles2, or none for software only")
elseif(NOT _renderers)
    set(_renderers ${_renderers_default})
elseif(_renderers STREQUAL "none")
    set(_renderers "")
else()
    foreach(r ${_renderers})
        if(NOT r IN_LIST _renderers_all)
            message(FATAL_ERROR "REAKTOR_RENDERERS=${_renderers_shown}: ${r} is not a renderer; the choices are direct3d11, direct3d12, opengl, opengles2, or none")
        elseif(NOT r IN_LIST _renderers_here)
            message(STATUS "REAKTOR_RENDERERS: ${r} is not a choice on ${CMAKE_SYSTEM_NAME}, ignored")
        endif()
    endforeach()
endif()
foreach(r ${_renderers_here})
    if(r IN_LIST _renderers)
        set(_on ON)
    else()
        set(_on OFF)
    endif()
    if(r STREQUAL direct3d11)
        set(SDL_RENDER_D3D11 ${_on} CACHE BOOL "" FORCE)
    elseif(r STREQUAL direct3d12)
        set(SDL_RENDER_D3D12 ${_on} CACHE BOOL "" FORCE)
    elseif(r STREQUAL opengl)
        set(SDL_OPENGL ${_on} CACHE BOOL "" FORCE)
    elseif(r STREQUAL opengles2)
        set(SDL_OPENGLES ${_on} CACHE BOOL "" FORCE)
    endif()
endforeach()

set(SDL_X11_XSCRNSAVER OFF CACHE BOOL "" FORCE)
# Linux packaging notes; OpenBSD refuses a program whose note segment passes 1 KB.
if(CMAKE_SYSTEM_NAME MATCHES "BSD")
    set(SDL_DLOPEN_NOTES OFF CACHE BOOL "" FORCE)
endif()
# NetBSD's loader searches only /usr/lib, so X11 and Wayland are linked.
if(CMAKE_SYSTEM_NAME STREQUAL "NetBSD")
    set(SDL_DEPS_SHARED OFF CACHE BOOL "" FORCE)
endif()

# A static program keeps only the functions and data it uses. MSVC's Release
# already splits functions; /Gw splits data.
if(MSVC)
    add_compile_options(/Gw)
elseif(NOT EMSCRIPTEN)
    add_compile_options(-ffunction-sections -fdata-sections)
endif()
# Reaktor and SDL optimized as one program: SDL's software rasterizer then no
# longer runs faster or slower as the code linked before it changes size. The
# objects hold the compiler's own form until the link, so a static library
# meant for other compilers is built with it off, as tools/libreaktor-pkg.sh
# does. On where it measured faster without new warnings: MSVC and Apple
# Clang. GCC warns in dependencies with it, and Clang on Linux gained nothing.
if(MSVC OR CMAKE_C_COMPILER_ID STREQUAL "AppleClang")
    set(_reaktor_lto_default ON)
else()
    set(_reaktor_lto_default OFF)
endif()
option(REAKTOR_LTO "Link-time optimization in a Release build" ${_reaktor_lto_default})
if(REAKTOR_LTO AND NOT EMSCRIPTEN)
    include(CheckIPOSupported)
    check_ipo_supported(RESULT _reaktor_lto OUTPUT _reaktor_lto_why LANGUAGES C CXX)
    if(_reaktor_lto)
        set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_RELEASE ON)
    else()
        message(STATUS "LTO: not supported by this toolchain")
    endif()
endif()
add_subdirectory("${TP}/SDL" EXCLUDE_FROM_ALL)
# SDL keeps link-time code out of SDL_mslibc.c for a build without the C
# library; with it the file is empty, and the flag only clashes with the
# precompiled header.
if(MSVC AND _reaktor_lto AND SDL_LIBC AND NOT CMAKE_VERSION VERSION_LESS 3.18)
    set_property(SOURCE "${TP}/SDL/src/stdlib/SDL_mslibc.c" DIRECTORY "${TP}/SDL"
        PROPERTY COMPILE_FLAGS "")
endif()

function(reaktor_write_if_changed path content)
    set(_old "")
    if(EXISTS "${path}")
        file(READ "${path}" _old)
    endif()
    if(NOT _old STREQUAL content)
        file(WRITE "${path}" "${content}")
    endif()
endfunction()
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}")

# SDL's dynamic API keeps every SDL function linked and loads whichever SDL
# library the SDL3_DYNAMIC_API environment variable names. Reaktor links SDL
# statically and reads no environment, so it is compiled out.
file(STRINGS "${TP}/SDL/src/dynapi/SDL_dynapi.h" _dynapi_guard REGEX "^#ifndef SDL_dynapi_h_")
if(NOT _dynapi_guard)
    message(FATAL_ERROR "SDL_dynapi.h no longer opens with #ifndef SDL_dynapi_h_; "
                        "core/sdl/no_dynapi.h needs its new guard")
endif()
if(MSVC)
    target_compile_options(SDL3-static PRIVATE
        "/FI${CMAKE_CURRENT_SOURCE_DIR}/core/sdl/no_dynapi.h")
else()
    target_compile_options(SDL3-static PRIVATE
        -include "${CMAKE_CURRENT_SOURCE_DIR}/core/sdl/no_dynapi.h")
endif()
if(REAKTOR_SHARED_SDL)
    target_compile_options(SDL3-shared PRIVATE
        -include "${CMAKE_CURRENT_SOURCE_DIR}/core/sdl/no_dynapi.h")
    # Our own SDL under its own name, never the distro's libSDL3.
    set_target_properties(SDL3-shared PROPERTIES OUTPUT_NAME reaktor-sdl3
        LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}")
endif()

if(UNIX AND NOT EMSCRIPTEN)
    find_library(REAKTOR_LIBM m)
    if(REAKTOR_LIBM)
        link_libraries(m)
    endif()
endif()

file(GLOB PLUTOVG_SRC "${TP}/plutosvg/plutovg/source/*.c")
add_library(plutovg STATIC ${PLUTOVG_SRC})
target_include_directories(plutovg PUBLIC "${TP}/plutosvg/plutovg/include")
target_compile_definitions(plutovg PUBLIC PLUTOVG_BUILD_STATIC
                                   PRIVATE STBI_ONLY_PNG STBI_ONLY_JPEG)

add_library(plutosvg STATIC "${TP}/plutosvg/source/plutosvg.c")
target_include_directories(plutosvg PUBLIC "${TP}/plutosvg/source")
target_compile_definitions(plutosvg PUBLIC PLUTOSVG_BUILD_STATIC)
target_link_libraries(plutosvg PUBLIC plutovg)

set(FT "${TP}/freetype/src")
add_library(freetype STATIC
    ${FT}/base/ftsystem.c ${FT}/base/ftinit.c ${FT}/base/ftdebug.c ${FT}/base/ftbase.c
    ${FT}/autofit/autofit.c ${FT}/cff/cff.c ${FT}/psaux/psaux.c ${FT}/pshinter/pshinter.c
    ${FT}/psnames/psnames.c ${FT}/sfnt/sfnt.c ${FT}/smooth/smooth.c ${FT}/truetype/truetype.c)
target_include_directories(freetype PUBLIC "${TP}/freetype/include" core/render/ft)
target_compile_definitions(freetype
    PUBLIC "FT_CONFIG_OPTIONS_H=<reaktor_ftoption.h>"
    PRIVATE FT2_BUILD_LIBRARY "FT_CONFIG_MODULES_H=<reaktor_ftmodule.h>")

add_library(onlay STATIC ${TP}/onlay/onlay.c)
target_include_directories(onlay PUBLIC ${TP}/onlay)
target_compile_definitions(onlay PUBLIC LAY_FLOAT=1)

if(REAKTOR_TESTS AND NOT EMSCRIPTEN)
    add_executable(onlaytest ${TP}/onlay/test_onlay.c)
    target_link_libraries(onlaytest PRIVATE onlay)
endif()

set(REAKTOR_BUILTINS
    assets/fonts/Aileron-Regular.otf
    assets/fonts/Aileron-Bold.otf
    assets/icons/reaktor-icon.svg
    external/ionicons/src/svg/chevron-down-outline.svg
    external/ionicons/src/svg/chevron-back-outline.svg
    external/ionicons/src/svg/chevron-forward-outline.svg
    external/ionicons/src/svg/ellipse.svg
    external/ionicons/src/svg/ellipse-outline.svg
    external/ionicons/src/svg/radio-button-off.svg
    external/ionicons/src/svg/close-outline.svg
    assets/css/reaktor.css
    external/watercss/src/parts/_core.css
    external/watercss/src/parts/_base.css
    external/watercss/src/parts/_typography.css
    external/watercss/src/parts/_forms.css
    external/watercss/src/parts/_range.css
    external/watercss/src/parts/_links.css
    external/watercss/src/parts/_code.css
    external/watercss/src/parts/_misc.css
    external/watercss/src/parts/_print.css
    external/watercss/src/variables-light.css
    external/watercss/src/variables-dark.css)
set(_gen "/* Generated by CMakeLists.txt from REAKTOR_BUILTINS. */\n#include \"util.h\"\n\n")
set(_rows "")
set(_n 0)
string(REPEAT "0x..," 16 _line)
foreach(_rel IN LISTS REAKTOR_BUILTINS)
    set(_f "${CMAKE_CURRENT_SOURCE_DIR}/${_rel}")
    set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${_f}")
    file(READ "${_f}" _hex HEX)
    file(SIZE "${_f}" _size)
    string(REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1," _bytes "${_hex}")
    string(REGEX REPLACE "(${_line})" "\\1\n" _bytes "${_bytes}")
    string(APPEND _gen "static const unsigned char builtin_${_n}[] = {\n${_bytes}0};\n")
    string(APPEND _rows "    { \"${_rel}\", builtin_${_n}, ${_size} },\n")
    math(EXPR _n "${_n} + 1")
endforeach()
string(APPEND _gen
    "\nconst reaktor_builtin reaktor_builtins[] = {\n${_rows}};\n"
    "const int reaktor_builtin_count = ${_n};\n")
set(_builtins "${CMAKE_BINARY_DIR}/gen/reaktor_builtins.c")
reaktor_write_if_changed("${_builtins}" "${_gen}")
message(STATUS "assets: ${_n} compiled in")

add_library(reaktor_headers INTERFACE)
target_include_directories(reaktor_headers INTERFACE include "${TP}/nuklear" "${TP}/nukanim")

add_library(reaktor_core STATIC
    core/base/util.c
    core/base/utf8.c
    core/base/url.c
    core/render/font.c
    core/render/nk_impl.c
    core/render/svg.c
    "${_builtins}")
target_include_directories(reaktor_core PUBLIC core/base core/render)
target_link_libraries(reaktor_core PUBLIC plutosvg freetype reaktor_headers ${REAKTOR_SDL})
# Nuklear built for size: 139 KB less of the library, at no measurable cost a
# frame (PERFORMANCE.md). A debug build keeps its own -O0.
set_property(SOURCE core/render/nk_impl.c APPEND PROPERTY COMPILE_OPTIONS
    "$<$<NOT:$<CONFIG:Debug>>:$<IF:$<C_COMPILER_ID:MSVC>,/Os,-Os>>")

set(APP_ICON assets/icons/reaktor-icon.ico)
set(APP_RESOURCES "")

add_executable(mkicon EXCLUDE_FROM_ALL tools/mkicon.c)
target_link_libraries(mkicon PRIVATE reaktor_core)

if(UNIX AND NOT APPLE AND NOT EMSCRIPTEN AND NOT ANDROID)
    add_library(reaktor_gibus INTERFACE)
    target_include_directories(reaktor_gibus INTERFACE "${TP}/gibus/include")
    set(THREADS_PREFER_PTHREAD_FLAG ON)
    find_package(Threads REQUIRED)
endif()

if(REAKTOR_TESTS AND NOT EMSCRIPTEN)
    add_executable(keytest tests/keytest.c core/ui/keys.c)
    target_link_libraries(keytest PRIVATE reaktor_headers)
    target_include_directories(keytest PRIVATE core/ui)
    target_link_libraries(keytest PRIVATE ${REAKTOR_SDL})

    add_executable(a11ytest tests/a11ytest.c core/a11y/a11y.c
        platform/a11y/a11y_snapshot.c core/base/utf8.c)
    target_link_libraries(a11ytest PRIVATE reaktor_headers ${REAKTOR_SDL})
    target_include_directories(a11ytest PRIVATE core/a11y core/render
        platform/a11y core/base)

    add_executable(animtest tests/animtest.c core/anim/anim.c)
    target_include_directories(animtest PRIVATE core/anim core/render
                                                "${TP}/nuklear/demo/sdl3_renderer")
    target_link_libraries(animtest PRIVATE reaktor_core ${REAKTOR_SDL})

    add_executable(localetest tests/localetest.c
                   core/locale/locale.c core/locale/plural.c
                   core/locale/format.c)
    target_link_libraries(localetest PRIVATE reaktor_headers ${REAKTOR_SDL})
    target_include_directories(localetest PRIVATE core/locale)
    target_compile_definitions(localetest PRIVATE REAKTOR_LOCALE_EMBEDDED)

    add_executable(laytest tests/laytest.c core/ui/layout.c)
    target_link_libraries(laytest PRIVATE reaktor_headers)
    target_include_directories(laytest PRIVATE core/ui core/render)
    target_link_libraries(laytest PRIVATE onlay)

    add_executable(csstest tests/csstest.c core/css/css.c)
    target_include_directories(csstest PRIVATE core/css core/base)
    target_link_libraries(csstest PRIVATE plutovg reaktor_headers)
    target_compile_definitions(csstest PRIVATE _CRT_SECURE_NO_WARNINGS
                               CSSTEST_SOURCE="${CMAKE_CURRENT_SOURCE_DIR}/")

    add_executable(basetest tests/basetest.c core/base/url.c core/base/utf8.c)
    target_include_directories(basetest PRIVATE core/base)
    target_link_libraries(basetest PRIVATE ${REAKTOR_SDL})

    add_executable(imagetest tests/imagetest.c)
    target_link_libraries(imagetest PRIVATE plutovg)

    add_executable(gibustest ${TP}/gibus/tests/gibustest.c ${TP}/gibus/src/gibus_msg.c)
    target_include_directories(gibustest PRIVATE ${TP}/gibus/include ${TP}/gibus/src)
    if(TARGET reaktor_gibus)
        target_sources(gibustest PRIVATE ${TP}/gibus/src/gibus_conn.c)
        target_link_libraries(gibustest PRIVATE Threads::Threads)
        target_compile_definitions(gibustest PRIVATE GIBUSTEST_LIVE)
    endif()

    if(MSVC)
        foreach(_t keytest a11ytest animtest localetest laytest csstest basetest imagetest gibustest)
            target_compile_options(${_t} PRIVATE /we4013)
        endforeach()
    endif()
endif()

if(WIN32 AND NOT EMSCRIPTEN)
    add_executable(vmwalk EXCLUDE_FROM_ALL tools/vmwalk.c)
endif()

if(WIN32)
    set(GEN "${CMAKE_BINARY_DIR}/gen")
    file(MAKE_DIRECTORY "${GEN}")
    configure_file("${CMAKE_CURRENT_SOURCE_DIR}/${APP_ICON}"
                   "${GEN}/reaktor.ico" COPYONLY)
    reaktor_write_if_changed("${GEN}/reaktor.rc" "1 ICON \"reaktor.ico\"\n")
    set(APP_RESOURCES "${GEN}/reaktor.rc")
elseif(UNIX AND NOT APPLE AND NOT EMSCRIPTEN)
    file(WRITE "${CMAKE_BINARY_DIR}/reaktor.desktop"
"[Desktop Entry]
Type=Application
Version=1.0
Name=Reaktor
Comment=A Nuklear-powered engine styled by CSS
Exec=${CMAKE_BINARY_DIR}/showcase
Icon=${CMAKE_CURRENT_SOURCE_DIR}/assets/icons/reaktor-icon.png
Terminal=false
Categories=Development;
StartupWMClass=showcase
")
endif()

option(REAKTOR_A11Y
    "Serve the accessibility tree to screen readers (UI Automation, AT-SPI, NSAccessibility, the DOM)"
    ON)

set(_a11y "${CMAKE_CURRENT_SOURCE_DIR}/platform/a11y")
add_library(reaktor_a11y_none INTERFACE)
target_sources(reaktor_a11y_none INTERFACE "${_a11y}/a11y_none.c" "${_a11y}/a11y_window_none.c")

add_library(reaktor_a11y INTERFACE)
if(NOT REAKTOR_A11Y)
    target_link_libraries(reaktor_a11y INTERFACE reaktor_a11y_none)
    message(STATUS "a11y: off; the tree is built and served to nothing")
elseif(EMSCRIPTEN)
    target_sources(reaktor_a11y INTERFACE "${_a11y}/a11y_web.c" "${_a11y}/a11y_window_none.c")
elseif(WIN32)
    target_sources(reaktor_a11y INTERFACE
        "${_a11y}/a11y_snapshot.c" "${_a11y}/a11y_win32.c")
    target_link_libraries(reaktor_a11y INTERFACE uiautomationcore ole32 oleaut32)
elseif(APPLE)
    # Here: an interface library compiles where it is linked, maybe without OBJC.
    enable_language(OBJC)
    add_library(reaktor_a11y_macos OBJECT "${_a11y}/a11y_macos.m")
    target_compile_options(reaktor_a11y_macos PRIVATE -fobjc-arc)
    target_compile_definitions(reaktor_a11y_macos PRIVATE REAKTOR_HAVE_NSACCESSIBILITY)
    target_link_libraries(reaktor_a11y_macos PRIVATE reaktor_runtime)
    target_sources(reaktor_a11y INTERFACE
        "${_a11y}/a11y_snapshot.c" "${_a11y}/a11y_window_none.c"
        "$<TARGET_OBJECTS:reaktor_a11y_macos>")
    target_compile_definitions(reaktor_a11y INTERFACE REAKTOR_HAVE_NSACCESSIBILITY)
    target_link_libraries(reaktor_a11y INTERFACE "-framework Cocoa")
elseif(TARGET reaktor_gibus)
    target_sources(reaktor_a11y INTERFACE
        "${_a11y}/a11y_snapshot.c" "${_a11y}/a11y_window_none.c" "${_a11y}/a11y_atspi.c")
    target_compile_definitions(reaktor_a11y INTERFACE REAKTOR_HAVE_ATSPI)
    target_link_libraries(reaktor_a11y INTERFACE reaktor_gibus)
    message(STATUS "a11y: AT-SPI")
else()
    target_link_libraries(reaktor_a11y INTERFACE reaktor_a11y_none)
    message(STATUS "a11y: no AT-SPI bridge on this system")
endif()

option(REAKTOR_LOCALE "Translations, from the catalogs in assets/locale" ON)
option(REAKTOR_LOCALE_EMBED "Compile the catalogs in rather than read them at startup" OFF)

set(_locale "${CMAKE_CURRENT_SOURCE_DIR}/core/locale")
add_library(reaktor_locale_none INTERFACE)
target_sources(reaktor_locale_none INTERFACE "${_locale}/locale_none.c")

add_library(reaktor_locale INTERFACE)
if(NOT REAKTOR_LOCALE)
    target_link_libraries(reaktor_locale INTERFACE reaktor_locale_none)
    message(STATUS "locale: off")
else()
    target_sources(reaktor_locale INTERFACE
        "${_locale}/locale.c" "${_locale}/plural.c" "${_locale}/format.c"
        "${_locale}/locale_runtime.c")
    if(REAKTOR_LOCALE_EMBED)
        file(GLOB _catalogs CONFIGURE_DEPENDS
             "${CMAKE_CURRENT_SOURCE_DIR}/assets/locale/*.txt")
        set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${_catalogs})
        set(_gen "/* Generated by CMakeLists.txt from assets/locale. */\n#include \"locale_internal.h\"\n\n")
        set(_rows "")
        set(_n 0)
        foreach(_f IN LISTS _catalogs)
            get_filename_component(_code "${_f}" NAME_WE)
            file(READ "${_f}" _hex HEX)
            file(SIZE "${_f}" _size)
            string(REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1," _bytes "${_hex}")
            string(APPEND _gen "static const unsigned char catalog_${_n}[] = {${_bytes}0};\n")
            string(APPEND _rows "    { \"${_code}\", catalog_${_n}, ${_size} },\n")
            math(EXPR _n "${_n} + 1")
        endforeach()
        if(_n EQUAL 0)
            set(_rows "    { 0, 0, 0 },\n")
        endif()
        string(APPEND _gen
            "\nconst struct reaktor_locale_catalog reaktor_locale_catalogs[] = {\n${_rows}};\n"
            "const int reaktor_locale_catalog_count = ${_n};\n")
        set(_out "${CMAKE_BINARY_DIR}/gen/locale_catalogs.c")
        reaktor_write_if_changed("${_out}" "${_gen}")
        target_sources(reaktor_locale INTERFACE "${_out}")
        target_compile_definitions(reaktor_locale INTERFACE REAKTOR_LOCALE_EMBEDDED)
        message(STATUS "locale: ${_n} catalogs compiled in")
    else()
        message(STATUS "locale: catalogs read from assets/locale at startup")
    endif()
endif()

option(REAKTOR_TEXT "Shaping, direction, fallback fonts and Unicode line breaking" ON)

set(_text "${CMAKE_CURRENT_SOURCE_DIR}/core/text")
add_library(reaktor_text_none INTERFACE)
target_sources(reaktor_text_none INTERFACE "${_text}/text_none.c")

add_library(reaktor_text INTERFACE)
if(NOT REAKTOR_TEXT)
    target_link_libraries(reaktor_text INTERFACE reaktor_text_none)
    message(STATUS "text: off; lines break at spaces, and Aileron draws what it can")
else()
    set(MJB_FEATURE_CHARACTER_NAMES OFF)
    set(MJB_FEATURE_COLLATION OFF)
    set(MJB_FEATURE_IDNA OFF)
    set(MJB_FEATURE_SECURITY OFF)
    add_subdirectory(${TP}/mojibake EXCLUDE_FROM_ALL)
    if(EMSCRIPTEN)
        set_target_properties(mojibake_lib PROPERTIES C_EXTENSIONS ON)
    endif()

    add_library(kb_text_shape STATIC "${_text}/kb.c")
    target_include_directories(kb_text_shape PUBLIC "${TP}/kb")
    if(MSVC)
        target_compile_options(kb_text_shape PRIVATE /w)
    else()
        target_compile_options(kb_text_shape PRIVATE -w)
    endif()

    target_sources(reaktor_text INTERFACE "${_text}/text.c")
    target_link_libraries(reaktor_text INTERFACE Mojibake::mojibake kb_text_shape)
    message(STATUS "text: shaping by kb_text_shape; direction and line breaking by mojibake")

    if(REAKTOR_TESTS AND NOT EMSCRIPTEN)
        add_executable(texttest tests/texttest.c)
        target_link_libraries(texttest PRIVATE reaktor_headers)
        target_include_directories(texttest PRIVATE core/render core/text)
        target_link_libraries(texttest PRIVATE reaktor_text reaktor_core
                              ${REAKTOR_SDL})
    endif()
endif()

option(REAKTOR_SETTINGS "Settings kept between runs, in settings.toml" ON)
option(REAKTOR_TRAY "A tray icon with a menu" ON)
option(REAKTOR_POPUP_WINDOWS "Menus in windows of their own, past the main window's edge" ON)
option(REAKTOR_INSPECTOR "The Inspector: tree, box, style, frame and log of a running app" ON)

foreach(_m settings:REAKTOR_SETTINGS:settings tray:REAKTOR_TRAY:tray
           popups:REAKTOR_POPUP_WINDOWS:popup inspector:REAKTOR_INSPECTOR:inspector)
    string(REPLACE ":" ";" _m "${_m}")
    list(GET _m 0 _name)
    list(GET _m 1 _opt)
    list(GET _m 2 _file)
    add_library(reaktor_${_name}_none INTERFACE)
    target_sources(reaktor_${_name}_none INTERFACE
        "${CMAKE_CURRENT_SOURCE_DIR}/runtime/${_file}_none.c")
    add_library(reaktor_${_name} INTERFACE)
    if(${_opt})
        target_sources(reaktor_${_name} INTERFACE
            "${CMAKE_CURRENT_SOURCE_DIR}/runtime/${_file}.c")
    else()
        target_link_libraries(reaktor_${_name} INTERFACE reaktor_${_name}_none)
        message(STATUS "${_name}: off")
    endif()
endforeach()
if(REAKTOR_SETTINGS)
    target_sources(reaktor_settings INTERFACE "${TP}/toml-c/toml.c")
    target_include_directories(reaktor_settings INTERFACE "${TP}/toml-c")
    if(EMSCRIPTEN)
        target_link_options(reaktor_settings INTERFACE -lidbfs.js
            "SHELL:--pre-js ${CMAKE_CURRENT_SOURCE_DIR}/tools/web-pre.js")
    endif()
endif()
# Linux and the BSDs speak StatusNotifierItem rather than take SDL's tray,
# which loads GTK.
if(REAKTOR_TRAY AND TARGET reaktor_gibus)
    target_compile_definitions(reaktor_tray INTERFACE REAKTOR_TRAY_DBUS)
    target_link_libraries(reaktor_tray INTERFACE reaktor_gibus)
    message(STATUS "tray: StatusNotifierItem")
endif()

option(REAKTOR_NOTIFY "System notifications: a toast, a D-Bus notification, the browser's" ON)

set(_notify "${CMAKE_CURRENT_SOURCE_DIR}/platform/notify")
add_library(reaktor_notify_none INTERFACE)
target_sources(reaktor_notify_none INTERFACE "${_notify}/notify_none.c")
add_library(reaktor_notify INTERFACE)
if(NOT REAKTOR_NOTIFY)
    target_link_libraries(reaktor_notify INTERFACE reaktor_notify_none)
    message(STATUS "notify: off")
else()
    target_sources(reaktor_notify INTERFACE "${_notify}/notify.c")
    if(WIN32 AND NOT EMSCRIPTEN)
        target_link_libraries(reaktor_notify INTERFACE shell32)
    elseif(APPLE)
        enable_language(OBJC)
        add_library(reaktor_notify_macos OBJECT "${_notify}/notify_macos.m")
        target_compile_options(reaktor_notify_macos PRIVATE -fobjc-arc)
        target_sources(reaktor_notify INTERFACE "$<TARGET_OBJECTS:reaktor_notify_macos>")
        target_link_libraries(reaktor_notify INTERFACE
            "-framework Foundation" "-framework UserNotifications")
    elseif(TARGET reaktor_gibus)
        target_compile_definitions(reaktor_notify INTERFACE REAKTOR_HAVE_GIBUS)
        target_link_libraries(reaktor_notify INTERFACE reaktor_gibus)
    elseif(NOT EMSCRIPTEN)
        target_link_libraries(reaktor_notify INTERFACE reaktor_notify_none)
        message(STATUS "notify: no D-Bus on this system; notifications are not sent")
    endif()
endif()

option(REAKTOR_PRINT "Printing and PDF export" ON)

add_library(reaktor_print_none INTERFACE)
target_sources(reaktor_print_none INTERFACE
    "${CMAKE_CURRENT_SOURCE_DIR}/runtime/print_none.c")
add_library(reaktor_print INTERFACE)
if(NOT REAKTOR_PRINT OR EMSCRIPTEN)
    target_link_libraries(reaktor_print INTERFACE reaktor_print_none)
    message(STATUS "print: off")
else()
    target_sources(reaktor_print INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/runtime/print.c")
    target_link_libraries(reaktor_print INTERFACE plutovg)
    if(WIN32)
        target_link_libraries(reaktor_print INTERFACE comdlg32 gdi32)
    elseif(APPLE)
        enable_language(OBJC)
        add_library(reaktor_print_macos OBJECT "${CMAKE_CURRENT_SOURCE_DIR}/runtime/print_macos.m")
        target_compile_options(reaktor_print_macos PRIVATE -fobjc-arc)
        target_sources(reaktor_print INTERFACE "$<TARGET_OBJECTS:reaktor_print_macos>")
        target_link_libraries(reaktor_print INTERFACE "-framework Cocoa" "-framework PDFKit")
    endif()
endif()

add_library(reaktor_runtime STATIC
    core/a11y/a11y.c
    core/anim/anim.c
    core/base/metrics.c
    core/css/style.c
    core/css/css.c
    core/render/damage.c
    core/render/draw.c
    core/ui/declare.c
    core/ui/controls.c
    core/ui/views.c
    core/ui/picker.c
    core/ui/focus.c
    core/ui/keys.c
    core/ui/layout.c
    core/ui/style_map.c
    core/ui/floater.c
    core/ui/toast.c
    core/ui/widgets.c
    platform/theme.c
    platform/lifecycle.c
    runtime/app.c
    runtime/input.c
    runtime/instance.c
    runtime/test.c
    runtime/services.c
    runtime/undo.c
    runtime/window.c)
target_compile_definitions(reaktor_runtime PRIVATE
    REAKTOR_VERSION_STRING="${PROJECT_VERSION}")
if(TARGET reaktor_gibus)
    target_sources(reaktor_runtime PRIVATE
        ${TP}/gibus/src/gibus_msg.c ${TP}/gibus/src/gibus_conn.c)
    # Its directory alone, and threads PUBLIC: a private link would put
    # $<LINK_ONLY:...> in what the shared library takes from the runtime's
    # INTERFACE_LINK_LIBRARIES.
    target_include_directories(reaktor_runtime PRIVATE ${TP}/gibus/include)
    target_compile_definitions(reaktor_runtime PRIVATE REAKTOR_HAVE_GIBUS)
    target_link_libraries(reaktor_runtime PUBLIC Threads::Threads)
endif()

if(EMSCRIPTEN)
    target_sources(reaktor_runtime PRIVATE platform/web/keyboard_web.c)
endif()

target_include_directories(reaktor_runtime PUBLIC
    include
    core/a11y
    core/anim
    core/base
    core/css
    core/locale
    core/render
    core/text
    core/ui
    platform
    platform/a11y
    platform/web
    core
    "${TP}/nuklear"
    "${TP}/nuklear/demo/sdl3_renderer")

target_link_libraries(reaktor_runtime PUBLIC
    reaktor_core
    ${REAKTOR_SDL}
    onlay)

if(WIN32 AND NOT EMSCRIPTEN)
    target_link_libraries(reaktor_runtime PUBLIC dxguid)
endif()

set(REAKTOR_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}" CACHE INTERNAL "")

foreach(_lic SDL/LICENSE.txt plutosvg/LICENSE nuklear/LICENSE
             nukanim/LICENSE onlay/LICENSE watercss/LICENSE.md ionicons/LICENSE mojibake/LICENSE
             kb/LICENSE)
    string(REGEX REPLACE "/.*" "" _who "${_lic}")
    configure_file("${CMAKE_CURRENT_SOURCE_DIR}/external/${_lic}"
                   "${CMAKE_BINARY_DIR}/licenses/${_who}.txt" COPYONLY)
endforeach()
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/external/plutosvg/plutovg/LICENSE"
               "${CMAKE_BINARY_DIR}/licenses/plutovg.txt" COPYONLY)
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/external/freetype/docs/FTL.TXT"
               "${CMAKE_BINARY_DIR}/licenses/freetype.txt" COPYONLY)
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/external/toml-c/LICENSE"
               "${CMAKE_BINARY_DIR}/licenses/toml-c.txt" COPYONLY)
if(TARGET reaktor_gibus)
    configure_file("${CMAKE_CURRENT_SOURCE_DIR}/external/gibus/LICENSE"
                   "${CMAKE_BINARY_DIR}/licenses/gibus.txt" COPYONLY)
endif()
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/LICENSE"
               "${CMAKE_BINARY_DIR}/licenses/reaktor.txt" COPYONLY)
set(REAKTOR_APP_RESOURCES "${APP_RESOURCES}" CACHE INTERNAL "")

if(REAKTOR_SHARED)
    # The runtime, the core and the libraries under them; reaktor.map says
    # what they export. The modules stay in each app, which exports them back.
    # On macOS SDL goes in too, and ld64 takes the map as a list of names.
    set(_so_parts reaktor_runtime reaktor_core plutosvg plutovg freetype onlay)
    set(_so_files "")
    foreach(_t IN LISTS _so_parts)
        target_compile_options(${_t} PRIVATE -fno-semantic-interposition)
    endforeach()
    if(APPLE)
        list(APPEND _so_parts SDL3-static)
    endif()
    foreach(_t IN LISTS _so_parts)
        list(APPEND _so_files "$<TARGET_FILE:${_t}>")
    endforeach()
    file(GENERATE OUTPUT "${CMAKE_BINARY_DIR}/reaktor_so.c" CONTENT "")
    add_library(reaktor_shared SHARED "${CMAKE_BINARY_DIR}/reaktor_so.c")
    set_target_properties(reaktor_shared PROPERTIES
        VERSION ${PROJECT_VERSION} SOVERSION 1
        LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
        LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/tools/reaktor.map")
    add_dependencies(reaktor_shared ${_so_parts})
    if(APPLE)
        file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/tools/reaktor.map" _map_lines)
        set(_exp "")
        foreach(_l IN LISTS _map_lines)
            if(_l MATCHES "^ *#" OR _l MATCHES "[{}:]")
                continue()
            endif()
            string(REGEX MATCHALL "[A-Za-z_][A-Za-z0-9_*]*" _names "${_l}")
            foreach(_n IN LISTS _names)
                string(APPEND _exp "_${_n}\n")
            endforeach()
        endforeach()
        string(APPEND _exp "_SDL_*\n")
        file(WRITE "${CMAKE_BINARY_DIR}/reaktor.exp" "${_exp}")
        set(_force "")
        foreach(_f IN LISTS _so_files)
            list(APPEND _force "-Wl,-force_load,${_f}")
        endforeach()
        set_target_properties(reaktor_shared PROPERTIES OUTPUT_NAME Reaktor
            FRAMEWORK TRUE FRAMEWORK_VERSION A
            MACOSX_FRAMEWORK_IDENTIFIER io.github.alpaq92.reaktor
            MACOSX_FRAMEWORK_SHORT_VERSION_STRING ${PROJECT_VERSION}
            MACOSX_FRAMEWORK_BUNDLE_VERSION ${PROJECT_VERSION}
            INSTALL_NAME_DIR "@rpath"
            LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/Frameworks")
        target_link_libraries(reaktor_shared PRIVATE ${_force}
            $<TARGET_PROPERTY:reaktor_runtime,INTERFACE_LINK_LIBRARIES>)
        target_link_options(reaktor_shared PRIVATE
            "-Wl,-exported_symbols_list,${CMAKE_BINARY_DIR}/reaktor.exp"
            "-Wl,-undefined,dynamic_lookup")
        target_link_libraries(reaktor_shared INTERFACE SDL3::Headers)
    else()
        set_target_properties(reaktor_shared PROPERTIES OUTPUT_NAME reaktor)
        target_link_libraries(reaktor_shared PRIVATE
            -Wl,--whole-archive ${_so_files} -Wl,--no-whole-archive
            $<TARGET_PROPERTY:reaktor_runtime,INTERFACE_LINK_LIBRARIES>)
        target_link_options(reaktor_shared PRIVATE
            "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/tools/reaktor.map")
        target_link_libraries(reaktor_shared INTERFACE ${REAKTOR_SDL})
    endif()
    target_include_directories(reaktor_shared INTERFACE
        $<TARGET_PROPERTY:reaktor_runtime,INTERFACE_INCLUDE_DIRECTORIES>)
    target_compile_definitions(reaktor_shared INTERFACE
        $<TARGET_PROPERTY:reaktor_runtime,INTERFACE_COMPILE_DEFINITIONS>)
endif()

function(reaktor_add_app name)
    cmake_parse_arguments(RA "CONSOLE;STATIC" "" "SOURCES;MODULES;ASSETS" ${ARGN})
    if(RA_CONSOLE)
        add_executable(${name} ${RA_SOURCES} ${REAKTOR_APP_RESOURCES})
    else()
        add_executable(${name} WIN32 ${RA_SOURCES} ${REAKTOR_APP_RESOURCES})
    endif()
    if(NOT RA_MODULES AND NOT "MODULES" IN_LIST RA_KEYWORDS_MISSING_VALUES)
        set(RA_MODULES a11y locale text settings tray popups notify print inspector)
    endif()
    set(_mods "")
    foreach(_m a11y locale text settings tray popups notify print inspector)
        if(_m IN_LIST RA_MODULES)
            list(APPEND _mods reaktor_${_m})
        else()
            list(APPEND _mods reaktor_${_m}_none)
        endif()
    endforeach()
    # STATIC: a test that reaches past include/reaktor/ links the archives even
    # in a shared build, so libreaktor.so need not export what it reaches.
    if(REAKTOR_SHARED AND NOT RA_STATIC)
        target_link_libraries(${name} PRIVATE ${_mods} reaktor_shared)
        set_target_properties(${name} PROPERTIES ENABLE_EXPORTS ON)
        if(APPLE)
            # Kept through -dead_strip and visible to the framework's lookups.
            target_link_options(${name} PRIVATE -Wl,-export_dynamic)
        endif()
    else()
        target_link_libraries(${name} PRIVATE reaktor_runtime ${_mods})
    endif()
    if(MSVC)
        target_compile_options(${name} PRIVATE /we4013)
    elseif(APPLE)
        target_link_options(${name} PRIVATE -Wl,-dead_strip)
    elseif(NOT EMSCRIPTEN)
        target_link_options(${name} PRIVATE -Wl,--gc-sections)
    endif()
    set_target_properties(${name} PROPERTIES
        RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}")
    if(EMSCRIPTEN)
        set(_pre "")
        foreach(_a IN LISTS RA_ASSETS)
            string(REGEX REPLACE "@.*$" "" _src "${_a}")
            string(REGEX REPLACE "^[^@]*" "" _dst "${_a}")
            get_filename_component(_src "${_src}" ABSOLUTE
                                   BASE_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
            list(APPEND _pre "SHELL:--preload-file ${_src}${_dst}")
            if(IS_DIRECTORY "${_src}")
                file(GLOB_RECURSE _deps CONFIGURE_DEPENDS "${_src}/*")
            else()
                set(_deps "${_src}")
            endif()
            set_property(TARGET ${name} APPEND PROPERTY LINK_DEPENDS ${_deps})
        endforeach()
        set_target_properties(${name} PROPERTIES SUFFIX ".html")
        target_compile_options(${name} PRIVATE -Oz)
        target_link_options(${name} PRIVATE
            ${_pre}
            -sALLOW_MEMORY_GROWTH=1
            -sINITIAL_MEMORY=64MB
            -sSTACK_SIZE=4MB
            -sMIN_WEBGL_VERSION=2
            -sMAX_WEBGL_VERSION=2
            -sEXIT_RUNTIME=0
            -Oz
            --closure 1
            "SHELL:--shell-file ${REAKTOR_SOURCE_DIR}/tools/shell.html")
        set_property(TARGET ${name} APPEND PROPERTY LINK_DEPENDS
                     "${REAKTOR_SOURCE_DIR}/tools/shell.html"
                     "${REAKTOR_SOURCE_DIR}/tools/web-pre.js")
    endif()
endfunction()

if(REAKTOR_SAMPLES)
reaktor_add_app(showcase SOURCES
    samples/showcase/shell.c
    samples/showcase/shortcuts.c
    samples/showcase/showcase.c
    samples/showcase/page_animation.c
    samples/showcase/page_buttons.c
    samples/showcase/page_diagnostics.c
    samples/showcase/page_display.c
    samples/showcase/page_inputs.c
    samples/showcase/page_layout.c
    samples/showcase/page_popups.c
    samples/showcase/page_styling.c
    samples/showcase/page_translations.c)
target_include_directories(showcase PRIVATE samples/showcase)

reaktor_add_app(simple MODULES none SOURCES samples/simple/simple.c)
reaktor_add_app(notepad MODULES settings popups print SOURCES samples/notepad/notepad.c)
if(NOT EMSCRIPTEN)
    reaktor_add_app(bench MODULES none SOURCES samples/bench/bench.c)
    reaktor_add_app(launchtest STATIC MODULES settings popups print SOURCES tests/launchtest.c)
    reaktor_add_app(uitest MODULES none SOURCES tests/uitest.c)
    reaktor_add_app(skiptest MODULES none SOURCES tests/skiptest.c)
    reaktor_add_app(damagetest STATIC MODULES none SOURCES tests/damagetest.c)
    reaktor_add_app(damagetest_text STATIC MODULES text SOURCES tests/damagetest.c)
    set_target_properties(launchtest PROPERTIES EXCLUDE_FROM_ALL ON)
endif()

if(EMSCRIPTEN)
    target_compile_options(reaktor_runtime PRIVATE -Oz)
    target_compile_options(plutovg PRIVATE -Oz)
    target_compile_options(plutosvg PRIVATE -Oz)
    target_compile_options(freetype PRIVATE -Oz)
    target_compile_options(reaktor_core PRIVATE -Oz)
    if(TARGET mojibake_lib)
        target_compile_options(mojibake_lib PRIVATE -Oz)
    endif()
    if(TARGET kb_text_shape)
        target_compile_options(kb_text_shape PRIVATE -Oz)
    endif()

    set(WASM_ASSETS "")
    file(GLOB _reaktor_srcs "${CMAKE_CURRENT_SOURCE_DIR}/core/*.h"
                      "${CMAKE_CURRENT_SOURCE_DIR}/core/*/*.c"
                      "${CMAKE_CURRENT_SOURCE_DIR}/core/*/*.h"
                      "${CMAKE_CURRENT_SOURCE_DIR}/platform/*.c"
                      "${CMAKE_CURRENT_SOURCE_DIR}/platform/*.h"
                      "${CMAKE_CURRENT_SOURCE_DIR}/platform/*/*.c"
                      "${CMAKE_CURRENT_SOURCE_DIR}/runtime/*.c"
                      "${CMAKE_CURRENT_SOURCE_DIR}/samples/*/*.c"
                      "${CMAKE_CURRENT_SOURCE_DIR}/samples/*/*.h")
    foreach(_s IN LISTS _reaktor_srcs)
        file(STRINGS "${_s}" _lines REGEX "(external|assets)/[^\"]*\\.(css|ttf|otf|svg|png)")
        foreach(_l IN LISTS _lines)
            string(REGEX MATCHALL "(external|assets)/[A-Za-z0-9_/.-]*\\.(css|ttf|otf|svg|png)"
                   _paths "${_l}")
            list(APPEND WASM_ASSETS ${_paths})
        endforeach()
    endforeach()
    list(REMOVE_DUPLICATES WASM_ASSETS)

    set(_fallback_font "assets/fonts/MPLUS1p-Regular.ttf")
    list(REMOVE_ITEM WASM_ASSETS "${_fallback_font}" ${REAKTOR_BUILTINS})
    set(WASM_MODULES "")
    if(REAKTOR_TEXT AND REAKTOR_LOCALE)
        list(APPEND WASM_MODULES
             "SHELL:--preload-file ${CMAKE_CURRENT_SOURCE_DIR}/${_fallback_font}@/${_fallback_font}")
    endif()
    if(REAKTOR_LOCALE AND NOT REAKTOR_LOCALE_EMBED)
        list(APPEND WASM_MODULES
             "SHELL:--preload-file ${CMAKE_CURRENT_SOURCE_DIR}/assets/locale@/assets/locale")
    endif()

    set(WASM_ICONS "")
    foreach(_s IN LISTS _reaktor_srcs)
        file(STRINGS "${_s}" _lines REGEX "[a-z0-9-]+-outline")
        foreach(_l IN LISTS _lines)
            string(REGEX MATCHALL "[a-z0-9]+(-[a-z0-9]+)*-outline" _n "${_l}")
            list(APPEND WASM_ICONS ${_n})
        endforeach()
        file(STRINGS "${_s}" _lines REGEX "\"[a-z0-9]+(-[a-z0-9]+)*\"")
        foreach(_l IN LISTS _lines)
            string(REGEX MATCHALL "\"[a-z0-9]+(-[a-z0-9]+)*\"" _n "${_l}")
            foreach(_q IN LISTS _n)
                string(REPLACE "\"" "" _q "${_q}")
                list(APPEND WASM_ICONS "${_q}")
            endforeach()
        endforeach()
    endforeach()
    list(REMOVE_DUPLICATES WASM_ICONS)
    list(LENGTH WASM_ASSETS _asset_count)

    set(WASM_PRELOAD "")
    foreach(_a IN LISTS WASM_ASSETS)
        if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${_a}")
            string(APPEND WASM_PRELOAD
                   "--preload-file \"${CMAKE_CURRENT_SOURCE_DIR}/${_a}@/${_a}\"\n")
        endif()
    endforeach()
    set(_icon_count 0)
    foreach(_i IN LISTS WASM_ICONS)
        set(_rel "external/ionicons/src/svg/${_i}.svg")
        list(FIND REAKTOR_BUILTINS "${_rel}" _builtin)
        if(_builtin EQUAL -1 AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${_rel}")
            string(APPEND WASM_PRELOAD
                   "--preload-file \"${CMAKE_CURRENT_SOURCE_DIR}/${_rel}@/${_rel}\"\n")
            math(EXPR _icon_count "${_icon_count} + 1")
        endif()
    endforeach()
    message(STATUS "wasm: packaging ${_asset_count} assets and ${_icon_count} icons")

    # A response file: the list outgrows Windows' 8191-character command line.
    set(_rsp "${CMAKE_BINARY_DIR}/wasm-assets.rsp")
    file(GENERATE OUTPUT "${_rsp}" CONTENT "${WASM_PRELOAD}")
    foreach(_app showcase simple notepad)
        target_link_options(${_app} PRIVATE "@${_rsp}")
        set_property(TARGET ${_app} APPEND PROPERTY LINK_DEPENDS "${_rsp}")
    endforeach()
    target_link_options(showcase PRIVATE ${WASM_MODULES})

    add_custom_command(TARGET showcase POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E copy_if_different
            "${CMAKE_CURRENT_SOURCE_DIR}/assets/icons/reaktor-icon.svg"
            "${CMAKE_BINARY_DIR}/reaktor-icon.svg"
        COMMAND ${CMAKE_COMMAND} -E copy_if_different
            "${CMAKE_CURRENT_SOURCE_DIR}/assets/icons/reaktor-icon.png"
            "${CMAKE_BINARY_DIR}/reaktor-icon.png"
        COMMAND ${CMAKE_COMMAND} -E copy_if_different
            "${CMAKE_CURRENT_SOURCE_DIR}/tools/keylog.js"
            "${CMAKE_BINARY_DIR}/keylog.js"
        COMMAND ${CMAKE_COMMAND} -E copy_if_different
            "${CMAKE_CURRENT_SOURCE_DIR}/tools/shell.js"
            "${CMAKE_BINARY_DIR}/shell.js"
        COMMENT "Copying page assets"
        VERBATIM)
endif()

if(MSVC)
    # Nuklear's NK_ALIGNOF takes the offset of a member of an unnamed struct.
    set_property(SOURCE core/render/nk_impl.c APPEND PROPERTY COMPILE_OPTIONS /wd4116)
    # nuklear.h combines constants of different enums in its own declarations.
    target_compile_options(reaktor_headers INTERFACE /wd5287)
    target_compile_options(showcase PRIVATE /wd4101)
    target_compile_definitions(showcase PRIVATE _CRT_SECURE_NO_WARNINGS)
endif()

if(APPLE AND NOT EMSCRIPTEN)
    configure_file(
        "${CMAKE_CURRENT_SOURCE_DIR}/tools/Info.plist.in"
        "${CMAKE_BINARY_DIR}/Info.plist" @ONLY)

    add_custom_command(TARGET showcase POST_BUILD
        COMMAND "${CMAKE_CURRENT_SOURCE_DIR}/tools/make-bundle.sh"
                "${CMAKE_BINARY_DIR}/reaktor.app"
                "$<TARGET_FILE:showcase>"
                "${CMAKE_BINARY_DIR}/Info.plist"
                "${CMAKE_CURRENT_SOURCE_DIR}"
        COMMENT "Assembling reaktor.app"
        VERBATIM)
endif()
endif()

if(MSVC)
    target_compile_options(plutovg PRIVATE /wd4244 /wd4267 /wd4018)
    target_compile_definitions(reaktor_core PRIVATE _CRT_SECURE_NO_WARNINGS)
endif()

add_library(reaktor_modules STATIC)
target_link_libraries(reaktor_modules PRIVATE reaktor_runtime reaktor_a11y reaktor_locale reaktor_text
                      reaktor_settings reaktor_tray reaktor_popups reaktor_notify reaktor_print
                      reaktor_inspector)
set_target_properties(reaktor_modules PROPERTIES EXCLUDE_FROM_ALL ON)

set(_parts reaktor_runtime reaktor_core reaktor_modules plutosvg plutovg freetype onlay
           SDL3-static)
foreach(_t mojibake_lib kb_text_shape)
    if(TARGET ${_t})
        list(APPEND _parts ${_t})
    endif()
endforeach()
set(_files "")
foreach(_t IN LISTS _parts)
    list(APPEND _files "$<TARGET_FILE:${_t}>")
endforeach()

function(reaktor_outside_links)
    set(_libs "")
    set(_dirs "")
    set(_opts "")
    set(_weak "")
    set(_seen "")
    set(_refound "")
    set(_todo ${ARGN})
    while(_todo)
        list(POP_FRONT _todo _t)
        get_target_property(_real ${_t} ALIASED_TARGET)
        if(_real)
            set(_t ${_real})
        endif()
        # libreaktor.a carries SDL3-static in the shared SDL's place.
        if(_t IN_LIST _seen OR _t STREQUAL "SDL3-shared")
            continue()
        endif()
        list(APPEND _seen ${_t})
        get_target_property(_type ${_t} TYPE)
        get_target_property(_imported ${_t} IMPORTED)
        set(_items "")
        if(_imported AND NOT _type STREQUAL "INTERFACE_LIBRARY")
            set(_props IMPORTED_IMPLIB_RELEASE IMPORTED_IMPLIB IMPORTED_LOCATION_RELEASE
                       IMPORTED_LOCATION)
            get_target_property(_cfgs ${_t} IMPORTED_CONFIGURATIONS)
            if(_cfgs)
                foreach(_c IN LISTS _cfgs)
                    list(APPEND _props IMPORTED_IMPLIB_${_c} IMPORTED_LOCATION_${_c})
                endforeach()
            endif()
            set(_file "")
            foreach(_p IN LISTS _props)
                get_target_property(_f ${_t} ${_p})
                if(_f)
                    set(_file "${_f}")
                    break()
                endif()
            endforeach()
            if(_file)
                list(APPEND _libs "${_file}")
            else()
                message(WARNING "libreaktor finds no file for ${_t}, which its parts link")
            endif()
        elseif(_t IN_LIST ARGN)
            get_target_property(_v ${_t} LINK_LIBRARIES)
            if(_v)
                list(APPEND _items ${_v})
            endif()
        elseif(NOT _type MATCHES "^(INTERFACE|OBJECT)_LIBRARY$")
            message(WARNING "libreaktor leaves out ${_t}, which its parts link")
        endif()
        foreach(_p INTERFACE_LINK_LIBRARIES INTERFACE_LINK_OPTIONS INTERFACE_LINK_DIRECTORIES)
            get_target_property(_v ${_t} ${_p})
            if(NOT _v)
                continue()
            endif()
            if(_p STREQUAL "INTERFACE_LINK_LIBRARIES")
                list(APPEND _items ${_v})
            elseif(_v MATCHES "\\$<")
                message(WARNING "libreaktor cannot carry ${_t}'s ${_p}: ${_v}")
            elseif(_p STREQUAL "INTERFACE_LINK_OPTIONS")
                list(APPEND _opts ${_v})
            else()
                list(APPEND _dirs ${_v})
            endif()
        endforeach()
        foreach(_i IN LISTS _items)
            if(_i MATCHES "^\\$<LINK_ONLY:(.*)>$")
                set(_i "${CMAKE_MATCH_1}")
            endif()
            if(_i MATCHES "^\\$<(TARGET_NAME|BUILD_INTERFACE):(.*)>$")
                set(_i "${CMAKE_MATCH_2}")
            endif()
            if(_i MATCHES "^\\$<INSTALL_INTERFACE:")
                continue()
            endif()
            # A dependency's own directory may have found it: its targets are not seen here.
            if(NOT TARGET "${_i}" AND _i MATCHES "^([A-Za-z0-9_]+)::")
                set(_pkg "${CMAKE_MATCH_1}")
                if(NOT _pkg STREQUAL "PkgConfig" AND NOT _pkg IN_LIST _refound)
                    list(APPEND _refound ${_pkg})
                    find_package(${_pkg} QUIET)
                endif()
            endif()
            if(TARGET "${_i}")
                list(APPEND _todo "${_i}")
            elseif(_i MATCHES "^PkgConfig::(.+)$")
                set(_pc_prefix "${CMAKE_MATCH_1}")
                list(APPEND _libs ${${_pc_prefix}_LIBRARIES})
                list(APPEND _dirs ${${_pc_prefix}_LIBRARY_DIRS})
                list(APPEND _opts ${${_pc_prefix}_LDFLAGS_OTHER})
            elseif(_i MATCHES "::")
                message(WARNING "libreaktor cannot find ${_i}, which ${_t} links")
            elseif(_i MATCHES "^\\$<LINK_LIBRARY:FRAMEWORK,(.*)>$")
                list(APPEND _libs "-framework ${CMAKE_MATCH_1}")
            elseif(_i MATCHES "^\\$<LINK_LIBRARY:WEAK_FRAMEWORK,(.*)>$")
                list(APPEND _weak "${CMAKE_MATCH_1}")
            elseif(_i MATCHES "\\$<")
                message(WARNING "libreaktor cannot carry ${_t}'s link to ${_i}")
            elseif(_i)
                list(APPEND _libs "${_i}")
            endif()
        endforeach()
    endwhile()

    set(_named "")
    foreach(_l IN LISTS _libs)
        if(IS_ABSOLUTE "${_l}" AND _l MATCHES "/lib([^/]+)\\.(so|dylib|tbd)(\\.[0-9.]+)?$")
            list(APPEND _named "${CMAKE_MATCH_1}")
            get_filename_component(_d "${_l}" DIRECTORY)
            string(FIND "${_d}" "${CMAKE_OSX_SYSROOT}" _in_sdk)
            if(NOT (CMAKE_OSX_SYSROOT AND _in_sdk EQUAL 0))
                list(APPEND _dirs "${_d}")
            endif()
        else()
            list(APPEND _named "${_l}")
        endif()
    endforeach()
    list(REMOVE_DUPLICATES _named)
    # A cross build found them under the sysroot; the package names where they are on the target.
    if(CMAKE_SYSROOT)
        set(_stripped "")
        foreach(_d IN LISTS _dirs)
            string(FIND "${_d}" "${CMAKE_SYSROOT}" _in_sysroot)
            if(_in_sysroot EQUAL 0)
                string(LENGTH "${CMAKE_SYSROOT}" _n)
                string(SUBSTRING "${_d}" ${_n} -1 _d)
            endif()
            list(APPEND _stripped "${_d}")
        endforeach()
        set(_dirs ${_stripped})
    endif()
    list(REMOVE_DUPLICATES _dirs)
    foreach(_d IN LISTS CMAKE_C_IMPLICIT_LINK_DIRECTORIES CMAKE_PLATFORM_IMPLICIT_LINK_DIRECTORIES)
        list(REMOVE_ITEM _dirs "${_d}")
    endforeach()
    list(REMOVE_DUPLICATES _opts)
    list(REMOVE_DUPLICATES _weak)

    set(_pc "")
    foreach(_d IN LISTS _dirs)
        string(APPEND _pc " -L${_d} -Wl,-rpath,${_d}")
    endforeach()
    foreach(_l IN LISTS _named)
        if(_l MATCHES "^-" OR IS_ABSOLUTE "${_l}")
            string(APPEND _pc " ${_l}")
        else()
            string(APPEND _pc " -l${_l}")
        endif()
    endforeach()
    foreach(_w IN LISTS _weak)
        list(APPEND _opts "SHELL:-Xlinker -weak_framework -Xlinker ${_w}")
    endforeach()
    foreach(_o IN LISTS _opts)
        string(REGEX REPLACE "^SHELL:" "" _o "${_o}")
        string(REGEX REPLACE "-Xlinker -weak_framework -Xlinker " "-Wl,-weak_framework," _o "${_o}")
        string(APPEND _pc " ${_o}")
    endforeach()

    set(REAKTOR_LINK_LIBS "${_named}" PARENT_SCOPE)
    set(REAKTOR_LINK_DIRS "${_dirs}" PARENT_SCOPE)
    set(REAKTOR_OUTSIDE_OPTIONS "${_opts}" PARENT_SCOPE)
    set(REAKTOR_PC_LIBS "${_pc}" PARENT_SCOPE)
endfunction()

reaktor_outside_links(${_parts})
set(REAKTOR_LINK_OPTIONS ${REAKTOR_OUTSIDE_OPTIONS})
if(EMSCRIPTEN)
    set(_wasm -sALLOW_MEMORY_GROWTH=1 -sINITIAL_MEMORY=64MB -sSTACK_SIZE=4MB
              -sMIN_WEBGL_VERSION=2 -sMAX_WEBGL_VERSION=2 -sEXIT_RUNTIME=0)
    list(APPEND REAKTOR_LINK_OPTIONS ${_wasm} -lidbfs.js
         "SHELL:--pre-js \${_reaktor_prefix}/share/reaktor/web-pre.js")
    string(JOIN " " _wasm ${_wasm})
    string(APPEND REAKTOR_PC_LIBS
           " ${_wasm} -lidbfs.js --pre-js \${pcfiledir}/../../share/reaktor/web-pre.js")
endif()
string(JOIN " " _beside ${REAKTOR_LINK_LIBS} ${REAKTOR_LINK_DIRS} ${REAKTOR_LINK_OPTIONS})
message(STATUS "libreaktor: a program links beside it ${_beside}")

if(MSVC)
    set(REAKTOR_LIB_NAME reaktor.lib)
else()
    set(REAKTOR_LIB_NAME libreaktor.a)
endif()
set(_lib "${CMAKE_BINARY_DIR}/lib/${REAKTOR_LIB_NAME}")
if(MSVC)
    set(_merge "${CMAKE_AR}" /NOLOGO "/OUT:${_lib}" ${_files})
elseif(APPLE)
    find_program(REAKTOR_LIBTOOL NAMES libtool PATHS /usr/bin NO_DEFAULT_PATH)
    set(_merge "${REAKTOR_LIBTOOL}" -static -o "${_lib}" ${_files})
else()
    set(_mri "CREATE ${_lib}\n")
    foreach(_f IN LISTS _files)
        string(APPEND _mri "ADDLIB ${_f}\n")
    endforeach()
    string(APPEND _mri "SAVE\nEND\n")
    file(GENERATE OUTPUT "${CMAKE_BINARY_DIR}/reaktor.mri" CONTENT "${_mri}")
    set(_merge "${CMAKE_COMMAND}" "-DAR=${CMAKE_AR}" "-DMRI=${CMAKE_BINARY_DIR}/reaktor.mri"
               -P "${CMAKE_CURRENT_SOURCE_DIR}/tools/merge-lib.cmake")
endif()
add_custom_command(OUTPUT "${_lib}"
    COMMAND "${CMAKE_COMMAND}" -E make_directory "${CMAKE_BINARY_DIR}/lib"
    COMMAND "${CMAKE_COMMAND}" -E remove -f "${_lib}"
    COMMAND ${_merge}
    DEPENDS ${_parts}
    COMMENT "Merging libreaktor"
    VERBATIM)
add_custom_target(libreaktor DEPENDS "${_lib}")

if(REAKTOR_SHARED)
    set(_mod_parts reaktor_modules)
    foreach(_t mojibake_lib kb_text_shape)
        if(TARGET ${_t})
            list(APPEND _mod_parts ${_t})
        endif()
    endforeach()
    set(_mod_lib "${CMAKE_BINARY_DIR}/lib/libreaktor-modules.a")
    if(APPLE)
        set(_mod_files "")
        foreach(_t IN LISTS _mod_parts)
            list(APPEND _mod_files "$<TARGET_FILE:${_t}>")
        endforeach()
        set(_mod_merge "${REAKTOR_LIBTOOL}" -static -o "${_mod_lib}" ${_mod_files})
    else()
        set(_mri "CREATE ${_mod_lib}\n")
        foreach(_t IN LISTS _mod_parts)
            string(APPEND _mri "ADDLIB $<TARGET_FILE:${_t}>\n")
        endforeach()
        string(APPEND _mri "SAVE\nEND\n")
        file(GENERATE OUTPUT "${CMAKE_BINARY_DIR}/reaktor-modules.mri" CONTENT "${_mri}")
        set(_mod_merge "${CMAKE_COMMAND}" "-DAR=${CMAKE_AR}"
                       "-DMRI=${CMAKE_BINARY_DIR}/reaktor-modules.mri"
                       -P "${CMAKE_CURRENT_SOURCE_DIR}/tools/merge-lib.cmake")
    endif()
    add_custom_command(OUTPUT "${_mod_lib}"
        COMMAND "${CMAKE_COMMAND}" -E make_directory "${CMAKE_BINARY_DIR}/lib"
        COMMAND "${CMAKE_COMMAND}" -E remove -f "${_mod_lib}"
        COMMAND ${_mod_merge}
        DEPENDS ${_mod_parts}
        COMMENT "Merging libreaktor-modules"
        VERBATIM)
    add_custom_target(libreaktor_modules DEPENDS "${_mod_lib}")
    add_dependencies(libreaktor reaktor_shared libreaktor_modules)
    if(REAKTOR_SHARED_SDL)
        add_dependencies(libreaktor SDL3-shared)
        # Both archives and libraries sit in one lib/: -l would pick the .so.
        set(REAKTOR_PC_LINK "-l:libreaktor.a")
    else()
        # A framework is not found by -l, so libreaktor.a still is.
        set(REAKTOR_PC_LINK "-lreaktor")
    endif()
else()
    set(REAKTOR_PC_LINK "-lreaktor")
endif()

option(REAKTOR_INSTALL "Install libreaktor's files" ${_reaktor_top})
if(REAKTOR_INSTALL)
    include(CMakePackageConfigHelpers)
    configure_file(tools/reaktorConfig.cmake.in "${CMAKE_BINARY_DIR}/reaktorConfig.cmake" @ONLY)
    write_basic_package_version_file("${CMAKE_BINARY_DIR}/reaktorConfigVersion.cmake"
        COMPATIBILITY SameMinorVersion)
    install(FILES "${_lib}" DESTINATION lib COMPONENT libreaktor OPTIONAL)
    if(REAKTOR_SHARED)
        if(APPLE)
            install(TARGETS reaktor_shared FRAMEWORK DESTINATION Frameworks COMPONENT libreaktor)
        else()
            install(TARGETS reaktor_shared SDL3-shared
                    LIBRARY DESTINATION lib COMPONENT libreaktor NAMELINK_COMPONENT libreaktor)
        endif()
        install(FILES "${_mod_lib}" DESTINATION lib COMPONENT libreaktor OPTIONAL)
    endif()
    install(DIRECTORY include/reaktor DESTINATION include COMPONENT libreaktor)
    install(FILES "${TP}/nuklear/nuklear.h" DESTINATION include COMPONENT libreaktor)
    install(FILES "${TP}/nukanim/nukanim.h" DESTINATION include COMPONENT libreaktor)
    install(DIRECTORY "${TP}/SDL/include/SDL3" DESTINATION include COMPONENT libreaktor)
    install(FILES "${CMAKE_BINARY_DIR}/reaktorConfig.cmake"
                  "${CMAKE_BINARY_DIR}/reaktorConfigVersion.cmake"
            DESTINATION lib/cmake/reaktor COMPONENT libreaktor)
    if(NOT MSVC)
        configure_file(tools/reaktor.pc.in "${CMAKE_BINARY_DIR}/reaktor.pc" @ONLY)
        install(FILES "${CMAKE_BINARY_DIR}/reaktor.pc" DESTINATION lib/pkgconfig
                COMPONENT libreaktor)
        if(REAKTOR_SHARED_SDL)
            configure_file(tools/reaktor-shared.pc.in "${CMAKE_BINARY_DIR}/reaktor-shared.pc" @ONLY)
            install(FILES "${CMAKE_BINARY_DIR}/reaktor-shared.pc" DESTINATION lib/pkgconfig
                    COMPONENT libreaktor)
        endif()
    endif()
    install(DIRECTORY "${CMAKE_BINARY_DIR}/licenses/" DESTINATION share/reaktor/licenses
            COMPONENT libreaktor)
    install(FILES assets/fonts/Aileron-Notice.txt DESTINATION share/reaktor/licenses
            COMPONENT libreaktor)
    install(FILES docs/NOTICE.md DESTINATION share/reaktor COMPONENT libreaktor)
    if(EMSCRIPTEN)
        install(FILES tools/web-pre.js DESTINATION share/reaktor COMPONENT libreaktor)
    endif()
    if(UNIX AND NOT APPLE AND NOT EMSCRIPTEN)
        foreach(_fmt deb rpm)
            add_custom_target(${_fmt}
                COMMAND sh "${CMAKE_CURRENT_SOURCE_DIR}/tools/libreaktor-pkg.sh"
                        -f ${_fmt} -b "${CMAKE_BINARY_DIR}" -o "${CMAKE_BINARY_DIR}/dist"
                DEPENDS libreaktor
                COMMENT "Packing libreaktor as a .${_fmt}"
                USES_TERMINAL VERBATIM)
        endforeach()
    endif()
endif()
