1# Debugging function
2function(ocv_cmake_dump_vars)
3  cmake_parse_arguments(DUMP "" "TOFILE" "" ${ARGN})
4  set(regex "${DUMP_UNPARSED_ARGUMENTS}")
5  get_cmake_property(_variableNames VARIABLES)
6  set(VARS "")
7  foreach(_variableName ${_variableNames})
8    if(_variableName MATCHES "${regex}")
9      set(VARS "${VARS}${_variableName}=${${_variableName}}\n")
10    endif()
11  endforeach()
12  if(DUMP_TOFILE)
13    file(WRITE ${CMAKE_BINARY_DIR}/${DUMP_TOFILE} "${VARS}")
14  else()
15    message(AUTHOR_WARNING "${VARS}")
16  endif()
17endfunction()
18
19
20# Search packages for host system instead of packages for target system
21# in case of cross compilation thess macro should be defined by toolchain file
22if(NOT COMMAND find_host_package)
23  macro(find_host_package)
24    find_package(${ARGN})
25  endmacro()
26endif()
27if(NOT COMMAND find_host_program)
28  macro(find_host_program)
29    find_program(${ARGN})
30  endmacro()
31endif()
32
33# assert macro
34# Note: it doesn't support lists in arguments
35# Usage samples:
36#   ocv_assert(MyLib_FOUND)
37#   ocv_assert(DEFINED MyLib_INCLUDE_DIRS)
38macro(ocv_assert)
39  if(NOT (${ARGN}))
40    string(REPLACE ";" " " __assert_msg "${ARGN}")
41    message(AUTHOR_WARNING "Assertion failed: ${__assert_msg}")
42  endif()
43endmacro()
44
45macro(ocv_debug_message)
46#  string(REPLACE ";" " " __msg "${ARGN}")
47#  message(STATUS "${__msg}")
48endmacro()
49
50macro(ocv_check_environment_variables)
51  foreach(_var ${ARGN})
52    if(NOT DEFINED ${_var} AND DEFINED ENV{${_var}})
53      set(__value "$ENV{${_var}}")
54      file(TO_CMAKE_PATH "${__value}" __value) # Assume that we receive paths
55      set(${_var} "${__value}")
56      message(STATUS "Update variable ${_var} from environment: ${${_var}}")
57    endif()
58  endforeach()
59endmacro()
60
61# rename modules target to world if needed
62macro(_ocv_fix_target target_var)
63  if(BUILD_opencv_world)
64    if(OPENCV_MODULE_${${target_var}}_IS_PART_OF_WORLD)
65      set(${target_var} opencv_world)
66    endif()
67  endif()
68endmacro()
69
70# adds include directories in such way that directories from the OpenCV source tree go first
71function(ocv_include_directories)
72  ocv_debug_message("ocv_include_directories( ${ARGN} )")
73  set(__add_before "")
74  foreach(dir ${ARGN})
75    get_filename_component(__abs_dir "${dir}" ABSOLUTE)
76    if("${__abs_dir}" MATCHES "^${OpenCV_SOURCE_DIR}" OR "${__abs_dir}" MATCHES "^${OpenCV_BINARY_DIR}")
77      list(APPEND __add_before "${dir}")
78    else()
79      include_directories(AFTER SYSTEM "${dir}")
80    endif()
81  endforeach()
82  include_directories(BEFORE ${__add_before})
83endfunction()
84
85# adds include directories in such way that directories from the OpenCV source tree go first
86function(ocv_target_include_directories target)
87  _ocv_fix_target(target)
88  set(__params "")
89  foreach(dir ${ARGN})
90    get_filename_component(__abs_dir "${dir}" ABSOLUTE)
91    if("${__abs_dir}" MATCHES "^${OpenCV_SOURCE_DIR}" OR "${__abs_dir}" MATCHES "^${OpenCV_BINARY_DIR}")
92      list(APPEND __params "${__abs_dir}")
93    else()
94      list(APPEND __params "${dir}")
95    endif()
96  endforeach()
97  if(HAVE_CUDA OR CMAKE_VERSION VERSION_LESS 2.8.11)
98    include_directories(${__params})
99  else()
100    if(TARGET ${target})
101      target_include_directories(${target} PRIVATE ${__params})
102    else()
103      set(__new_inc "${OCV_TARGET_INCLUDE_DIRS_${target}};${__params}")
104      set(OCV_TARGET_INCLUDE_DIRS_${target} "${__new_inc}" CACHE INTERNAL "")
105    endif()
106  endif()
107endfunction()
108
109# clears all passed variables
110macro(ocv_clear_vars)
111  foreach(_var ${ARGN})
112    unset(${_var} CACHE)
113  endforeach()
114endmacro()
115
116set(OCV_COMPILER_FAIL_REGEX
117    "command line option .* is valid for .* but not for C\\+\\+" # GNU
118    "command line option .* is valid for .* but not for C" # GNU
119    "unrecognized .*option"                     # GNU
120    "unknown .*option"                          # Clang
121    "ignoring unknown option"                   # MSVC
122    "warning D9002"                             # MSVC, any lang
123    "option .*not supported"                    # Intel
124    "[Uu]nknown option"                         # HP
125    "[Ww]arning: [Oo]ption"                     # SunPro
126    "command option .* is not recognized"       # XL
127    "not supported in this configuration; ignored"       # AIX
128    "File with unknown suffix passed to linker" # PGI
129    "WARNING: unknown flag:"                    # Open64
130  )
131
132MACRO(ocv_check_compiler_flag LANG FLAG RESULT)
133  if(NOT DEFINED ${RESULT})
134    if("_${LANG}_" MATCHES "_CXX_")
135      set(_fname "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/src.cxx")
136      if("${CMAKE_CXX_FLAGS} ${FLAG} " MATCHES "-Werror " OR "${CMAKE_CXX_FLAGS} ${FLAG} " MATCHES "-Werror=unknown-pragmas ")
137        FILE(WRITE "${_fname}" "int main() { return 0; }\n")
138      else()
139        FILE(WRITE "${_fname}" "#pragma\nint main() { return 0; }\n")
140      endif()
141    elseif("_${LANG}_" MATCHES "_C_")
142      set(_fname "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/src.c")
143      if("${CMAKE_C_FLAGS} ${FLAG} " MATCHES "-Werror " OR "${CMAKE_C_FLAGS} ${FLAG} " MATCHES "-Werror=unknown-pragmas ")
144        FILE(WRITE "${_fname}" "int main(void) { return 0; }\n")
145      else()
146        FILE(WRITE "${_fname}" "#pragma\nint main(void) { return 0; }\n")
147      endif()
148    elseif("_${LANG}_" MATCHES "_OBJCXX_")
149      set(_fname "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/src.mm")
150      if("${CMAKE_CXX_FLAGS} ${FLAG} " MATCHES "-Werror " OR "${CMAKE_CXX_FLAGS} ${FLAG} " MATCHES "-Werror=unknown-pragmas ")
151        FILE(WRITE "${_fname}" "int main() { return 0; }\n")
152      else()
153        FILE(WRITE "${_fname}" "#pragma\nint main() { return 0; }\n")
154      endif()
155    else()
156      unset(_fname)
157    endif()
158    if(_fname)
159      MESSAGE(STATUS "Performing Test ${RESULT}")
160      TRY_COMPILE(${RESULT}
161        "${CMAKE_BINARY_DIR}"
162        "${_fname}"
163        COMPILE_DEFINITIONS "${FLAG}"
164        OUTPUT_VARIABLE OUTPUT)
165
166      FOREACH(_regex ${OCV_COMPILER_FAIL_REGEX})
167        IF("${OUTPUT}" MATCHES "${_regex}")
168          SET(${RESULT} 0)
169          break()
170        ENDIF()
171      ENDFOREACH()
172
173      IF(${RESULT})
174        SET(${RESULT} 1 CACHE INTERNAL "Test ${RESULT}")
175        MESSAGE(STATUS "Performing Test ${RESULT} - Success")
176      ELSE(${RESULT})
177        MESSAGE(STATUS "Performing Test ${RESULT} - Failed")
178        SET(${RESULT} "" CACHE INTERNAL "Test ${RESULT}")
179      ENDIF(${RESULT})
180    else()
181      SET(${RESULT} 0)
182    endif()
183  endif()
184ENDMACRO()
185
186macro(ocv_check_flag_support lang flag varname)
187  if("_${lang}_" MATCHES "_CXX_")
188    set(_lang CXX)
189  elseif("_${lang}_" MATCHES "_C_")
190    set(_lang C)
191  elseif("_${lang}_" MATCHES "_OBJCXX_")
192    set(_lang OBJCXX)
193  else()
194    set(_lang ${lang})
195  endif()
196
197  string(TOUPPER "${flag}" ${varname})
198  string(REGEX REPLACE "^(/|-)" "HAVE_${_lang}_" ${varname} "${${varname}}")
199  string(REGEX REPLACE " -|-|=| |\\." "_" ${varname} "${${varname}}")
200
201  ocv_check_compiler_flag("${_lang}" "${ARGN} ${flag}" ${${varname}})
202endmacro()
203
204# turns off warnings
205macro(ocv_warnings_disable)
206  if(NOT ENABLE_NOISY_WARNINGS)
207    set(_flag_vars "")
208    set(_msvc_warnings "")
209    set(_gxx_warnings "")
210    foreach(arg ${ARGN})
211      if(arg MATCHES "^CMAKE_")
212        list(APPEND _flag_vars ${arg})
213      elseif(arg MATCHES "^/wd")
214        list(APPEND _msvc_warnings ${arg})
215      elseif(arg MATCHES "^-W")
216        list(APPEND _gxx_warnings ${arg})
217      endif()
218    endforeach()
219    if(MSVC AND _msvc_warnings AND _flag_vars)
220      foreach(var ${_flag_vars})
221        foreach(warning ${_msvc_warnings})
222          set(${var} "${${var}} ${warning}")
223        endforeach()
224      endforeach()
225    elseif((CMAKE_COMPILER_IS_GNUCXX OR (UNIX AND CV_ICC)) AND _gxx_warnings AND _flag_vars)
226      foreach(var ${_flag_vars})
227        foreach(warning ${_gxx_warnings})
228          if(NOT warning MATCHES "^-Wno-")
229            string(REPLACE "${warning}" "" ${var} "${${var}}")
230            string(REPLACE "-W" "-Wno-" warning "${warning}")
231          endif()
232          ocv_check_flag_support(${var} "${warning}" _varname)
233          if(${_varname})
234            set(${var} "${${var}} ${warning}")
235          endif()
236        endforeach()
237      endforeach()
238    endif()
239    unset(_flag_vars)
240    unset(_msvc_warnings)
241    unset(_gxx_warnings)
242  endif(NOT ENABLE_NOISY_WARNINGS)
243endmacro()
244
245macro(add_apple_compiler_options the_module)
246  ocv_check_flag_support(OBJCXX "-fobjc-exceptions" HAVE_OBJC_EXCEPTIONS)
247  if(HAVE_OBJC_EXCEPTIONS)
248    foreach(source ${OPENCV_MODULE_${the_module}_SOURCES})
249      if("${source}" MATCHES "\\.mm$")
250        get_source_file_property(flags "${source}" COMPILE_FLAGS)
251        if(flags)
252          set(flags "${_flags} -fobjc-exceptions")
253        else()
254          set(flags "-fobjc-exceptions")
255        endif()
256
257        set_source_files_properties("${source}" PROPERTIES COMPILE_FLAGS "${flags}")
258      endif()
259    endforeach()
260  endif()
261endmacro()
262
263# Provides an option that the user can optionally select.
264# Can accept condition to control when option is available for user.
265# Usage:
266#   option(<option_variable> "help string describing the option" <initial value or boolean expression> [IF <condition>])
267macro(OCV_OPTION variable description value)
268  set(__value ${value})
269  set(__condition "")
270  set(__varname "__value")
271  foreach(arg ${ARGN})
272    if(arg STREQUAL "IF" OR arg STREQUAL "if")
273      set(__varname "__condition")
274    else()
275      list(APPEND ${__varname} ${arg})
276    endif()
277  endforeach()
278  unset(__varname)
279  if(__condition STREQUAL "")
280    set(__condition 2 GREATER 1)
281  endif()
282
283  if(${__condition})
284    if(__value MATCHES ";")
285      if(${__value})
286        option(${variable} "${description}" ON)
287      else()
288        option(${variable} "${description}" OFF)
289      endif()
290    elseif(DEFINED ${__value})
291      if(${__value})
292        option(${variable} "${description}" ON)
293      else()
294        option(${variable} "${description}" OFF)
295      endif()
296    else()
297      option(${variable} "${description}" ${__value})
298    endif()
299  else()
300    unset(${variable} CACHE)
301  endif()
302  unset(__condition)
303  unset(__value)
304endmacro()
305
306
307# Macros that checks if module have been installed.
308# After it adds module to build and define
309# constants passed as second arg
310macro(CHECK_MODULE module_name define)
311  set(${define} 0)
312  if(PKG_CONFIG_FOUND)
313    set(ALIAS               ALIASOF_${module_name})
314    set(ALIAS_FOUND                 ${ALIAS}_FOUND)
315    set(ALIAS_INCLUDE_DIRS   ${ALIAS}_INCLUDE_DIRS)
316    set(ALIAS_LIBRARY_DIRS   ${ALIAS}_LIBRARY_DIRS)
317    set(ALIAS_LIBRARIES         ${ALIAS}_LIBRARIES)
318
319    PKG_CHECK_MODULES(${ALIAS} ${module_name})
320
321    if(${ALIAS_FOUND})
322      set(${define} 1)
323      foreach(P "${ALIAS_INCLUDE_DIRS}")
324        if(${P})
325          list(APPEND VIDEOIO_INCLUDE_DIRS ${${P}})
326          list(APPEND HIGHGUI_INCLUDE_DIRS ${${P}})
327        endif()
328      endforeach()
329
330      foreach(P "${ALIAS_LIBRARY_DIRS}")
331        if(${P})
332          list(APPEND VIDEOIO_LIBRARY_DIRS ${${P}})
333          list(APPEND HIGHGUI_LIBRARY_DIRS ${${P}})
334        endif()
335      endforeach()
336
337      list(APPEND VIDEOIO_LIBRARIES ${${ALIAS_LIBRARIES}})
338      list(APPEND HIGHGUI_LIBRARIES ${${ALIAS_LIBRARIES}})
339    endif()
340  endif()
341endmacro()
342
343
344set(OPENCV_BUILD_INFO_FILE "${OpenCV_BINARY_DIR}/version_string.tmp")
345file(REMOVE "${OPENCV_BUILD_INFO_FILE}")
346function(ocv_output_status msg)
347  message(STATUS "${msg}")
348  string(REPLACE "\\" "\\\\" msg "${msg}")
349  string(REPLACE "\"" "\\\"" msg "${msg}")
350  file(APPEND "${OPENCV_BUILD_INFO_FILE}" "\"${msg}\\n\"\n")
351endfunction()
352
353macro(ocv_finalize_status)
354  if(NOT OPENCV_SKIP_STATUS_FINALIZATION)
355    if(DEFINED OPENCV_MODULE_opencv_core_BINARY_DIR)
356      execute_process(COMMAND ${CMAKE_COMMAND} -E copy_if_different "${OPENCV_BUILD_INFO_FILE}" "${OPENCV_MODULE_opencv_core_BINARY_DIR}/version_string.inc" OUTPUT_QUIET)
357    endif()
358  endif()
359endmacro()
360
361
362# Status report function.
363# Automatically align right column and selects text based on condition.
364# Usage:
365#   status(<text>)
366#   status(<heading> <value1> [<value2> ...])
367#   status(<heading> <condition> THEN <text for TRUE> ELSE <text for FALSE> )
368function(status text)
369  set(status_cond)
370  set(status_then)
371  set(status_else)
372
373  set(status_current_name "cond")
374  foreach(arg ${ARGN})
375    if(arg STREQUAL "THEN")
376      set(status_current_name "then")
377    elseif(arg STREQUAL "ELSE")
378      set(status_current_name "else")
379    else()
380      list(APPEND status_${status_current_name} ${arg})
381    endif()
382  endforeach()
383
384  if(DEFINED status_cond)
385    set(status_placeholder_length 32)
386    string(RANDOM LENGTH ${status_placeholder_length} ALPHABET " " status_placeholder)
387    string(LENGTH "${text}" status_text_length)
388    if(status_text_length LESS status_placeholder_length)
389      string(SUBSTRING "${text}${status_placeholder}" 0 ${status_placeholder_length} status_text)
390    elseif(DEFINED status_then OR DEFINED status_else)
391      ocv_output_status("${text}")
392      set(status_text "${status_placeholder}")
393    else()
394      set(status_text "${text}")
395    endif()
396
397    if(DEFINED status_then OR DEFINED status_else)
398      if(${status_cond})
399        string(REPLACE ";" " " status_then "${status_then}")
400        string(REGEX REPLACE "^[ \t]+" "" status_then "${status_then}")
401        ocv_output_status("${status_text} ${status_then}")
402      else()
403        string(REPLACE ";" " " status_else "${status_else}")
404        string(REGEX REPLACE "^[ \t]+" "" status_else "${status_else}")
405        ocv_output_status("${status_text} ${status_else}")
406      endif()
407    else()
408      string(REPLACE ";" " " status_cond "${status_cond}")
409      string(REGEX REPLACE "^[ \t]+" "" status_cond "${status_cond}")
410      ocv_output_status("${status_text} ${status_cond}")
411    endif()
412  else()
413    ocv_output_status("${text}")
414  endif()
415endfunction()
416
417
418# remove all matching elements from the list
419macro(ocv_list_filterout lst regex)
420  foreach(item ${${lst}})
421    if(item MATCHES "${regex}")
422      list(REMOVE_ITEM ${lst} "${item}")
423    endif()
424  endforeach()
425endmacro()
426
427
428# stable & safe duplicates removal macro
429macro(ocv_list_unique __lst)
430  if(${__lst})
431    list(REMOVE_DUPLICATES ${__lst})
432  endif()
433endmacro()
434
435
436# safe list reversal macro
437macro(ocv_list_reverse __lst)
438  if(${__lst})
439    list(REVERSE ${__lst})
440  endif()
441endmacro()
442
443
444# safe list sorting macro
445macro(ocv_list_sort __lst)
446  if(${__lst})
447    list(SORT ${__lst})
448  endif()
449endmacro()
450
451
452# add prefix to each item in the list
453macro(ocv_list_add_prefix LST PREFIX)
454  set(__tmp "")
455  foreach(item ${${LST}})
456    list(APPEND __tmp "${PREFIX}${item}")
457  endforeach()
458  set(${LST} ${__tmp})
459  unset(__tmp)
460endmacro()
461
462
463# add suffix to each item in the list
464macro(ocv_list_add_suffix LST SUFFIX)
465  set(__tmp "")
466  foreach(item ${${LST}})
467    list(APPEND __tmp "${item}${SUFFIX}")
468  endforeach()
469  set(${LST} ${__tmp})
470  unset(__tmp)
471endmacro()
472
473
474# gets and removes the first element from list
475macro(ocv_list_pop_front LST VAR)
476  if(${LST})
477    list(GET ${LST} 0 ${VAR})
478    list(REMOVE_AT ${LST} 0)
479  else()
480    set(${VAR} "")
481  endif()
482endmacro()
483
484
485# simple regex escaping routine (does not cover all cases!!!)
486macro(ocv_regex_escape var regex)
487  string(REGEX REPLACE "([+.*^$])" "\\\\1" ${var} "${regex}")
488endmacro()
489
490
491# convert list of paths to full paths
492macro(ocv_convert_to_full_paths VAR)
493  if(${VAR})
494    set(__tmp "")
495    foreach(path ${${VAR}})
496      get_filename_component(${VAR} "${path}" ABSOLUTE)
497      list(APPEND __tmp "${${VAR}}")
498    endforeach()
499    set(${VAR} ${__tmp})
500    unset(__tmp)
501  endif()
502endmacro()
503
504
505# convert list of paths to libraries names without lib prefix
506macro(ocv_convert_to_lib_name var)
507  set(__tmp "")
508  foreach(path ${ARGN})
509    get_filename_component(__tmp_name "${path}" NAME_WE)
510    string(REGEX REPLACE "^lib" "" __tmp_name ${__tmp_name})
511    list(APPEND __tmp "${__tmp_name}")
512  endforeach()
513  set(${var} ${__tmp})
514  unset(__tmp)
515  unset(__tmp_name)
516endmacro()
517
518
519# add install command
520function(ocv_install_target)
521  install(TARGETS ${ARGN})
522
523  set(isPackage 0)
524  unset(__package)
525  unset(__target)
526  foreach(e ${ARGN})
527    if(NOT DEFINED __target)
528      set(__target "${e}")
529    endif()
530    if(isPackage EQUAL 1)
531      set(__package "${e}")
532      break()
533    endif()
534    if(e STREQUAL "EXPORT")
535      set(isPackage 1)
536    endif()
537  endforeach()
538
539  if(DEFINED __package)
540    list(APPEND ${__package}_TARGETS ${__target})
541    set(${__package}_TARGETS "${${__package}_TARGETS}" CACHE INTERNAL "List of ${__package} targets")
542  endif()
543
544  if(INSTALL_CREATE_DISTRIB)
545    if(MSVC AND NOT BUILD_SHARED_LIBS)
546      set(__target "${ARGV0}")
547
548      set(isArchive 0)
549      set(isDst 0)
550      unset(__dst)
551      foreach(e ${ARGN})
552        if(isDst EQUAL 1)
553          set(__dst "${e}")
554          break()
555        endif()
556        if(isArchive EQUAL 1 AND e STREQUAL "DESTINATION")
557          set(isDst 1)
558        endif()
559        if(e STREQUAL "ARCHIVE")
560          set(isArchive 1)
561        else()
562          set(isArchive 0)
563        endif()
564      endforeach()
565
566#      message(STATUS "Process ${__target} dst=${__dst}...")
567      if(DEFINED __dst)
568        if(CMAKE_VERSION VERSION_LESS 2.8.12)
569          get_target_property(fname ${__target} LOCATION_DEBUG)
570          if(fname MATCHES "\\.lib$")
571            string(REGEX REPLACE "\\.lib$" ".pdb" fname "${fname}")
572            install(FILES ${fname} DESTINATION ${__dst} CONFIGURATIONS Debug)
573          endif()
574
575          get_target_property(fname ${__target} LOCATION_RELEASE)
576          if(fname MATCHES "\\.lib$")
577            string(REGEX REPLACE "\\.lib$" ".pdb" fname "${fname}")
578            install(FILES ${fname} DESTINATION ${__dst} CONFIGURATIONS Release)
579          endif()
580        else()
581          # CMake 2.8.12 brokes PDB support in STATIC libraries for MSVS
582        endif()
583      endif()
584    endif()
585  endif()
586endfunction()
587
588
589# read set of version defines from the header file
590macro(ocv_parse_header FILENAME FILE_VAR)
591  set(vars_regex "")
592  set(__parnet_scope OFF)
593  set(__add_cache OFF)
594  foreach(name ${ARGN})
595    if("${name}" STREQUAL "PARENT_SCOPE")
596      set(__parnet_scope ON)
597    elseif("${name}" STREQUAL "CACHE")
598      set(__add_cache ON)
599    elseif(vars_regex)
600      set(vars_regex "${vars_regex}|${name}")
601    else()
602      set(vars_regex "${name}")
603    endif()
604  endforeach()
605  if(EXISTS "${FILENAME}")
606    file(STRINGS "${FILENAME}" ${FILE_VAR} REGEX "#define[ \t]+(${vars_regex})[ \t]+[0-9]+" )
607  else()
608    unset(${FILE_VAR})
609  endif()
610  foreach(name ${ARGN})
611    if(NOT "${name}" STREQUAL "PARENT_SCOPE" AND NOT "${name}" STREQUAL "CACHE")
612      if(${FILE_VAR})
613        if(${FILE_VAR} MATCHES ".+[ \t]${name}[ \t]+([0-9]+).*")
614          string(REGEX REPLACE ".+[ \t]${name}[ \t]+([0-9]+).*" "\\1" ${name} "${${FILE_VAR}}")
615        else()
616          set(${name} "")
617        endif()
618        if(__add_cache)
619          set(${name} ${${name}} CACHE INTERNAL "${name} parsed from ${FILENAME}" FORCE)
620        elseif(__parnet_scope)
621          set(${name} "${${name}}" PARENT_SCOPE)
622        endif()
623      else()
624        unset(${name} CACHE)
625      endif()
626    endif()
627  endforeach()
628endmacro()
629
630# read single version define from the header file
631macro(ocv_parse_header2 LIBNAME HDR_PATH VARNAME)
632  ocv_clear_vars(${LIBNAME}_VERSION_MAJOR
633                 ${LIBNAME}_VERSION_MAJOR
634                 ${LIBNAME}_VERSION_MINOR
635                 ${LIBNAME}_VERSION_PATCH
636                 ${LIBNAME}_VERSION_TWEAK
637                 ${LIBNAME}_VERSION_STRING)
638  set(${LIBNAME}_H "")
639  if(EXISTS "${HDR_PATH}")
640    file(STRINGS "${HDR_PATH}" ${LIBNAME}_H REGEX "^#define[ \t]+${VARNAME}[ \t]+\"[^\"]*\".*$" LIMIT_COUNT 1)
641  endif()
642
643  if(${LIBNAME}_H)
644    string(REGEX REPLACE "^.*[ \t]${VARNAME}[ \t]+\"([0-9]+).*$" "\\1" ${LIBNAME}_VERSION_MAJOR "${${LIBNAME}_H}")
645    string(REGEX REPLACE "^.*[ \t]${VARNAME}[ \t]+\"[0-9]+\\.([0-9]+).*$" "\\1" ${LIBNAME}_VERSION_MINOR  "${${LIBNAME}_H}")
646    string(REGEX REPLACE "^.*[ \t]${VARNAME}[ \t]+\"[0-9]+\\.[0-9]+\\.([0-9]+).*$" "\\1" ${LIBNAME}_VERSION_PATCH "${${LIBNAME}_H}")
647    set(${LIBNAME}_VERSION_MAJOR ${${LIBNAME}_VERSION_MAJOR} ${ARGN})
648    set(${LIBNAME}_VERSION_MINOR ${${LIBNAME}_VERSION_MINOR} ${ARGN})
649    set(${LIBNAME}_VERSION_PATCH ${${LIBNAME}_VERSION_PATCH} ${ARGN})
650    set(${LIBNAME}_VERSION_STRING "${${LIBNAME}_VERSION_MAJOR}.${${LIBNAME}_VERSION_MINOR}.${${LIBNAME}_VERSION_PATCH}")
651
652    # append a TWEAK version if it exists:
653    set(${LIBNAME}_VERSION_TWEAK "")
654    if("${${LIBNAME}_H}" MATCHES "^.*[ \t]${VARNAME}[ \t]+\"[0-9]+\\.[0-9]+\\.[0-9]+\\.([0-9]+).*$")
655      set(${LIBNAME}_VERSION_TWEAK "${CMAKE_MATCH_1}" ${ARGN})
656    endif()
657    if(${LIBNAME}_VERSION_TWEAK)
658      set(${LIBNAME}_VERSION_STRING "${${LIBNAME}_VERSION_STRING}.${${LIBNAME}_VERSION_TWEAK}" ${ARGN})
659    else()
660      set(${LIBNAME}_VERSION_STRING "${${LIBNAME}_VERSION_STRING}" ${ARGN})
661    endif()
662  endif()
663endmacro()
664
665# read single version info from the pkg file
666macro(ocv_parse_pkg LIBNAME PKG_PATH SCOPE)
667  if(EXISTS "${PKG_PATH}/${LIBNAME}.pc")
668    file(STRINGS "${PKG_PATH}/${LIBNAME}.pc" line_to_parse REGEX "^Version:[ \t]+[0-9.]*.*$" LIMIT_COUNT 1)
669    STRING(REGEX REPLACE ".*Version: ([^ ]+).*" "\\1" ALIASOF_${LIBNAME}_VERSION "${line_to_parse}" )
670  endif()
671endmacro()
672
673################################################################################################
674# short command to setup source group
675function(ocv_source_group group)
676  if(BUILD_opencv_world AND OPENCV_MODULE_${the_module}_IS_PART_OF_WORLD)
677    set(group "${the_module}\\${group}")
678  endif()
679  cmake_parse_arguments(SG "" "DIRBASE" "GLOB;GLOB_RECURSE;FILES" ${ARGN})
680  set(files "")
681  if(SG_FILES)
682    list(APPEND files ${SG_FILES})
683  endif()
684  if(SG_GLOB)
685    file(GLOB srcs ${SG_GLOB})
686    list(APPEND files ${srcs})
687  endif()
688  if(SG_GLOB_RECURSE)
689    file(GLOB_RECURSE srcs ${SG_GLOB_RECURSE})
690    list(APPEND files ${srcs})
691  endif()
692  if(SG_DIRBASE)
693    foreach(f ${files})
694      file(RELATIVE_PATH fpart "${SG_DIRBASE}" "${f}")
695      if(fpart MATCHES "^\\.\\.")
696        message(AUTHOR_WARNING "Can't detect subpath for source_group command: Group=${group} FILE=${f} DIRBASE=${SG_DIRBASE}")
697        set(fpart "")
698      else()
699        get_filename_component(fpart "${fpart}" PATH)
700        if(fpart)
701          set(fpart "/${fpart}") # add '/'
702          string(REPLACE "/" "\\" fpart "${fpart}")
703        endif()
704      endif()
705      source_group("${group}${fpart}" FILES ${f})
706    endforeach()
707  else()
708    source_group(${group} FILES ${files})
709  endif()
710endfunction()
711
712function(ocv_target_link_libraries target)
713  _ocv_fix_target(target)
714  set(LINK_DEPS ${ARGN})
715  # process world
716  if(BUILD_opencv_world)
717    foreach(m ${OPENCV_MODULES_BUILD})
718      if(OPENCV_MODULE_${m}_IS_PART_OF_WORLD)
719        if(";${LINK_DEPS};" MATCHES ";${m};")
720          list(REMOVE_ITEM LINK_DEPS ${m})
721          if(NOT (";${LINK_DEPS};" MATCHES ";opencv_world;"))
722            list(APPEND LINK_DEPS opencv_world)
723          endif()
724        endif()
725      endif()
726    endforeach()
727  endif()
728  target_link_libraries(${target} ${LINK_DEPS})
729endfunction()
730
731function(_ocv_append_target_includes target)
732  if(DEFINED OCV_TARGET_INCLUDE_DIRS_${target})
733    target_include_directories(${target} PRIVATE ${OCV_TARGET_INCLUDE_DIRS_${target}})
734    if (TARGET ${target}_object)
735      target_include_directories(${target}_object PRIVATE ${OCV_TARGET_INCLUDE_DIRS_${target}})
736    endif()
737    unset(OCV_TARGET_INCLUDE_DIRS_${target} CACHE)
738  endif()
739endfunction()
740
741function(ocv_add_executable target)
742  add_executable(${target} ${ARGN})
743  _ocv_append_target_includes(${target})
744endfunction()
745
746function(ocv_add_library target)
747  set(cuda_objs "")
748  if(HAVE_CUDA)
749    set(cuda_srcs "")
750
751    foreach(var ${ARGN})
752      if(var MATCHES ".cu")
753        list(APPEND cuda_srcs ${var})
754      endif()
755    endforeach()
756
757    if(cuda_srcs)
758      ocv_include_directories(${CUDA_INCLUDE_DIRS})
759      ocv_cuda_compile(cuda_objs ${lib_cuda_srcs} ${lib_cuda_hdrs})
760    endif()
761    set(OPENCV_MODULE_${target}_CUDA_OBJECTS ${cuda_objs} CACHE INTERNAL "Compiled CUDA object files")
762  endif()
763
764  add_library(${target} ${ARGN} ${cuda_objs})
765
766  # Add OBJECT library (added in cmake 2.8.8) to use in compound modules
767  if (NOT CMAKE_VERSION VERSION_LESS "2.8.8"
768      AND NOT OPENCV_MODULE_${target}_CHILDREN
769      AND NOT OPENCV_MODULE_${target}_CLASS STREQUAL "BINDINGS"
770      AND NOT ${target} STREQUAL "opencv_ts"
771    )
772    set(sources ${ARGN})
773    ocv_list_filterout(sources "\\\\.(cl|inc)$")
774    add_library(${target}_object OBJECT ${sources})
775    set_target_properties(${target}_object PROPERTIES
776      EXCLUDE_FROM_ALL True
777      EXCLUDE_FROM_DEFAULT_BUILD True
778      POSITION_INDEPENDENT_CODE True
779      )
780    if (ENABLE_SOLUTION_FOLDERS)
781      set_target_properties(${target}_object PROPERTIES FOLDER "object_libraries")
782    endif()
783    unset(sources)
784  endif()
785
786  _ocv_append_target_includes(${target})
787endfunction()
788
789# build the list of opencv libs and dependencies for all modules
790#  _modules - variable to hold list of all modules
791#  _extra - variable to hold list of extra dependencies
792#  _3rdparty - variable to hold list of prebuilt 3rdparty libraries
793macro(ocv_get_all_libs _modules _extra _3rdparty)
794  set(${_modules} "")
795  set(${_extra} "")
796  set(${_3rdparty} "")
797  foreach(m ${OPENCV_MODULES_PUBLIC})
798    get_target_property(deps ${m} INTERFACE_LINK_LIBRARIES)
799    if(NOT deps)
800      set(deps "")
801    endif()
802    list(INSERT ${_modules} 0 ${deps} ${m})
803    foreach (dep ${deps} ${OPENCV_LINKER_LIBS})
804      if (NOT DEFINED OPENCV_MODULE_${dep}_LOCATION)
805        if (TARGET ${dep})
806          get_target_property(_output ${dep} ARCHIVE_OUTPUT_DIRECTORY)
807          if ("${_output}" STREQUAL "${3P_LIBRARY_OUTPUT_PATH}")
808            list(INSERT ${_3rdparty} 0 ${dep})
809          else()
810            list(INSERT ${_extra} 0 ${dep})
811          endif()
812        else()
813          list(INSERT ${_extra} 0 ${dep})
814        endif()
815      endif()
816    endforeach()
817  endforeach()
818
819  # ippicv specific handling
820  list(FIND ${_extra} "ippicv" ippicv_idx)
821  if (${ippicv_idx} GREATER -1)
822    list(REMOVE_ITEM ${_extra} "ippicv")
823    list(INSERT ${_3rdparty} 0 "ippicv")
824  endif()
825
826  # split 3rdparty libs and modules
827  list(REMOVE_ITEM ${_modules} ${${_3rdparty}} ${${_extra}})
828
829  # convert CMake lists to makefile literals
830  foreach(lst ${_modules} ${_3rdparty} ${_extra})
831    ocv_list_unique(${lst})
832    ocv_list_reverse(${lst})
833  endforeach()
834endmacro()
835