cmake_minimum_required(VERSION 3.24)
project(plot VERSION 0.1.0
  DESCRIPTION "An embeddable OpenGL time-series plotting library for real-time, high-sample-rate data"
  LANGUAGES CXX)

list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
include(plot_options)
include(GNUInstallDirs)

# The version header: generated into the build tree at configure time, from the
# template beside it. It is a public header -- the umbrella names it, the
# self-containment and umbrella checks in tests/ hold it to the same rules, and
# the install rules place it under include/plot/ with the rest of the surface --
# so a consumer can ask what it compiled against (see include/plot/version.hpp.in).
configure_file(include/plot/version.hpp.in
  "${CMAKE_CURRENT_BINARY_DIR}/include/plot/version.hpp" @ONLY)

add_library(plot_core
  src/core/status.cpp
  src/math/transform.cpp
  src/data/minmax_pyramid.cpp
  src/data/series.cpp
  src/data/array_series.cpp
  src/data/stream_series.cpp
  src/data/xy_series.cpp
  src/gl/loader.cpp
  src/gl/handle.cpp
  src/render/shaders.cpp
  src/render/text.cpp
  src/render/text_atlas.cpp
  src/render/embedded_mono_font.cpp
  src/render/primitives.cpp
  src/render/buffer.cpp
  src/render/vertex_array.cpp
  src/render/program.cpp
  src/render/renderer.cpp
  src/plot/ticks.cpp
  src/plot/axis.cpp
  src/plot/grid.cpp
  src/plot/measure.cpp
  src/plot/plot.cpp
  src/plot/figure.cpp
  src/input/controller.cpp
)
add_library(plot::core ALIAS plot_core)
# What the target is called in an installed tree. Without this the export set is
# namespaced by the target's own name (plot::plot_core), while the build tree --
# and every consumer, and this project's own comments -- says plot::core.
set_target_properties(plot_core PROPERTIES EXPORT_NAME core)

# The shared-library case names its file versions: the dynamic loader follows
# the SONAME (libplot_core.so.<SOVERSION>, the major component), so an
# ABI-breaking release moves it by bumping project()'s major. The static
# archive -- the default, and the only shape the presets build -- carries no
# such name, and setting the properties on it would be noise.
if(BUILD_SHARED_LIBS)
  set_target_properties(plot_core PROPERTIES
    VERSION ${PROJECT_VERSION}
    SOVERSION ${PROJECT_VERSION_MAJOR})
endif()

target_include_directories(plot_core PUBLIC
  $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
  # The generated version header lives here, not under the source root (see
  # configure_file above); everything that compiles against plot::core reaches
  # it through this interface, including the header checks in tests/.
  $<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}/include>
  $<INSTALL_INTERFACE:include>)
target_compile_features(plot_core PUBLIC cxx_std_20)
target_link_libraries(plot_core PRIVATE ${CMAKE_DL_LIBS})
plot_apply_warnings(plot_core)

# The optional runtime-font backend: plot::text::TrueTypeFont. The option and
# its guard live in cmake/plot_options.cmake with every other PLOT_* option;
# what is left here is the one thing an option cannot do for itself: adding the
# target. See the option's comment there for why it is opt-in and separable.
if(PLOT_BUILD_TTF_FONT)
  add_subdirectory(src/text)
endif()

# Adapters own the surface and translate their host's events; examples link the
# adapter they demo. Both are opt-in, so the core library and its tests still build
# on a bare toolchain.
#
# They are added before the test suite on purpose: a test that drives an adapter
# needs that adapter's targets to exist, and with both switches on the suite can
# then exercise them (see tests/CMakeLists.txt).
if(PLOT_BUILD_GLFW)
  add_subdirectory(adapters/glfw)
endif()

if(PLOT_BUILD_IMGUI)
  add_subdirectory(adapters/imgui)
endif()

if(PLOT_BUILD_QT6)
  add_subdirectory(adapters/qt6)
endif()

if(PLOT_BUILD_GTK4)
  add_subdirectory(adapters/gtk4)
endif()

if(PLOT_BUILD_EXAMPLES)
  add_subdirectory(examples)
endif()

if(PLOT_BUILD_TESTS)
  # Test-only: counts the pyramid's covering-decomposition entries and its bucket
  # merges so a test can pin the query's O(log n) cost and the append path's
  # amortised O(1) cost, neither of which any answer reveals. Off in every
  # non-test build (see include/plot/data/detail/{cover,merge}_count.hpp).
  #
  # PLOT_RING_STATS is the same for the persistent-mapped instance ring: the
  # properties a frame must hold there -- no slot written twice within a frame,
  # and one fence wait at most, at the start of the frame -- are invisible in the
  # pixels, so a test reads counters instead (see
  # include/plot/render/detail/ring_stats.hpp).
  #
  # PLOT_COUNT_MEASURE_RECOMPUTES is the same for the measurement cache: whether
  # `Plot::measurement()` recomputed or returned a cached result is invisible in
  # the value it returns, so a test that has to tell a live cache from one frozen
  # on a stale window counts re-evaluations (see
  # include/plot/plot/detail/measure_count.hpp).
  target_compile_definitions(plot_core PRIVATE PLOT_PYRAMID_COUNT_COVERS
                                             PLOT_PYRAMID_COUNT_MERGES
                                             PLOT_RING_STATS
                                             PLOT_COUNT_MEASURE_RECOMPUTES)

  enable_testing()
  add_subdirectory(tests)
endif()

# The reproducible coverage report. A custom target rather than a ctest case,
# for two reasons: a ctest entry registered in the coverage preset would either
# fail in a freshly configured tree (no report exists until tools/coverage.sh
# has run once, which would break the plain `ctest --test-dir build/cov` the
# preset's own documentation promises) or it would have to build the library
# and re-run the whole suite inside the test, duplicating the script. A target
# that is not part of `all` costs the ordinary presets nothing -- and it is not
# even created there, because PLOT_COVERAGE is off and the option's guard
# rejects a tree that carries no --coverage flags. The exact command a reader
# gets is `cmake --build build/cov --target coverage`, which is the same one
# tools/coverage.sh implements.
if(PLOT_COVERAGE)
  add_custom_target(coverage
    COMMAND "${CMAKE_SOURCE_DIR}/tools/coverage.sh" "${CMAKE_BINARY_DIR}"
    COMMENT "coverage: building, running the suite, capturing src/** and enforcing the floor"
    USES_TERMINAL VERBATIM)
endif()

# Install and export. The core always goes in; each adapter joins the set only if
# its toolkit can be re-found on a consumer's machine, which the adapter decided
# when it was added (plot_record_adapter_export() -- the decisions and the reasons
# are in the configure log above). plotConfig.cmake then re-finds exactly those
# toolkits before including the targets file the adapters are described in, so
# find_package(plot) + target_link_libraries(consumer PRIVATE plot::core) works
# from an installed prefix with no -I or -L of the consumer's own.
if(PLOT_INSTALL)
  # The adapters that could be promised to a consumer, in the order they were
  # added, and the find_dependency() calls that re-create their toolkits there.
  get_property(PLOT_ADAPTER_EXPORT_TARGETS GLOBAL PROPERTY PLOT_ADAPTER_EXPORT_TARGETS)
  # Substituted into plotConfig.cmake below (@PLOT_ADAPTER_DEPENDENCIES@).
  get_property(PLOT_ADAPTER_DEPENDENCIES GLOBAL PROPERTY PLOT_ADAPTER_DEPENDENCIES)

  include(CMakePackageConfigHelpers)

  # No INCLUDES DESTINATION here: every target already declares
  # $<INSTALL_INTERFACE:include> in its own target_include_directories(), and
  # asking for it twice puts the same directory in the export twice.
  install(TARGETS plot_core ${PLOT_ADAPTER_EXPORT_TARGETS}
    EXPORT plotTargets
    ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
    LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
    RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
  # The public headers, and the generated version header with them. The
  # directory rule takes the source tree (FILES_MATCHING, so the version.hpp.in
  # template -- a .in, not a .hpp -- cannot travel); the generated
  # include/plot/version.hpp is not under the source root, so it goes in by
  # name. The optional backend's header goes in only when that backend was
  # built: an installed header with no library behind it is a promise the
  # prefix cannot keep, and which configuration a prefix came from is not
  # something a consumer can see.
  if(PLOT_BUILD_TTF_FONT)
    install(DIRECTORY include/plot
      DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
      FILES_MATCHING PATTERN "*.hpp")
  else()
    install(DIRECTORY include/plot
      DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
      FILES_MATCHING PATTERN "*.hpp"
      PATTERN "true_type_font.hpp" EXCLUDE)
  endif()
  install(FILES "${CMAKE_CURRENT_BINARY_DIR}/include/plot/version.hpp"
    DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/plot)

  # The licences that travel with the installed files: this library's MIT text,
  # and the OFL 1.1 text for the embedded font the headers bake in, so a
  # redistributor of the prefix holds both grants without a second checkout.
  install(FILES LICENSE licences/OFL-1.1.txt
    DESTINATION ${CMAKE_INSTALL_DATADIR}/licenses/plot)

  # pkg-config metadata, for consumers whose build is not CMake. find_package()
  # and the package config below remain the primary interface; see plot.pc.in.
  set(PLOT_PC_LIBDIR "${CMAKE_INSTALL_LIBDIR}")
  set(PLOT_PC_INCLUDEDIR "${CMAKE_INSTALL_INCLUDEDIR}")
  set(PLOT_PC_LIB "-lplot_core")
  set(PLOT_PC_LIBS_PRIVATE "")
  foreach(plot_pc_lib IN LISTS CMAKE_DL_LIBS)
    list(APPEND PLOT_PC_LIBS_PRIVATE "-l${plot_pc_lib}")
  endforeach()
  string(REPLACE ";" " " PLOT_PC_LIBS_PRIVATE "${PLOT_PC_LIBS_PRIVATE}")
  configure_file(plot.pc.in "${CMAKE_CURRENT_BINARY_DIR}/plot.pc" @ONLY)
  install(FILES "${CMAKE_CURRENT_BINARY_DIR}/plot.pc"
    DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig)

  install(EXPORT plotTargets
    NAMESPACE plot::
    FILE plotTargets.cmake
    DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/plot)

  configure_package_config_file(
    cmake/plotConfig.cmake.in
    "${CMAKE_CURRENT_BINARY_DIR}/plotConfig.cmake"
    INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/plot)
  # SameMinorVersion, deliberately: the project is 0.x, where the major
  # component carries no ABI promise and the minor is what moves when one
  # breaks, so a consumer asking for 0.1 gets 0.1.x and nothing newer. It goes
  # up to SameMajorVersion when the version leaves 0.
  write_basic_package_version_file(
    "${CMAKE_CURRENT_BINARY_DIR}/plotConfigVersion.cmake"
    VERSION ${PROJECT_VERSION}
    COMPATIBILITY SameMinorVersion)

  install(FILES
    "${CMAKE_CURRENT_BINARY_DIR}/plotConfig.cmake"
    "${CMAKE_CURRENT_BINARY_DIR}/plotConfigVersion.cmake"
    DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/plot)
endif()
