Merge pull request #192 from taka-no-me/ndk_selection_fix
[profile/ivi/opencv.git] / cmake / OpenCVDetectAndroidSDK.cmake
1 if(EXISTS "${ANDROID_EXECUTABLE}")
2   set(ANDROID_SDK_DETECT_QUIET TRUE)
3 endif()
4
5 file(TO_CMAKE_PATH "$ENV{ProgramFiles}" ProgramFiles_ENV_PATH)
6 file(TO_CMAKE_PATH "$ENV{HOME}" HOME_ENV_PATH)
7
8 if(CMAKE_HOST_WIN32)
9   set(ANDROID_SDK_OS windows)
10 elseif(CMAKE_HOST_APPLE)
11   set(ANDROID_SDK_OS macosx)
12 else()
13   set(ANDROID_SDK_OS linux)
14 endif()
15
16 #find android SDK: search in ANDROID_SDK first
17 find_host_program(ANDROID_EXECUTABLE
18   NAMES android.bat android
19   PATH_SUFFIXES tools
20   PATHS
21     ENV ANDROID_SDK
22   DOC "Android SDK location"
23   NO_DEFAULT_PATH
24   )
25
26 # Now search default paths
27 find_host_program(ANDROID_EXECUTABLE
28   NAMES android.bat android
29   PATH_SUFFIXES android-sdk-${ANDROID_SDK_OS}/tools
30                 android-sdk-${ANDROID_SDK_OS}_x86/tools
31                 android-sdk-${ANDROID_SDK_OS}_86/tools
32                 android-sdk/tools
33   PATHS /opt
34         "${HOME_ENV_PATH}/NVPACK"
35         "$ENV{SystemDrive}/NVPACK"
36         "${ProgramFiles_ENV_PATH}/Android"
37   DOC "Android SDK location"
38   )
39
40 if(ANDROID_EXECUTABLE)
41   if(NOT ANDROID_SDK_DETECT_QUIET)
42     message(STATUS "Found android tool: ${ANDROID_EXECUTABLE}")
43   endif()
44
45   get_filename_component(ANDROID_SDK_TOOLS_PATH "${ANDROID_EXECUTABLE}" PATH)
46
47   #read source.properties
48   if(EXISTS "${ANDROID_SDK_TOOLS_PATH}/source.properties")
49     file(STRINGS "${ANDROID_SDK_TOOLS_PATH}/source.properties" ANDROID_SDK_TOOLS_SOURCE_PROPERTIES_LINES REGEX "^[ ]*[^#].*$")
50     foreach(line ${ANDROID_SDK_TOOLS_SOURCE_PROPERTIES_LINES})
51       string(REPLACE "\\:" ":" line ${line})
52       string(REPLACE "=" ";" line ${line})
53       list(GET line 0 line_name)
54       list(GET line 1 line_value)
55       string(REPLACE "." "_" line_name ${line_name})
56       SET(ANDROID_TOOLS_${line_name} "${line_value}" CACHE INTERNAL "from ${ANDROID_SDK_TOOLS_PATH}/source.properties")
57       MARK_AS_ADVANCED(ANDROID_TOOLS_${line_name})
58     endforeach()
59   endif()
60
61   #fix missing revision (SDK tools before r9 don't set revision number correctly)
62   if(NOT ANDROID_TOOLS_Pkg_Revision)
63     SET(ANDROID_TOOLS_Pkg_Revision "Unknown" CACHE INTERNAL "")
64     MARK_AS_ADVANCED(ANDROID_TOOLS_Pkg_Revision)
65   endif()
66
67   #fix missing description
68   if(NOT ANDROID_TOOLS_Pkg_Desc)
69     SET(ANDROID_TOOLS_Pkg_Desc "Android SDK Tools, revision ${ANDROID_TOOLS_Pkg_Revision}." CACHE INTERNAL "")
70     MARK_AS_ADVANCED(ANDROID_TOOLS_Pkg_Desc)
71   endif()
72
73   #warn about outdated SDK
74   if(NOT ANDROID_TOOLS_Pkg_Revision GREATER 13)
75     SET(ANDROID_TOOLS_Pkg_Desc "${ANDROID_TOOLS_Pkg_Desc} It is recommended to update your SDK tools to revision 14 or newer." CACHE INTERNAL "")
76   endif()
77
78   if(ANDROID_TOOLS_Pkg_Revision GREATER 13)
79     SET(ANDROID_PROJECT_PROPERTIES_FILE project.properties)
80     SET(ANDROID_ANT_PROPERTIES_FILE ant.properties)
81   else()
82     SET(ANDROID_PROJECT_PROPERTIES_FILE default.properties)
83     SET(ANDROID_ANT_PROPERTIES_FILE build.properties)
84   endif()
85
86   set(ANDROID_MANIFEST_FILE AndroidManifest.xml)
87   set(ANDROID_LIB_PROJECT_FILES build.xml local.properties proguard-project.txt ${ANDROID_PROJECT_PROPERTIES_FILE})
88   set(ANDROID_PROJECT_FILES ${ANDROID_LIB_PROJECT_FILES})
89
90   #get installed targets
91   if(ANDROID_TOOLS_Pkg_Revision GREATER 11)
92     execute_process(COMMAND ${ANDROID_EXECUTABLE} list target -c
93       RESULT_VARIABLE ANDROID_PROCESS
94       OUTPUT_VARIABLE ANDROID_SDK_TARGETS
95       ERROR_VARIABLE ANDROID_PROCESS_ERRORS
96       OUTPUT_STRIP_TRAILING_WHITESPACE
97       )
98     string(REGEX MATCHALL "[^\n]+" ANDROID_SDK_TARGETS "${ANDROID_SDK_TARGETS}")
99   else()
100     #old SDKs (r11 and older) don't provide compact list
101     execute_process(COMMAND ${ANDROID_EXECUTABLE} list target
102       RESULT_VARIABLE ANDROID_PROCESS
103       OUTPUT_VARIABLE ANDROID_SDK_TARGETS_FULL
104       ERROR_VARIABLE ANDROID_PROCESS_ERRORS
105       OUTPUT_STRIP_TRAILING_WHITESPACE
106       )
107     string(REGEX MATCHALL "(^|\n)id: [0-9]+ or \"([^\n]+[0-9+])\"(\n|$)" ANDROID_SDK_TARGETS_FULL "${ANDROID_SDK_TARGETS_FULL}")
108
109     SET(ANDROID_SDK_TARGETS "")
110     if(ANDROID_PROCESS EQUAL 0)
111       foreach(line ${ANDROID_SDK_TARGETS_FULL})
112         string(REGEX REPLACE "(^|\n)id: [0-9]+ or \"([^\n]+[0-9+])\"(\n|$)" "\\2" line "${line}")
113         list(APPEND ANDROID_SDK_TARGETS "${line}")
114       endforeach()
115     endif()
116   endif()
117
118   if(NOT ANDROID_PROCESS EQUAL 0)
119     message(ERROR "Failed to get list of installed Android targets.")
120     set(ANDROID_EXECUTABLE "ANDROID_EXECUTABLE-NOTFOUND")
121   endif()
122
123   # clear ANDROID_SDK_TARGET if no target is provided by user
124   if(NOT ANDROID_SDK_TARGET)
125     set(ANDROID_SDK_TARGET "" CACHE STRING "Android SDK target for the OpenCV Java API and samples")
126   endif()
127   if(ANDROID_SDK_TARGETS AND CMAKE_VERSION VERSION_GREATER "2.8")
128     set_property( CACHE ANDROID_SDK_TARGET PROPERTY STRINGS ${ANDROID_SDK_TARGETS} )
129   endif()
130 endif(ANDROID_EXECUTABLE)
131
132 # finds minimal installed SDK target compatible with provided names or API levels
133 # usage:
134 #   get_compatible_android_api_level(VARIABLE [level1] [level2] ...)
135 macro(android_get_compatible_target VAR)
136   set(${VAR} "${VAR}-NOTFOUND")
137   if(ANDROID_SDK_TARGETS)
138     list(GET ANDROID_SDK_TARGETS 0 __lvl)
139     string(REGEX MATCH "[0-9]+$" __lvl "${__lvl}")
140
141     #find minimal level mathing to all provided levels
142     foreach(lvl ${ARGN})
143       string(REGEX MATCH "[0-9]+$" __level "${lvl}")
144       if(__level GREATER __lvl)
145         set(__lvl ${__level})
146       endif()
147     endforeach()
148
149     #search for compatible levels
150     foreach(lvl ${ANDROID_SDK_TARGETS})
151       string(REGEX MATCH "[0-9]+$" __level "${lvl}")
152       if(__level EQUAL __lvl)
153         #look for exact match
154         foreach(usrlvl ${ARGN})
155           if("${usrlvl}" STREQUAL "${lvl}")
156             set(${VAR} "${lvl}")
157             break()
158           endif()
159         endforeach()
160         if("${${VAR}}" STREQUAL "${lvl}")
161           break() #exact match was found
162         elseif(NOT ${VAR})
163           set(${VAR} "${lvl}")
164         endif()
165       elseif(__level GREATER __lvl)
166         if(NOT ${VAR})
167           set(${VAR} "${lvl}")
168         endif()
169         break()
170       endif()
171     endforeach()
172
173     unset(__lvl)
174     unset(__level)
175   endif()
176 endmacro()
177
178 unset(__android_project_chain CACHE)
179 #add_android_project(target_name ${path} NATIVE_DEPS opencv_core LIBRARY_DEPS ${OpenCV_BINARY_DIR} SDK_TARGET 11)
180 macro(add_android_project target path)
181   # parse arguments
182   set(android_proj_arglist NATIVE_DEPS LIBRARY_DEPS SDK_TARGET IGNORE_JAVA IGNORE_MANIFEST)
183   set(__varname "android_proj_")
184   foreach(v ${android_proj_arglist})
185     set(${__varname}${v} "")
186   endforeach()
187   foreach(arg ${ARGN})
188     set(__var "${__varname}")
189     foreach(v ${android_proj_arglist})
190       if("${v}" STREQUAL "${arg}")
191         set(__varname "android_proj_${v}")
192         break()
193       endif()
194     endforeach()
195     if(__var STREQUAL __varname)
196       list(APPEND ${__var} "${arg}")
197     endif()
198   endforeach()
199
200   # get compatible SDK target
201   android_get_compatible_target(android_proj_sdk_target ${ANDROID_NATIVE_API_LEVEL} ${android_proj_SDK_TARGET})
202
203   if(NOT android_proj_sdk_target)
204     message(WARNING "Can not find any SDK target compatible with: ${ANDROID_NATIVE_API_LEVEL} ${android_proj_SDK_TARGET}
205                      The project ${target} will not be build")
206   endif()
207
208   # check native dependencies
209   if(android_proj_IGNORE_JAVA)
210     ocv_check_dependencies(${android_proj_NATIVE_DEPS})
211   else()
212     ocv_check_dependencies(${android_proj_NATIVE_DEPS} opencv_java)
213   endif()
214
215   if(OCV_DEPENDENCIES_FOUND AND android_proj_sdk_target AND ANDROID_EXECUTABLE AND ANT_EXECUTABLE AND ANDROID_TOOLS_Pkg_Revision GREATER 13 AND EXISTS "${path}/${ANDROID_MANIFEST_FILE}")
216
217     project(${target})
218     set(android_proj_bin_dir "${CMAKE_CURRENT_BINARY_DIR}/.build")
219
220     # get project sources
221     file(GLOB_RECURSE android_proj_files RELATIVE "${path}" "${path}/res/*" "${path}/src/*")
222
223     if(NOT android_proj_IGNORE_MANIFEST)
224       list(APPEND android_proj_files ${ANDROID_MANIFEST_FILE})
225     endif()
226
227     # copy sources out from the build tree
228     set(android_proj_file_deps "")
229     foreach(f ${android_proj_files})
230       add_custom_command(
231         OUTPUT "${android_proj_bin_dir}/${f}"
232         COMMAND ${CMAKE_COMMAND} -E copy "${path}/${f}" "${android_proj_bin_dir}/${f}"
233         MAIN_DEPENDENCY "${path}/${f}"
234         COMMENT "Copying ${f}")
235       list(APPEND android_proj_file_deps "${path}/${f}" "${android_proj_bin_dir}/${f}")
236     endforeach()
237
238     set(android_proj_lib_deps_commands "")
239     set(android_proj_target_files ${ANDROID_PROJECT_FILES})
240     ocv_list_add_prefix(android_proj_target_files "${android_proj_bin_dir}/")
241
242     # process Android library dependencies
243     foreach(dep ${android_proj_LIBRARY_DEPS})
244       file(RELATIVE_PATH __dep "${android_proj_bin_dir}" "${dep}")
245       list(APPEND android_proj_lib_deps_commands
246         COMMAND ${ANDROID_EXECUTABLE} --silent update project --path "${android_proj_bin_dir}" --library "${__dep}")
247     endforeach()
248
249     # fix Android project
250     add_custom_command(
251         OUTPUT ${android_proj_target_files}
252         COMMAND ${CMAKE_COMMAND} -E remove ${android_proj_target_files}
253         COMMAND ${ANDROID_EXECUTABLE} --silent update project --path "${android_proj_bin_dir}" --target "${android_proj_sdk_target}" --name "${target}"
254         ${android_proj_lib_deps_commands}
255         MAIN_DEPENDENCY "${android_proj_bin_dir}/${ANDROID_MANIFEST_FILE}"
256         DEPENDS "${path}/${ANDROID_MANIFEST_FILE}"
257         COMMENT "Updating Android project at ${path}. SDK target: ${android_proj_sdk_target}"
258         )
259
260     list(APPEND android_proj_file_deps ${android_proj_target_files})
261
262     # build native part
263     file(GLOB_RECURSE android_proj_jni_files "${path}/jni/*.c" "${path}/jni/*.h" "${path}/jni/*.cpp" "${path}/jni/*.hpp")
264     ocv_list_filterout(android_proj_jni_files "\\\\.svn")
265
266     if(android_proj_jni_files AND EXISTS ${path}/jni/Android.mk AND NOT DEFINED JNI_LIB_NAME)
267       file(STRINGS "${path}/jni/Android.mk" JNI_LIB_NAME REGEX "LOCAL_MODULE[ ]*:=[ ]*.*" )
268       string(REGEX REPLACE "LOCAL_MODULE[ ]*:=[ ]*([a-zA-Z_][a-zA-Z_0-9]*)[ ]*" "\\1" JNI_LIB_NAME "${JNI_LIB_NAME}")
269
270       if(JNI_LIB_NAME)
271         ocv_include_modules_recurse(${android_proj_NATIVE_DEPS})
272         ocv_include_directories("${path}/jni")
273
274         add_library(${JNI_LIB_NAME} MODULE ${android_proj_jni_files})
275         target_link_libraries(${JNI_LIB_NAME} ${OPENCV_LINKER_LIBS} ${android_proj_NATIVE_DEPS})
276
277         set_target_properties(${JNI_LIB_NAME} PROPERTIES
278             OUTPUT_NAME "${JNI_LIB_NAME}"
279             LIBRARY_OUTPUT_DIRECTORY "${android_proj_bin_dir}/libs/${ANDROID_NDK_ABI_NAME}"
280             )
281
282         get_target_property(android_proj_jni_location "${JNI_LIB_NAME}" LOCATION)
283     if (NOT (CMAKE_BUILD_TYPE MATCHES "debug"))
284         add_custom_command(TARGET ${JNI_LIB_NAME} POST_BUILD COMMAND ${CMAKE_STRIP} --strip-unneeded "${android_proj_jni_location}")
285     endif()
286       endif()
287     endif()
288
289     # build java part
290     if(android_proj_IGNORE_JAVA)
291       add_custom_command(
292          OUTPUT "${android_proj_bin_dir}/bin/${target}-debug.apk"
293          COMMAND ${ANT_EXECUTABLE} -q -noinput -k debug
294          COMMAND ${CMAKE_COMMAND} -E touch "${android_proj_bin_dir}/bin/${target}-debug.apk" # needed because ant does not update the timestamp of updated apk
295          WORKING_DIRECTORY "${android_proj_bin_dir}"
296          MAIN_DEPENDENCY "${android_proj_bin_dir}/${ANDROID_MANIFEST_FILE}"
297          DEPENDS ${android_proj_file_deps} ${JNI_LIB_NAME})
298     else()
299       add_custom_command(
300          OUTPUT "${android_proj_bin_dir}/bin/${target}-debug.apk"
301          COMMAND ${ANT_EXECUTABLE} -q -noinput -k debug
302          COMMAND ${CMAKE_COMMAND} -E touch "${android_proj_bin_dir}/bin/${target}-debug.apk" # needed because ant does not update the timestamp of updated apk
303          WORKING_DIRECTORY "${android_proj_bin_dir}"
304          MAIN_DEPENDENCY "${android_proj_bin_dir}/${ANDROID_MANIFEST_FILE}"
305          DEPENDS "${OpenCV_BINARY_DIR}/bin/.classes.jar.dephelper" opencv_java # as we are part of OpenCV we can just force this dependency
306          DEPENDS ${android_proj_file_deps} ${JNI_LIB_NAME})
307     endif()
308
309     unset(JNI_LIB_NAME)
310
311     add_custom_target(${target} ALL SOURCES "${android_proj_bin_dir}/bin/${target}-debug.apk" )
312     if(NOT android_proj_IGNORE_JAVA)
313       add_dependencies(${target} opencv_java)
314     endif()
315     if(android_proj_native_deps)
316       add_dependencies(${target} ${android_proj_native_deps})
317     endif()
318
319     if(__android_project_chain)
320       add_dependencies(${target} ${__android_project_chain})
321     endif()
322     set(__android_project_chain ${target} CACHE INTERNAL "auxiliary variable used for Android progects chaining")
323
324     # put the final .apk to the OpenCV's bin folder
325     add_custom_command(TARGET ${target} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy "${android_proj_bin_dir}/bin/${target}-debug.apk" "${OpenCV_BINARY_DIR}/bin/${target}.apk")
326     if(INSTALL_ANDROID_EXAMPLES AND "${target}" MATCHES "^example-")
327       #apk
328       install(FILES "${OpenCV_BINARY_DIR}/bin/${target}.apk" DESTINATION "samples" COMPONENT main)
329       get_filename_component(sample_dir "${path}" NAME)
330       #java part
331       list(REMOVE_ITEM android_proj_files ${ANDROID_MANIFEST_FILE})
332       foreach(f ${android_proj_files} ${ANDROID_MANIFEST_FILE})
333         get_filename_component(install_subdir "${f}" PATH)
334         install(FILES "${android_proj_bin_dir}/${f}" DESTINATION "samples/${sample_dir}/${install_subdir}" COMPONENT main)
335       endforeach()
336       #jni part + eclipse files
337       file(GLOB_RECURSE jni_files RELATIVE "${path}" "${path}/jni/*" "${path}/.cproject")
338       ocv_list_filterout(jni_files "\\\\.svn")
339       foreach(f ${jni_files} ".classpath" ".project" ".settings/org.eclipse.jdt.core.prefs")
340         get_filename_component(install_subdir "${f}" PATH)
341         install(FILES "${path}/${f}" DESTINATION "samples/${sample_dir}/${install_subdir}" COMPONENT main)
342       endforeach()
343       #update proj
344       if(android_proj_lib_deps_commands)
345         set(inst_lib_opt " --library ../../sdk/java")
346       endif()
347       install(CODE "EXECUTE_PROCESS(COMMAND ${ANDROID_EXECUTABLE} --silent update project --path . --target \"${android_proj_sdk_target}\" --name \"${target}\" ${inst_lib_opt}
348                                     WORKING_DIRECTORY \"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/samples/${sample_dir}\"
349                                    )"  COMPONENT main)
350       #empty 'gen'
351       install(CODE "MAKE_DIRECTORY(\"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/samples/${sample_dir}/gen\")" COMPONENT main)
352     endif()
353   endif()
354 endmacro()