cmake_minimum_required(VERSION 3.21)
# the Mac release this port matches
project(digi35_win VERSION 0.11.8 LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# The same Qt on every machine: QRhi's API may change between Qt versions.
# QRhi is in Qt's private Gui module, which is what the warning would say.
set(QT_NO_PRIVATE_MODULE_WARNING ON)
find_package(Qt6 6.12.0 EXACT REQUIRED COMPONENTS Gui GuiPrivate ShaderTools Widgets Network Multimedia Sql)
qt_standard_project_setup()

set(ENGINE_SOURCES
    engine/Dump.cpp
    engine/HighlightRecovery.cpp
    engine/Clarity.cpp
    engine/ColorContrast.cpp
    engine/MatchedCurve.cpp
    engine/Sharpen.cpp
    engine/ColorTools.cpp
    engine/ColorMix.cpp
    engine/LabScan.cpp
    engine/NegativeConvert.cpp
    engine/SlideScan.cpp
    engine/Dust.cpp
    engine/HighlightsOpposed.cpp
    engine/Demosaic.cpp
    engine/DemosaicRCD.cpp
    engine/DemosaicAmaze.cpp
    engine/DynamicRange.cpp
    engine/Frames.cpp
    engine/CameraProfiles.cpp
    engine/Setup.cpp
    engine/Filters.cpp
    engine/GpuGraph.cpp
    engine/FilmRenderer.cpp
    engine/Packs.cpp
    engine/Recipe.cpp
    engine/PrintCurves.cpp
    engine/FilmMath.cpp
    engine/ToneCurve.cpp
    engine/SetupBuilder.cpp
    engine/FrameGeometry.cpp
    engine/MaskRasterizer.cpp
    engine/LogFormats.cpp
    engine/LookLUT.cpp
    engine/AutoGeometry.cpp
    engine/Perspective.cpp
)

# The kernels, GLSL 440 compute, baked by qsb into SPIR-V (Vulkan), HLSL 5.0
# (Direct3D 12 and 11) and MSL (Metal). No GLSL for OpenGL: the port runs on
# neither. On Windows the HLSL is compiled when the program is built (fxc), so
# no kernel is compiled while it runs.
set(DIGI35_PRECOMPILE "")
if(WIN32)
    set(DIGI35_PRECOMPILE PRECOMPILE)
endif()
set(ENGINE_KERNELS
    engine/shaders/film_expose.comp
    engine/shaders/scatter_mix.comp
    engine/shaders/accumulate_scaled.comp
    engine/shaders/halation_add.comp
    engine/shaders/film_log.comp
    engine/shaders/film_develop.comp
    engine/shaders/couplers_amount.comp
    engine/shaders/film_develop_couplers.comp
    engine/shaders/film_grain_layer.comp
    engine/shaders/grain_convolve.comp
    engine/shaders/grain_convolve_add.comp
    engine/shaders/print_and_scan.comp
    engine/shaders/grain_mirror.comp
    engine/shaders/grain_even_mean.comp
    engine/shaders/grain_restore_mean.comp
    engine/shaders/encode_display.comp
    engine/shaders/apply_curves.comp
    engine/shaders/apply_presence.comp
    engine/shaders/apply_basic.comp
    engine/shaders/histogram_rgb.comp
    engine/shaders/apply_geometry.comp
    engine/shaders/effects_blur.comp
    engine/shaders/effects_bloom_select.comp
    engine/shaders/effects_bloom_composite.comp
    engine/shaders/effects_mix.comp
    engine/shaders/effects_glow_select.comp
    engine/shaders/effects_halation_select.comp
    engine/shaders/effects_light_combine.comp
    engine/shaders/motion_grade.comp
    engine/shaders/motion_screen.comp
    engine/shaders/motion_luma.comp
    engine/shaders/motion_chroma.comp
    engine/shaders/digital_expose.comp
    engine/shaders/digital_print.comp
    engine/shaders/scene_drag_gain.comp
)

# LibRaw, compiled in (cmake/LibRaw.cmake): the fallback decoder.
include(cmake/LibRaw.cmake)
add_library(digi35_libraw STATIC ${LIBRAW_SOURCES})
target_include_directories(digi35_libraw PUBLIC third_party/LibRaw)
target_compile_definitions(digi35_libraw PUBLIC LIBRAW_NODLL PRIVATE _CRT_SECURE_NO_WARNINGS)
set_target_properties(digi35_libraw PROPERTIES CXX_STANDARD 17)
if(MSVC)
    target_compile_options(digi35_libraw PRIVATE /w)
else()
    target_compile_options(digi35_libraw PRIVATE -w)
endif()

# zlib and libjpeg-turbo, for the DNGs LibRaw reads only with them: Deflate
# (floating point: Lightroom's HDR and panorama merges) and lossy JPEG
# (Lightroom's Smart Previews, lossy-compressed DNGs). Without them the first
# fail and the second decode to nothing.
if(NOT CMAKE_C_COMPILER)
    set(CMAKE_C_COMPILER "${CMAKE_CXX_COMPILER}")
endif()
enable_language(C)
set(DIGI35_ZLIB_DIR ${CMAKE_CURRENT_SOURCE_DIR}/third_party/zlib-1.3.2)
add_library(digi35_zlib STATIC
    ${DIGI35_ZLIB_DIR}/adler32.c ${DIGI35_ZLIB_DIR}/compress.c ${DIGI35_ZLIB_DIR}/crc32.c ${DIGI35_ZLIB_DIR}/deflate.c
    ${DIGI35_ZLIB_DIR}/gzclose.c ${DIGI35_ZLIB_DIR}/gzlib.c ${DIGI35_ZLIB_DIR}/gzread.c ${DIGI35_ZLIB_DIR}/gzwrite.c
    ${DIGI35_ZLIB_DIR}/infback.c ${DIGI35_ZLIB_DIR}/inffast.c ${DIGI35_ZLIB_DIR}/inflate.c ${DIGI35_ZLIB_DIR}/inftrees.c
    ${DIGI35_ZLIB_DIR}/trees.c ${DIGI35_ZLIB_DIR}/uncompr.c ${DIGI35_ZLIB_DIR}/zutil.c)
target_include_directories(digi35_zlib PUBLIC ${DIGI35_ZLIB_DIR})
target_compile_definitions(digi35_zlib PRIVATE _CRT_SECURE_NO_WARNINGS _CRT_NONSTDC_NO_DEPRECATE)
if(MSVC)
    target_compile_options(digi35_zlib PRIVATE /w)
else()
    target_compile_options(digi35_zlib PRIVATE -w)
endif()
# libjpeg-turbo builds only on its own (its CMakeLists refuses
# add_subdirectory), so as an external project: the static library alone,
# without SIMD, so no assembler is needed.
include(ExternalProject)
set(DIGI35_JPEG_PREFIX ${CMAKE_CURRENT_BINARY_DIR}/libjpeg-turbo)
if(MSVC)
    set(DIGI35_JPEG_LIB ${DIGI35_JPEG_PREFIX}/lib/jpeg-static.lib)
else()
    set(DIGI35_JPEG_LIB ${DIGI35_JPEG_PREFIX}/lib/libjpeg.a)
endif()
ExternalProject_Add(digi35_jpeg_build
    SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/third_party/libjpeg-turbo-3.2.0
    BINARY_DIR ${DIGI35_JPEG_PREFIX}/build
    INSTALL_DIR ${DIGI35_JPEG_PREFIX}
    CMAKE_ARGS
        -DCMAKE_BUILD_TYPE=Release
        -DCMAKE_INSTALL_PREFIX=<INSTALL_DIR>
        -DCMAKE_INSTALL_LIBDIR=lib
        -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}
        -DENABLE_SHARED=OFF -DENABLE_STATIC=ON
        -DWITH_SIMD=OFF -DWITH_TURBOJPEG=OFF -DWITH_TOOLS=OFF -DWITH_TESTS=OFF -DWITH_CRT_DLL=ON
    BUILD_BYPRODUCTS ${DIGI35_JPEG_LIB})
file(MAKE_DIRECTORY ${DIGI35_JPEG_PREFIX}/include)
add_library(digi35_jpeg STATIC IMPORTED)
set_target_properties(digi35_jpeg PROPERTIES IMPORTED_LOCATION ${DIGI35_JPEG_LIB}
                                              INTERFACE_INCLUDE_DIRECTORIES ${DIGI35_JPEG_PREFIX}/include)
add_dependencies(digi35_libraw digi35_jpeg_build)
target_compile_definitions(digi35_libraw PRIVATE USE_ZLIB USE_JPEG)
target_link_libraries(digi35_libraw PUBLIC digi35_zlib digi35_jpeg)

# libjxl, for JPEG XL DNGs (DNG 1.7, newer lossy and lossless ones): LibRaw
# finds their tiles and reads the rest, and engine/RawUnpackLibRaw.cpp decodes
# the tiles, which LibRaw leaves to Adobe's SDK. The project's own Windows
# build (third_party/libjxl-0.12.0-x64-windows/README.txt), its DLLs beside
# the app.
if(WIN32)
    set(DIGI35_JXL_DIR ${CMAKE_CURRENT_SOURCE_DIR}/third_party/libjxl-0.12.0-x64-windows)
    add_library(digi35_jxl INTERFACE)
    target_include_directories(digi35_jxl INTERFACE ${DIGI35_JXL_DIR}/include)
    target_link_libraries(digi35_jxl INTERFACE ${DIGI35_JXL_DIR}/lib/jxl.lib ${DIGI35_JXL_DIR}/lib/jxl_threads.lib)
    target_compile_definitions(digi35_jxl INTERFACE DIGI35_JPEGXL)
    target_link_libraries(digi35_libraw PUBLIC digi35_jxl)
    file(GLOB DIGI35_JXL_DLLS ${DIGI35_JXL_DIR}/bin/*.dll)
    foreach(dll ${DIGI35_JXL_DLLS})
        get_filename_component(name ${dll} NAME)
        configure_file(${dll} ${CMAKE_CURRENT_BINARY_DIR}/${name} COPYONLY)
    endforeach()
endif()

# ONNX Runtime (MIT), for the AI tools: loaded by the program itself at
# their first use (engine/AiRuntime.cpp), its DLLs beside the program; the
# graphics card through Windows' own DirectML.dll.
set(DIGI35_ORT_DIR ${CMAKE_CURRENT_SOURCE_DIR}/third_party/onnxruntime-1.24.4)
add_library(digi35_ort INTERFACE)
target_include_directories(digi35_ort INTERFACE ${DIGI35_ORT_DIR}/include)
set(DIGI35_ORT_DLLS ${DIGI35_ORT_DIR}/bin/onnxruntime.dll ${DIGI35_ORT_DIR}/bin/onnxruntime_providers_shared.dll)
foreach(dll ${DIGI35_ORT_DLLS})
    get_filename_component(name ${dll} NAME)
    configure_file(${dll} ${CMAKE_CURRENT_BINARY_DIR}/${name} COPYONLY)
endforeach()

# RawSpeed, compiled in (cmake/RawSpeed.cmake): the standard decoder.
include(cmake/RawSpeed.cmake)

# The CPU side rounds as the Mac's Swift does, which fuses no multiply and add
# into one instruction; so the Mac's build and the PC's compute alike.
function(digi35_rounding name)
    if(MSVC AND CMAKE_CXX_COMPILER_ID MATCHES "Clang")
        target_compile_options(${name} PRIVATE /clang:-ffp-contract=off)
    elseif(MSVC)
        target_compile_options(${name} PRIVATE /fp:precise)
    else()
        target_compile_options(${name} PRIVATE -Wall -Wextra -ffp-contract=off)
    endif()
endfunction()

function(digi35_tool name main)
    qt_add_executable(${name} ${main} ${ENGINE_SOURCES})
    set_target_properties(${name} PROPERTIES MACOSX_BUNDLE OFF WIN32_EXECUTABLE OFF)
    target_include_directories(${name} PRIVATE engine)
    target_link_libraries(${name} PRIVATE Qt6::Gui Qt6::GuiPrivate)
    digi35_rounding(${name})
    qt_add_shaders(${name} "${name}_kernels"
        NOGLSL
        HLSL 50
        ${DIGI35_PRECOMPILE}
        MSL 12
        BASE engine/shaders
        PREFIX "/shaders"
        FILES ${ENGINE_KERNELS}
    )
endfunction()

# the AI models from the command line (tools/port-ai)
qt_add_executable(digi35-ai tools/port-ai/main.cpp engine/AiRuntime.cpp engine/AiTools.cpp engine/OnnxEdit.cpp
    engine/Dump.cpp)
set_target_properties(digi35-ai PROPERTIES WIN32_EXECUTABLE OFF)
target_include_directories(digi35-ai PRIVATE engine)
target_link_libraries(digi35-ai PRIVATE Qt6::Gui digi35_ort)

digi35_tool(digi35-render tools/port-render/main.cpp)
digi35_tool(digi35-setup tools/port-setup/main.cpp)
digi35_tool(digi35-lut tools/port-lut/main.cpp)
digi35_tool(digi35-checks tools/port-checks/main.cpp)
# the undo steps' names are the app's (EditNames)
target_sources(digi35-checks PRIVATE app/EditNames.cpp app/Vocabulary.cpp app/Presets.cpp app/AppSettings.cpp)
target_include_directories(digi35-checks PRIVATE app)

# The port's RAW decoder, against Apple's (tools/mac-reference/flxdecode).
# On the CPU, and on the GPU with these kernels (GpuDecoder), as the film's.
set(RAW_KERNELS
    engine/shaders/raw_demosaic_mhc.comp
    engine/shaders/raw_demosaic_green.comp
    engine/shaders/raw_demosaic_colours.comp
    engine/shaders/raw_highlight_blocks.comp
    engine/shaders/raw_colour.comp
    engine/shaders/raw_noise_samples.comp
    engine/shaders/raw_repair.comp
    engine/shaders/raw_false_colour.comp
    engine/shaders/raw_cnr_guide.comp
    engine/shaders/raw_cnr_half.comp
    engine/shaders/raw_box.comp
    engine/shaders/raw_cnr_ab.comp
    engine/shaders/raw_cnr_apply.comp
    engine/shaders/raw_sharp_luma.comp
    engine/shaders/raw_blur.comp
    engine/shaders/raw_sharp_energy.comp
    engine/shaders/raw_sharp_apply.comp
    engine/shaders/raw_lens.comp
    engine/shaders/raw_turn.comp
    engine/shaders/raw_bin2.comp
    engine/shaders/raw_cnr_blend.comp
    engine/shaders/raw_lanczos.comp
)
qt_add_executable(digi35-decode tools/port-decode/main.cpp engine/RawUnpackRawSpeed.cpp engine/RawUnpackLibRaw.cpp
    engine/RawDecoder.cpp engine/HighlightsOpposed.cpp engine/Demosaic.cpp engine/DemosaicRCD.cpp engine/DemosaicAmaze.cpp engine/RawDetail.cpp engine/GpuDecoder.cpp engine/AppleColour.cpp engine/LensCorrection.cpp engine/ChromaticAberration.cpp
    engine/Dump.cpp engine/RawDenoise.cpp engine/AiTools.cpp engine/AiRuntime.cpp engine/OnnxEdit.cpp)
set_target_properties(digi35-decode PROPERTIES MACOSX_BUNDLE OFF WIN32_EXECUTABLE OFF)
target_include_directories(digi35-decode PRIVATE engine)
target_link_libraries(digi35-decode PRIVATE Qt6::Gui Qt6::GuiPrivate digi35_rawspeed digi35_libraw digi35_ort)
digi35_rounding(digi35-decode)
qt_add_shaders(digi35-decode "digi35-decode_kernels"
    NOGLSL
    HLSL 50
    ${DIGI35_PRECOMPILE}
    MSL 12
    BASE engine/shaders
    PREFIX "/shaders"
    FILES ${RAW_KERNELS}
)
# Apple's camera profiles (tools/calibrate), next to the programs; the decode
# falls back to the cameras' daylight matrices while there is none
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/engine/data/apple-colour.json)
    configure_file(engine/data/apple-colour.json ${CMAKE_CURRENT_BINARY_DIR}/apple-colour.json COPYONLY)
endif()
# Lensfun's lens database (third_party/lensfun, CC BY-SA 3.0), its XML alone,
# next to the programs: the lens correction's, where a camera has no data of
# its own. The port reads it itself (LensCorrection); Lensfun's library is
# not used.
file(GLOB LENSFUN_DB CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/third_party/lensfun/data/db/*.xml)
foreach(xml ${LENSFUN_DB})
    get_filename_component(name ${xml} NAME)
    configure_file(${xml} ${CMAKE_CURRENT_BINARY_DIR}/lensfun/${name} COPYONLY)
endforeach()

# FFmpeg, for Motion's clips: Homebrew's on a Mac; on Windows the app's own
# LGPL build (tools/ffmpeg/build.sh, into build/ffmpeg, or DIGI35_FFMPEG), its
# libraries copied next to the programs.
if(WIN32)
    set(DIGI35_FFMPEG "${CMAKE_CURRENT_SOURCE_DIR}/build/ffmpeg" CACHE PATH "FFmpeg, as tools/ffmpeg/build.sh builds it")
    set(FFMPEG_DIR "${DIGI35_FFMPEG}")
    if(NOT EXISTS "${FFMPEG_DIR}/lib/avcodec.lib")
        message(FATAL_ERROR "no FFmpeg at ${FFMPEG_DIR}: build it with tools/ffmpeg/build.sh")
    endif()
    add_library(digi35_ffmpeg INTERFACE)
    target_include_directories(digi35_ffmpeg INTERFACE "${FFMPEG_DIR}/include")
    target_link_libraries(digi35_ffmpeg INTERFACE "${FFMPEG_DIR}/lib/avformat.lib" "${FFMPEG_DIR}/lib/avcodec.lib"
                                               "${FFMPEG_DIR}/lib/avutil.lib" "${FFMPEG_DIR}/lib/swscale.lib"
                                               "${FFMPEG_DIR}/lib/swresample.lib")
    file(GLOB FFMPEG_DLLS "${FFMPEG_DIR}/bin/*.dll")
    foreach(dll ${FFMPEG_DLLS})
        get_filename_component(name ${dll} NAME)
        configure_file(${dll} ${CMAKE_CURRENT_BINARY_DIR}/${name} COPYONLY)
    endforeach()
else()
    find_package(PkgConfig REQUIRED)
    pkg_check_modules(FFMPEG REQUIRED IMPORTED_TARGET libavformat libavcodec libavutil libswscale libswresample)
    add_library(digi35_ffmpeg INTERFACE)
    target_link_libraries(digi35_ffmpeg INTERFACE PkgConfig::FFMPEG)
endif()

# Motion's sources, which read and write movies with FFmpeg
set(MOTION_SOURCES engine/Clip.cpp engine/Motion.cpp engine/ClipExport.cpp engine/ClipAudio.cpp)
add_executable(digi35-clip tools/port-clip/main.cpp engine/Clip.cpp engine/LogFormats.cpp)
target_include_directories(digi35-clip PRIVATE engine)
target_link_libraries(digi35-clip PRIVATE digi35_ffmpeg)
digi35_tool(digi35-motion tools/port-motion/main.cpp)
target_sources(digi35-motion PRIVATE ${MOTION_SOURCES})
target_link_libraries(digi35-motion PRIVATE digi35_ffmpeg)
digi35_tool(digi35-export tools/port-export/main.cpp)
target_sources(digi35-export PRIVATE ${MOTION_SOURCES})
target_link_libraries(digi35-export PRIVATE digi35_ffmpeg)

# The app: Digi35 for Windows, both halves of the Mac app, Stills and Motion.
set(APP_SOURCES
    app/main.cpp
    app/AppSettings.cpp
    app/Theme.cpp
    app/Vocabulary.cpp
    app/Widgets.cpp
    app/CurvesView.cpp
    app/Inspector.cpp
    app/Canvas.cpp
    app/MainWindow.cpp
    app/Splash.cpp
    app/Ratings.cpp
    app/Nadam.cpp
    app/Updater.cpp
    app/Performance.cpp
    app/Walkthrough.cpp
    app/Features.cpp
    app/HdrPanel.cpp
    app/ControlLink.cpp
    app/Explorer.cpp
    app/ExportDialog.cpp
    app/Document.cpp
    app/EditNames.cpp
    app/Presets.cpp
    app/RenderEngine.cpp
    app/QuickPreviews.cpp
    app/Exporter.cpp
    app/Exif.cpp
    app/MotionEngine.cpp
    app/MotionDocument.cpp
    app/MotionCanvas.cpp
    app/TransportBar.cpp
    app/MotionInspector.cpp
    app/AudioPlayback.cpp
    app/Filmstrip.cpp
    app/Browse.cpp
    app/Library.cpp
    app/FilterBuilder.cpp
    app/MetaWriter.cpp
    app/MetadataEditor.cpp
    app/BatchRename.cpp
    app/MetadataForm.cpp
    app/FolderPanel.cpp
    app/Collections.cpp
    app/Sidecars.cpp
    app/ModelStore.cpp
)
qt_add_executable(Digi35 ${APP_SOURCES} ${ENGINE_SOURCES} ${MOTION_SOURCES}
    engine/RawUnpackRawSpeed.cpp engine/RawUnpackLibRaw.cpp engine/RawDecoder.cpp engine/HighlightsOpposed.cpp engine/Demosaic.cpp engine/DemosaicRCD.cpp engine/DemosaicAmaze.cpp engine/RawDetail.cpp
    engine/GpuDecoder.cpp engine/AppleColour.cpp engine/LensCorrection.cpp engine/ChromaticAberration.cpp
    engine/AiRuntime.cpp engine/AiTools.cpp engine/OnnxEdit.cpp engine/Heal.cpp engine/HdrMerge.cpp engine/Defringe.cpp engine/FilmicHighlights.cpp
    engine/RawDenoise.cpp)
set_target_properties(Digi35 PROPERTIES MACOSX_BUNDLE OFF WIN32_EXECUTABLE ON)
# the version, for the program, Explorer and the installer (tools/pc/package.cmd)
configure_file(app/version.h.in ${CMAKE_CURRENT_BINARY_DIR}/version.h)
file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/version.txt "${PROJECT_VERSION}")
target_include_directories(Digi35 PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
# the icon and the version Explorer shows
if(WIN32)
    target_sources(Digi35 PRIVATE app/Digi35.rc)
    # the GPU's memory budget (RenderEngine's gpuMemoryFree)
    target_link_libraries(Digi35 PRIVATE dxgi)
endif()
target_include_directories(Digi35 PRIVATE engine app)
target_link_libraries(Digi35 PRIVATE Qt6::Widgets Qt6::Gui Qt6::GuiPrivate Qt6::CorePrivate Qt6::Network Qt6::Multimedia Qt6::Sql
                                         digi35_rawspeed digi35_libraw digi35_ffmpeg digi35_ort)
digi35_rounding(Digi35)
qt_add_shaders(Digi35 "Digi35_kernels"
    NOGLSL
    HLSL 50
    ${DIGI35_PRECOMPILE}
    MSL 12
    BASE engine/shaders
    PREFIX "/shaders"
    FILES ${ENGINE_KERNELS} ${RAW_KERNELS}
)
# Digi35's logo, for the window and the empty canvas
qt_add_resources(Digi35 "branding" PREFIX "/branding" BASE app FILES app/digi35.png app/leader-canister.png app/leader-strip.png)
# the features overview's pictures: one RAW through several films, the sky's
# mask, a real scanned darkroom-print frame and the Stream Deck
qt_add_resources(Digi35 "overview" PREFIX "/overview" BASE app/overview FILES
    app/overview/raw.jpg app/overview/portra400.jpg app/overview/ektar100.jpg app/overview/velvia50.jpg
    app/overview/trix400.jpg app/overview/vision500t.jpg app/overview/skymask.png app/overview/frame.png
    app/overview/streamdeck.jpg app/overview/hdr-dark.jpg app/overview/hdr-bright.jpg app/overview/hdr-merged.jpg
    app/overview/ss-full.jpg app/overview/ss-soft.jpg app/overview/ss-sharp.jpg)
# the developing tank turned over while a picture opens: 60 frames, 25 a second
file(GLOB TANK_FRAMES ${CMAKE_CURRENT_SOURCE_DIR}/app/tank/tank_*.png)
qt_add_resources(Digi35 "tank" PREFIX "/tank" BASE app/tank FILES ${TANK_FRAMES})
# The Mac app's tree, the release the port follows: mac/, the submodule, in
# the port's own repository; the repository's root, beside windows/, in the
# public one (as tools/mac-reference/mac-tree.sh finds it).
set(DIGI35_MAC ${CMAKE_CURRENT_SOURCE_DIR}/mac)
if(NOT EXISTS ${DIGI35_MAC}/build.sh)
    get_filename_component(DIGI35_MAC ${CMAKE_CURRENT_SOURCE_DIR}/.. ABSOLUTE)
endif()
# The film packs next to the program: the Mac app's, or on the PC the copy
# tools/pc/remote.sh keeps beside the sources.
# the Mac app's folder: Digi35, or FLXFilmLab as it was named before
set(DIGI35_PACKS ${DIGI35_MAC}/Digi35/Resources/packs)
if(NOT EXISTS ${DIGI35_PACKS}/index.json)
    set(DIGI35_PACKS ${DIGI35_MAC}/FLXFilmLab/Resources/packs)
endif()
if(NOT EXISTS ${DIGI35_PACKS}/index.json)
    set(DIGI35_PACKS ${CMAKE_CURRENT_SOURCE_DIR}/packs)
endif()
file(GLOB PACK_FILES CONFIGURE_DEPENDS ${DIGI35_PACKS}/*.json ${DIGI35_PACKS}/*.tclut ${DIGI35_PACKS}/*.txt)
foreach(f ${PACK_FILES})
    get_filename_component(name ${f} NAME)
    configure_file(${f} ${CMAKE_CURRENT_BINARY_DIR}/packs/${name} COPYONLY)
endforeach()
# The presets that come with the app (Digi35's own)
file(GLOB PRESET_FILES CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/presets/*.json)
set(PRESET_NAMES)
foreach(f ${PRESET_FILES})
    get_filename_component(name ${f} NAME)
    list(APPEND PRESET_NAMES ${name})
    configure_file(${f} ${CMAKE_CURRENT_BINARY_DIR}/presets/${name} COPYONLY)
endforeach()
# one renamed or taken out of presets/ goes from the build too, so the
# installer, which takes the build's folder whole, does not ship it
file(GLOB BUILT_PRESETS ${CMAKE_CURRENT_BINARY_DIR}/presets/*.json)
foreach(f ${BUILT_PRESETS})
    get_filename_component(name ${f} NAME)
    if(NOT name IN_LIST PRESET_NAMES)
        file(REMOVE ${f})
    endif()
endforeach()
# The frames that come with the app (real scans, Digi35's own)
file(GLOB FRAME_FILES CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/frames/*.png ${CMAKE_CURRENT_SOURCE_DIR}/frames/*.jpg)
foreach(f ${FRAME_FILES})
    get_filename_component(name ${f} NAME)
    configure_file(${f} ${CMAKE_CURRENT_BINARY_DIR}/frames/${name} COPYONLY)
endforeach()
# On Windows, Qt's libraries and plugins beside the program, so it runs
# from Explorer as well as from a shell with Qt on its PATH.
if(WIN32)
    find_program(WINDEPLOYQT windeployqt HINTS "${QT6_INSTALL_PREFIX}/bin" "${Qt6_DIR}/../../../bin")
    if(WINDEPLOYQT)
        add_custom_command(TARGET Digi35 POST_BUILD
            COMMAND "${WINDEPLOYQT}" --release --no-translations --no-system-d3d-compiler --no-opengl-sw
                    --no-compiler-runtime --skip-plugin-types multimedia --no-ffmpeg "$<TARGET_FILE:Digi35>" > "${CMAKE_CURRENT_BINARY_DIR}/windeployqt.log"
            VERBATIM)
    endif()
endif()

# The app as it is handed over (tools\pc\package.cmd): the program, Qt's
# libraries and plugins, the compiler's runtime, the data, and the licences.
if(WIN32)
    install(TARGETS Digi35 RUNTIME DESTINATION .)
    install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/packs ${CMAKE_CURRENT_BINARY_DIR}/lensfun
                      ${CMAKE_CURRENT_BINARY_DIR}/presets ${CMAKE_CURRENT_BINARY_DIR}/frames DESTINATION .)
    # the Stream Deck plugin and profile (streamdeck/), for whoever has one
    install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/streamdeck/Digi35.streamDeckPlugin
                  ${CMAKE_CURRENT_SOURCE_DIR}/streamdeck/Digi35.streamDeckProfile
                  "${CMAKE_CURRENT_SOURCE_DIR}/streamdeck/Digi35 15 keys.streamDeckProfile"
                  ${CMAKE_CURRENT_SOURCE_DIR}/streamdeck/Install.txt DESTINATION "Stream Deck")
    install(FILES ${CMAKE_CURRENT_BINARY_DIR}/cameras.xml DESTINATION .)
    # the getting started guide (docs/guide/build.ps1 prints it), which Help > Getting Started Guide opens
    if(EXISTS "${DIGI35_MAC}/docs/Digi35 Getting Started.pdf")
        install(FILES "${DIGI35_MAC}/docs/Digi35 Getting Started.pdf" DESTINATION .)
    else()
        message(WARNING "no docs/Digi35 Getting Started.pdf: the app is packaged without its guide")
    endif()
    # what is new in this version (docs/whats-new/build.ps1 prints it), which Help > What's New opens
    # off for the first release (nothing is new to someone downloading it); on
    # again with -DDIGI35_WHATS_NEW=ON once there are updates to describe
    option(DIGI35_WHATS_NEW "Install the What's New PDF" ON)
    if(DIGI35_WHATS_NEW AND EXISTS "${DIGI35_MAC}/docs/Digi35 What's New.pdf")
        install(FILES "${DIGI35_MAC}/docs/Digi35 What's New.pdf" DESTINATION .)
    endif()
    # every version's notes (tools/pc/release_changelog.py writes it), which Help > Changelog shows
    if(EXISTS "${DIGI35_MAC}/docs/Digi35 Changelog.md")
        install(FILES "${DIGI35_MAC}/docs/Digi35 Changelog.md" DESTINATION .)
    endif()
    if(EXISTS ${CMAKE_CURRENT_BINARY_DIR}/apple-colour.json)
        install(FILES ${CMAKE_CURRENT_BINARY_DIR}/apple-colour.json DESTINATION .)
    endif()
    # The licences of what the app is made of: its own and its film data's,
    # the libraries it carries, Lensfun's data, Qt's and FFmpeg's.
    function(digi35_licence source name)
        if(NOT EXISTS "${source}")
            message(FATAL_ERROR "no licence at ${source}")
        endif()
        install(FILES "${source}" DESTINATION licenses RENAME "${name}")
    endfunction()
    digi35_licence(${DIGI35_MAC}/LICENSE "Digi35 - GPL-3.0.txt")
    digi35_licence(${DIGI35_MAC}/NOTICE.md "Digi35 - notices.md")
    digi35_licence(${DIGI35_PACKS}/LICENSE-CC-BY-SA-4.0.txt "Film packs - CC BY-SA 4.0.txt")
    digi35_licence(${CMAKE_CURRENT_SOURCE_DIR}/third_party/LibRaw/LICENSE.LGPL "LibRaw - LGPL-2.1.txt")
    digi35_licence(${CMAKE_CURRENT_SOURCE_DIR}/third_party/LibRaw/LICENSE.CDDL "LibRaw - CDDL-1.0.txt")
    digi35_licence(${CMAKE_CURRENT_SOURCE_DIR}/third_party/LibRaw/COPYRIGHT "LibRaw - copyright.txt")
    digi35_licence(${CMAKE_CURRENT_SOURCE_DIR}/third_party/rawspeed/LICENSE "RawSpeed - LGPL-2.1.txt")
    digi35_licence(${CMAKE_CURRENT_SOURCE_DIR}/third_party/pugixml/LICENSE.md "pugixml - MIT.md")
    digi35_licence(${CMAKE_CURRENT_SOURCE_DIR}/third_party/zlib-1.3.2/LICENSE "zlib - zlib License.txt")
    digi35_licence(${CMAKE_CURRENT_SOURCE_DIR}/third_party/libjpeg-turbo-3.2.0/LICENSE.md "libjpeg-turbo - IJG and BSD-3-Clause.md")
    digi35_licence(${DIGI35_JXL_DIR}/licenses/LICENSE.libjxl "libjxl - BSD-3-Clause.txt")
    digi35_licence(${DIGI35_JXL_DIR}/licenses/LICENSE.brotli "Brotli - MIT.txt")
    digi35_licence(${DIGI35_JXL_DIR}/licenses/LICENSE.highway "Highway - Apache-2.0 or BSD-3-Clause.txt")
    digi35_licence(${DIGI35_JXL_DIR}/licenses/LICENSE.skcms "skcms - BSD-3-Clause.txt")
    digi35_licence(${DIGI35_ORT_DIR}/LICENSE "ONNX Runtime - MIT.txt")
    digi35_licence(${DIGI35_ORT_DIR}/ThirdPartyNotices.txt "ONNX Runtime - third-party notices.txt")
    digi35_licence(${CMAKE_CURRENT_SOURCE_DIR}/third_party/lensfun/docs/cc-by-sa-3.0.txt "Lensfun database - CC BY-SA 3.0.txt")
    digi35_licence(${CMAKE_CURRENT_SOURCE_DIR}/third_party/lensfun/docs/lgpl-3.0.txt "Qt 6 - LGPL-3.0.txt")
    # the third-party code inside Qt's libraries and plugins (tools/pc/qt_notices.py)
    digi35_licence("${CMAKE_CURRENT_SOURCE_DIR}/third_party/qt-notices/Qt 6 - third-party notices.txt"
                   "Qt 6 - third-party notices.txt")
    # the DirectX Shader Compiler windeployqt carries from the Windows SDK
    digi35_licence(${CMAKE_CURRENT_SOURCE_DIR}/third_party/windows-sdk/sdk_license.rtf
                   "DirectX Shader Compiler - Windows SDK license.rtf")
    digi35_licence(${CMAKE_CURRENT_SOURCE_DIR}/third_party/windows-sdk/sdk_third_party_notices.rtf
                   "DirectX Shader Compiler - third-party notices.rtf")
    digi35_licence(${FFMPEG_DIR}/LICENSE.txt "FFmpeg - LGPL-2.1.txt")
    digi35_licence(${FFMPEG_DIR}/SOURCE.txt "FFmpeg - source.txt")
    digi35_licence(${FFMPEG_DIR}/NOTICES.txt "FFmpeg - notices.txt")
    # FFmpeg's libraries Motion reads and writes movies with
    file(GLOB FFMPEG_RUNTIME "${FFMPEG_DIR}/bin/avcodec-*.dll" "${FFMPEG_DIR}/bin/avformat-*.dll"
         "${FFMPEG_DIR}/bin/avutil-*.dll" "${FFMPEG_DIR}/bin/swscale-*.dll" "${FFMPEG_DIR}/bin/swresample-*.dll")
    install(FILES ${FFMPEG_RUNTIME} DESTINATION .)
    # libjxl's, for JPEG XL DNGs
    install(FILES ${DIGI35_JXL_DLLS} DESTINATION .)
    # ONNX Runtime's, for the AI tools
    install(FILES ${DIGI35_ORT_DLLS} DESTINATION .)
    if(WINDEPLOYQT)
        install(CODE "execute_process(COMMAND \"${WINDEPLOYQT}\" --release --no-translations --no-system-d3d-compiler
                      --no-opengl-sw --no-compiler-runtime --skip-plugin-types multimedia --no-ffmpeg \"\${CMAKE_INSTALL_PREFIX}/Digi35.exe\" OUTPUT_QUIET)")
    endif()
    set(CMAKE_INSTALL_SYSTEM_RUNTIME_DESTINATION .)
    include(InstallRequiredSystemLibraries)
endif()
