# ##############################################################################
# pjsua2 Java bindings
#
# SWIG turns pjsua2.i into pjsua2_wrap.cpp plus the org.pjsip.pjsua2 Java
# sources. The shared library is what System.loadLibrary("pjsua2") opens --
# see the jniclasscode pragma in pjsua2.i -- so its name is fixed.
#
# On Android, Gradle compiles the Java beside it and packages both into the
# AAR, and a build of its own copies both into the sample app (see "The Android
# sample app" below). Elsewhere this builds what java/Makefile does, in this
# directory of the build tree:
#
#   libpjsua2.so, libpjsua2.jnilib or pjsua2.dll   the JNI library
#   pjsua2.jar                                      the bindings
#   pjsua2_java_samples.jar                         test.java and sample.java
#
#   java -cp pjsua2.jar:pjsua2_java_samples.jar -Djava.library.path=. test
#
# python/CMakeLists.txt builds the Python module, csharp/CMakeLists.txt the C#
# bindings.

find_package(SWIG 4.0 REQUIRED COMPONENTS java)
include(UseSWIG)
include(Pj/Swig)

# Where the generated .java is written.
#
# It is identical for every ABI, but CMAKE_CURRENT_BINARY_DIR is not: Gradle
# configures one build directory per ABI, and putting four copies of the same
# classes on the source path is a duplicate class error. So Gradle overrides
# this with a single shared directory, while a standalone CMake build keeps
# everything under its own build tree.
set(PJSUA2_JAVA_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/java"
  CACHE PATH "Directory the generated pjsua2 Java sources are written to"
)

set_property(SOURCE pjsua2.i PROPERTY CPLUSPLUS ON)
set_property(SOURCE pjsua2.i PROPERTY COMPILE_OPTIONS
  -package org.pjsip.pjsua2
  -doxygen
)
set_property(SOURCE pjsua2.i PROPERTY USE_SWIG_DEPENDENCIES TRUE)
# __ANDROID__ selects the UTF-8 std::string typemaps in and_string.i. SWIG
# does not see the compiler's built-in macros, so it has to be told.
if(ANDROID)
  set_property(SOURCE pjsua2.i PROPERTY COMPILE_DEFINITIONS __ANDROID__)
endif()

swig_add_library(pjsua2jni
  TYPE SHARED
  LANGUAGE java
  OUTPUT_DIR "${PJSUA2_JAVA_OUTPUT_DIR}/org/pjsip/pjsua2"
  OUTFILE_DIR "${CMAKE_CURRENT_BINARY_DIR}"
  SOURCES pjsua2.i
)

set_target_properties(pjsua2jni PROPERTIES
  # Fixed by the loadLibrary call in pjsua2.i.
  OUTPUT_NAME pjsua2

  # The C++ library is called pjsua2 as well. It is normally static, so the
  # two do not collide, but with BUILD_SHARED_LIBS they would both want
  # libpjsua2.so. Keep this one in its own directory either way, without a
  # per-configuration subdirectory.
  LIBRARY_OUTPUT_DIRECTORY "$<1:${CMAKE_CURRENT_BINARY_DIR}>"
  RUNTIME_OUTPUT_DIRECTORY "$<1:${CMAKE_CURRENT_BINARY_DIR}>"
)

# Each library whose headers the wrapper includes, as the C# bindings
target_link_libraries(pjsua2jni PRIVATE
  pjsua2 pjsua-lib pjsip pjmedia pjnath pjlib-util pjlib
)

# The NDK has jni.h in its sysroot; a desktop build needs the JDK's
if(NOT ANDROID)
  find_package(JNI REQUIRED COMPONENTS JVM)
  target_include_directories(pjsua2jni PRIVATE ${JNI_INCLUDE_DIRS})
else()
  # The wrapper itself calls ANativeWindow_fromSurface() (pjsua2.i), as
  # java/Makefile links it; pjmedia-videodev only passes libandroid on when
  # static
  target_link_libraries(pjsua2jni PRIVATE android)
endif()

# The wrapper reads pointers out of jlong by type punning, which SWIG advises
# compiling with -fno-strict-aliasing; it also has unused helper functions.
target_compile_options(pjsua2jni PRIVATE
  $<$<CXX_COMPILER_ID:GNU,Clang,AppleClang>:-fno-strict-aliasing>
  $<$<CXX_COMPILER_ID:GNU,Clang,AppleClang>:-Wno-unused-function>
)

# Export the JNI entry points and nothing else; see pjsua2jni.map. Only the
# GNU-style linkers use a version script, which on Android is all of them.
if(ANDROID)
  set(_pjsua2jni_map "${CMAKE_CURRENT_SOURCE_DIR}/pjsua2jni.map")
  target_link_options(pjsua2jni PRIVATE
    "LINKER:--version-script=${_pjsua2jni_map}"
  )
  # A version script is not a source file, so relink when it changes.
  set_property(TARGET pjsua2jni APPEND PROPERTY LINK_DEPENDS "${_pjsua2jni_map}")
  unset(_pjsua2jni_map)
endif()

# SWIG parses the headers itself, see Pj/Swig.cmake
pj_swig_include_pj_headers(pjsua2jni)

# ##############################################################################
# Java helper classes
#
# These belong to the binding rather than to any sample app, so they ship
# beside the generated sources -- the android_helpers target in the SWIG
# Makefile does the same. See Pj/Swig.cmake.

pj_android_java_helpers(pjsua2jni_helpers "${PJSUA2_JAVA_OUTPUT_DIR}"
  _pjsua2_helpers
)
# Gradle builds only pjsua2jni, and needs the helpers with it
add_dependencies(pjsua2jni pjsua2jni_helpers)

# ##############################################################################
# The Android sample app
#
# Put the bindings where pjsip-apps/src/swig/java/android takes them prebuilt,
# as java/Makefile does: the JNI library (and libc++_shared.so) in
# jniLibs/<abi>, the Java under java/. The C# bindings do the same for the MAUI
# project. Gradle's own CMake build and build-aar.sh build only pjsua2jni, so
# they copy nothing.

if(ANDROID)
  set(PJSUA2_ANDROID_DIR
    "${PROJECT_SOURCE_DIR}/pjsip-apps/src/swig/java/android/pjsua2/src/main"
    CACHE PATH
    "The Android source set to copy the pjsua2 Java bindings into; empty for none"
  )
endif()

if(ANDROID AND PJSUA2_ANDROID_DIR)
  set(_pj_jni_dir "${PJSUA2_ANDROID_DIR}/jniLibs/${ANDROID_ABI}")
  set(_pj_java_dir "${PJSUA2_ANDROID_DIR}/java/org/pjsip")
  pj_android_cxx_shared(_pj_cxx_shared)

  add_custom_target(pjsua2jni_android ALL
    COMMAND "${CMAKE_COMMAND}" -E make_directory "${_pj_jni_dir}"
    COMMAND "${CMAKE_COMMAND}" -E copy_if_different
            "$<TARGET_FILE:pjsua2jni>" ${_pj_cxx_shared} "${_pj_jni_dir}"
    COMMENT "Copying the pjsua2 Java bindings into ${PJSUA2_ANDROID_DIR}"
    VERBATIM
  )
  add_dependencies(pjsua2jni_android pjsua2jni)

  # Unless SWIG writes there itself, sync the classes: remove only those SWIG
  # no longer generates (an app may keep its own sources in a subpackage, as
  # the sample's org.pjsip.pjsua2.app), and rewrite only those that changed,
  # so that Gradle does not recompile them all on every build
  cmake_path(COMPARE "${PJSUA2_JAVA_OUTPUT_DIR}/org/pjsip" EQUAL
    "${_pj_java_dir}" _pj_same_dir
  )
  if(NOT _pj_same_dir)
    set(_pj_sync_script "${CMAKE_CURRENT_BINARY_DIR}/pjsua2_android_sync.cmake")
    file(WRITE "${_pj_sync_script}" [[
file(GLOB _new RELATIVE "${SRC}" "${SRC}/*.java")
if(NOT _new)
  message(FATAL_ERROR "No generated classes in ${SRC}")
endif()
file(GLOB _old RELATIVE "${DST}" "${DST}/*.java")
list(REMOVE_ITEM _old ${_new})
foreach(_f IN LISTS _old)
  file(REMOVE "${DST}/${_f}")
endforeach()
execute_process(
  COMMAND "${CMAKE_COMMAND}" -E copy_directory_if_different "${SRC}" "${DST}"
  COMMAND_ERROR_IS_FATAL ANY
)
]])
    add_custom_command(TARGET pjsua2jni_android POST_BUILD
      COMMAND "${CMAKE_COMMAND}"
              "-DSRC=${PJSUA2_JAVA_OUTPUT_DIR}/org/pjsip/pjsua2"
              "-DDST=${_pj_java_dir}/pjsua2"
              -P "${_pj_sync_script}"
      VERBATIM
    )
    unset(_pj_sync_script)
    if(_pjsua2_helpers)
      add_custom_command(TARGET pjsua2jni_android POST_BUILD
        COMMAND "${CMAKE_COMMAND}" -E copy_if_different
                ${_pjsua2_helpers} "${_pj_java_dir}"
        VERBATIM
      )
    endif()
  endif()

  unset(_pj_jni_dir)
  unset(_pj_java_dir)
  unset(_pj_cxx_shared)
  unset(_pj_same_dir)
endif()
unset(_pjsua2_helpers)

if(ANDROID)
  return()
endif()

# ##############################################################################
# pjsua2.jar
#
# Which classes SWIG writes is only known once it has run, so the list of
# sources javac compiles is a file made after each run.

find_package(Java 1.8 REQUIRED COMPONENTS Development Runtime)
include(UseJava)

set(_pj_java_pkg_dir "${PJSUA2_JAVA_OUTPUT_DIR}/org/pjsip/pjsua2")
set(_pj_java_list "${CMAKE_CURRENT_BINARY_DIR}/pjsua2_java_sources.txt")
set(_pj_java_list_script "${CMAKE_CURRENT_BINARY_DIR}/pjsua2_java_sources.cmake")
file(WRITE "${_pj_java_list_script}" [[
file(GLOB _sources "${DIR}/*.java")
list(JOIN _sources "\"\n\"" _sources)
file(WRITE "${OUT}" "\"${_sources}\"\n")
]])

# pjsua2JNI.java is one of the files the SWIG step names as its output
add_custom_command(
  OUTPUT "${_pj_java_list}"
  COMMAND "${CMAKE_COMMAND}" -DDIR=${_pj_java_pkg_dir} -DOUT=${_pj_java_list}
          -P "${_pj_java_list_script}"
  DEPENDS "${_pj_java_pkg_dir}/pjsua2JNI.java" "${_pj_java_list_script}"
  VERBATIM
)

add_jar(pjsua2_jar
  SOURCES "@${_pj_java_list}"
  OUTPUT_NAME pjsua2
)
add_dependencies(pjsua2_jar pjsua2jni)

# make compiles MyApp.java, the Android sample's model, with the bindings;
# sample.java is built on it
add_jar(pjsua2_java_samples
  SOURCES
    java/test.java
    java/sample.java
    java/android/app/src/main/java/org/pjsip/pjsua2/app/MyApp.java
  INCLUDE_JARS pjsua2_jar
)

unset(_pj_java_pkg_dir)
unset(_pj_java_list)
unset(_pj_java_list_script)

# ##############################################################################
# Installation
#
# The jar and the JNI library together, as the C# bindings; make installs
# nothing. Run with -Djava.library.path pointing there.

set(PJ_INSTALL_JAVADIR "${CMAKE_INSTALL_LIBDIR}/pjproject/java" CACHE PATH
  "Directory the pjsua2 Java bindings are installed to"
)

# With shared libraries, the JNI library finds them in the libdir
pj_swig_install_rpath(pjsua2jni "${PJ_INSTALL_JAVADIR}")

install(TARGETS pjsua2jni
  LIBRARY DESTINATION "${PJ_INSTALL_JAVADIR}" COMPONENT PjJava
  RUNTIME DESTINATION "${PJ_INSTALL_JAVADIR}" COMPONENT PjJava
)
# CMake 4.5 warns when install_jar() installs the jar, which it cannot tell
# is built by pjsua2_jar
if(CMAKE_VERSION VERSION_GREATER_EQUAL 4.5)
  install(FILES "$<TARGET_PROPERTY:pjsua2_jar,JAR_FILE>"
    DESTINATION "${PJ_INSTALL_JAVADIR}" COMPONENT PjJava
    BUILD_DEPENDS pjsua2_jar
  )
else()
  install_jar(pjsua2_jar DESTINATION "${PJ_INSTALL_JAVADIR}" COMPONENT PjJava)
endif()

# ##############################################################################
# Test: test.java, run against the build tree, as make test

if(BUILD_TESTING)
  if(WIN32)
    set(_pj_sep "$<SEMICOLON>")
  else()
    set(_pj_sep ":")
  endif()
  add_test(NAME pjsua2-java
    COMMAND "${Java_JAVA_EXECUTABLE}"
      -cp "$<TARGET_PROPERTY:pjsua2_jar,JAR_FILE>${_pj_sep}$<TARGET_PROPERTY:pjsua2_java_samples,JAR_FILE>"
      "-Djava.library.path=$<TARGET_FILE_DIR:pjsua2jni>"
      test
  )
  set_tests_properties(pjsua2-java PROPERTIES
    FAIL_REGULAR_EXPRESSION "Failed to load native library pjsua2"
  )
  unset(_pj_sep)
endif()
