Merge pull request #8953 from mattmyne:cocoa_window_32_64_objc_fix
[platform/upstream/opencv.git] / cmake / OpenCVModule.cmake
1 # Local variables (set for each module):
2 #
3 # name       - short name in lower case i.e. core
4 # the_module - full name in lower case i.e. opencv_core
5
6 # Global variables:
7 #
8 # OPENCV_MODULE_${the_module}_LOCATION
9 # OPENCV_MODULE_${the_module}_BINARY_DIR
10 # OPENCV_MODULE_${the_module}_DESCRIPTION
11 # OPENCV_MODULE_${the_module}_CLASS - PUBLIC|INTERNAL|BINDINGS
12 # OPENCV_MODULE_${the_module}_HEADERS
13 # OPENCV_MODULE_${the_module}_SOURCES
14 # OPENCV_MODULE_${the_module}_DEPS - final flattened set of module dependencies
15 # OPENCV_MODULE_${the_module}_DEPS_TO_LINK - differs from above for world build only
16 # OPENCV_MODULE_${the_module}_DEPS_EXT - non-module dependencies
17 # OPENCV_MODULE_${the_module}_REQ_DEPS
18 # OPENCV_MODULE_${the_module}_OPT_DEPS
19 # OPENCV_MODULE_${the_module}_PRIVATE_REQ_DEPS
20 # OPENCV_MODULE_${the_module}_PRIVATE_OPT_DEPS
21 # OPENCV_MODULE_${the_module}_IS_PART_OF_WORLD
22 # OPENCV_MODULE_${the_module}_CUDA_OBJECTS - compiled CUDA objects list
23 # OPENCV_MODULE_${the_module}_CHILDREN - list of submodules for compound modules (cmake >= 2.8.8)
24 # OPENCV_MODULE_${the_module}_WRAPPERS - list of wrappers supporting this module
25 # HAVE_${the_module} - for fast check of module availability
26
27 # To control the setup of the module you could also set:
28 # the_description - text to be used as current module description
29 # the_label - label for current module
30 # OPENCV_MODULE_TYPE - STATIC|SHARED - set to force override global settings for current module
31 # OPENCV_MODULE_IS_PART_OF_WORLD - ON|OFF (default ON) - should the module be added to the opencv_world?
32 # BUILD_${the_module}_INIT - ON|OFF (default ON) - initial value for BUILD_${the_module}
33 # OPENCV_MODULE_CHILDREN - list of submodules
34
35 # The verbose template for OpenCV module:
36 #
37 #   ocv_add_module(modname <dependencies>)
38 #   ocv_glob_module_sources(([EXCLUDE_CUDA] <extra sources&headers>)
39 #                          or glob them manually and ocv_set_module_sources(...)
40 #   ocv_module_include_directories(<extra include directories>)
41 #   ocv_create_module()
42 #   <add extra link dependencies, compiler options, etc>
43 #   ocv_add_precompiled_headers(${the_module})
44 #   <add extra installation rules>
45 #   ocv_add_accuracy_tests(<extra dependencies>)
46 #   ocv_add_perf_tests(<extra dependencies>)
47 #   ocv_add_samples(<extra dependencies>)
48 #
49 #
50 # If module have no "extra" then you can define it in one line:
51 #
52 #   ocv_define_module(modname <dependencies>)
53
54 # clean flags for modules enabled on previous cmake run
55 # this is necessary to correctly handle modules removal
56 foreach(mod ${OPENCV_MODULES_BUILD} ${OPENCV_MODULES_DISABLED_USER} ${OPENCV_MODULES_DISABLED_AUTO} ${OPENCV_MODULES_DISABLED_FORCE})
57   if(HAVE_${mod})
58     unset(HAVE_${mod} CACHE)
59   endif()
60   unset(OPENCV_MODULE_${mod}_DEPS CACHE)
61   unset(OPENCV_MODULE_${mod}_DEPS_EXT CACHE)
62   unset(OPENCV_MODULE_${mod}_REQ_DEPS CACHE)
63   unset(OPENCV_MODULE_${mod}_OPT_DEPS CACHE)
64   unset(OPENCV_MODULE_${mod}_PRIVATE_REQ_DEPS CACHE)
65   unset(OPENCV_MODULE_${mod}_PRIVATE_OPT_DEPS CACHE)
66   unset(OPENCV_MODULE_${mod}_LINK_DEPS CACHE)
67   unset(OPENCV_MODULE_${mod}_WRAPPERS CACHE)
68   unset(OPENCV_DEPENDANT_TARGETS_${mod} CACHE)
69 endforeach()
70
71 # clean modules info which needs to be recalculated
72 set(OPENCV_MODULES_PUBLIC         "" CACHE INTERNAL "List of OpenCV modules marked for export")
73 set(OPENCV_MODULES_BUILD          "" CACHE INTERNAL "List of OpenCV modules included into the build")
74 set(OPENCV_MODULES_DISABLED_USER  "" CACHE INTERNAL "List of OpenCV modules explicitly disabled by user")
75 set(OPENCV_MODULES_DISABLED_AUTO  "" CACHE INTERNAL "List of OpenCV modules implicitly disabled due to dependencies")
76 set(OPENCV_MODULES_DISABLED_FORCE "" CACHE INTERNAL "List of OpenCV modules which can not be build in current configuration")
77 unset(OPENCV_WORLD_MODULES CACHE)
78
79 # adds dependencies to OpenCV module
80 # Usage:
81 #   add_dependencies(opencv_<name> [REQUIRED] [<list of dependencies>] [OPTIONAL <list of modules>] [WRAP <list of wrappers>])
82 # Notes:
83 # * <list of dependencies> - can include full names of modules or full pathes to shared/static libraries or cmake targets
84 macro(ocv_add_dependencies full_modname)
85   ocv_debug_message("ocv_add_dependencies(" ${full_modname} ${ARGN} ")")
86   #we don't clean the dependencies here to allow this macro several times for every module
87   foreach(d "REQUIRED" ${ARGN})
88     if(d STREQUAL "REQUIRED")
89       set(__depsvar OPENCV_MODULE_${full_modname}_REQ_DEPS)
90     elseif(d STREQUAL "OPTIONAL")
91       set(__depsvar OPENCV_MODULE_${full_modname}_OPT_DEPS)
92     elseif(d STREQUAL "PRIVATE_REQUIRED")
93       set(__depsvar OPENCV_MODULE_${full_modname}_PRIVATE_REQ_DEPS)
94     elseif(d STREQUAL "PRIVATE_OPTIONAL")
95       set(__depsvar OPENCV_MODULE_${full_modname}_PRIVATE_OPT_DEPS)
96     elseif(d STREQUAL "WRAP")
97       set(__depsvar OPENCV_MODULE_${full_modname}_WRAPPERS)
98     else()
99       list(APPEND ${__depsvar} "${d}")
100     endif()
101   endforeach()
102   unset(__depsvar)
103
104   # hack for python
105   set(__python_idx)
106   list(FIND OPENCV_MODULE_${full_modname}_WRAPPERS "python" __python_idx)
107   if (NOT __python_idx EQUAL -1)
108     list(REMOVE_ITEM OPENCV_MODULE_${full_modname}_WRAPPERS "python")
109     list(APPEND OPENCV_MODULE_${full_modname}_WRAPPERS "python2" "python3")
110   endif()
111   unset(__python_idx)
112
113   ocv_list_unique(OPENCV_MODULE_${full_modname}_REQ_DEPS)
114   ocv_list_unique(OPENCV_MODULE_${full_modname}_OPT_DEPS)
115   ocv_list_unique(OPENCV_MODULE_${full_modname}_PRIVATE_REQ_DEPS)
116   ocv_list_unique(OPENCV_MODULE_${full_modname}_PRIVATE_OPT_DEPS)
117   ocv_list_unique(OPENCV_MODULE_${full_modname}_WRAPPERS)
118
119   set(OPENCV_MODULE_${full_modname}_REQ_DEPS ${OPENCV_MODULE_${full_modname}_REQ_DEPS}
120     CACHE INTERNAL "Required dependencies of ${full_modname} module")
121   set(OPENCV_MODULE_${full_modname}_OPT_DEPS ${OPENCV_MODULE_${full_modname}_OPT_DEPS}
122     CACHE INTERNAL "Optional dependencies of ${full_modname} module")
123   set(OPENCV_MODULE_${full_modname}_PRIVATE_REQ_DEPS ${OPENCV_MODULE_${full_modname}_PRIVATE_REQ_DEPS}
124     CACHE INTERNAL "Required private dependencies of ${full_modname} module")
125   set(OPENCV_MODULE_${full_modname}_PRIVATE_OPT_DEPS ${OPENCV_MODULE_${full_modname}_PRIVATE_OPT_DEPS}
126     CACHE INTERNAL "Optional private dependencies of ${full_modname} module")
127   set(OPENCV_MODULE_${full_modname}_WRAPPERS ${OPENCV_MODULE_${full_modname}_WRAPPERS}
128     CACHE INTERNAL "List of wrappers supporting module ${full_modname}")
129 endmacro()
130
131 # declare new OpenCV module in current folder
132 # Usage:
133 #   ocv_add_module(<name> [INTERNAL|BINDINGS] [REQUIRED] [<list of dependencies>] [OPTIONAL <list of optional dependencies>] [WRAP <list of wrappers>])
134 # Example:
135 #   ocv_add_module(yaom INTERNAL opencv_core opencv_highgui opencv_flann OPTIONAL opencv_cudev)
136 macro(ocv_add_module _name)
137   ocv_debug_message("ocv_add_module(" ${_name} ${ARGN} ")")
138   string(TOLOWER "${_name}" name)
139   set(the_module opencv_${name})
140
141   # the first pass - collect modules info, the second pass - create targets
142   if(OPENCV_INITIAL_PASS)
143     #guard agains redefinition
144     if(";${OPENCV_MODULES_BUILD};${OPENCV_MODULES_DISABLED_USER};" MATCHES ";${the_module};")
145       message(FATAL_ERROR "Redefinition of the ${the_module} module.
146   at:                    ${CMAKE_CURRENT_SOURCE_DIR}
147   previously defined at: ${OPENCV_MODULE_${the_module}_LOCATION}
148 ")
149     endif()
150
151     if(NOT DEFINED the_description)
152       set(the_description "The ${name} OpenCV module")
153     endif()
154
155     if(NOT DEFINED BUILD_${the_module}_INIT)
156       set(BUILD_${the_module}_INIT ON)
157     endif()
158
159     # create option to enable/disable this module
160     option(BUILD_${the_module} "Include ${the_module} module into the OpenCV build" ${BUILD_${the_module}_INIT})
161
162     # remember the module details
163     set(OPENCV_MODULE_${the_module}_DESCRIPTION "${the_description}" CACHE INTERNAL "Brief description of ${the_module} module")
164     set(OPENCV_MODULE_${the_module}_LOCATION    "${CMAKE_CURRENT_SOURCE_DIR}" CACHE INTERNAL "Location of ${the_module} module sources")
165
166     set(OPENCV_MODULE_${the_module}_LINK_DEPS "" CACHE INTERNAL "")
167
168     # parse list of dependencies
169     if("${ARGV1}" STREQUAL "INTERNAL" OR "${ARGV1}" STREQUAL "BINDINGS")
170       set(OPENCV_MODULE_${the_module}_CLASS "${ARGV1}" CACHE INTERNAL "The category of the module")
171       set(__ocv_argn__ ${ARGN})
172       list(REMOVE_AT __ocv_argn__ 0)
173       ocv_add_dependencies(${the_module} ${__ocv_argn__})
174       unset(__ocv_argn__)
175     else()
176       set(OPENCV_MODULE_${the_module}_CLASS "PUBLIC" CACHE INTERNAL "The category of the module")
177       ocv_add_dependencies(${the_module} ${ARGN})
178       if(BUILD_${the_module})
179         set(OPENCV_MODULES_PUBLIC ${OPENCV_MODULES_PUBLIC} "${the_module}" CACHE INTERNAL "List of OpenCV modules marked for export")
180       endif()
181     endif()
182
183     # add self to the world dependencies
184     if((NOT DEFINED OPENCV_MODULE_IS_PART_OF_WORLD
185         AND NOT OPENCV_MODULE_${the_module}_CLASS STREQUAL "BINDINGS"
186         AND (NOT OPENCV_PROCESSING_EXTRA_MODULES OR NOT OPENCV_WORLD_EXCLUDE_EXTRA_MODULES)
187         AND (NOT BUILD_SHARED_LIBS OR NOT "x${OPENCV_MODULE_TYPE}" STREQUAL "xSTATIC"))
188         OR OPENCV_MODULE_IS_PART_OF_WORLD
189         )
190       set(OPENCV_MODULE_${the_module}_IS_PART_OF_WORLD ON CACHE INTERNAL "")
191       ocv_add_dependencies(opencv_world OPTIONAL ${the_module})
192     else()
193       set(OPENCV_MODULE_${the_module}_IS_PART_OF_WORLD OFF CACHE INTERNAL "")
194     endif()
195
196     if(NOT DEFINED the_label)
197       if(OPENCV_PROCESSING_EXTRA_MODULES)
198         set(the_label "Extra")
199       else()
200         set(the_label "Main")
201       endif()
202     endif()
203     set(OPENCV_MODULE_${the_module}_LABEL "${the_label};${the_module}" CACHE INTERNAL "")
204
205     if(BUILD_${the_module})
206       set(OPENCV_MODULES_BUILD ${OPENCV_MODULES_BUILD} "${the_module}" CACHE INTERNAL "List of OpenCV modules included into the build")
207     else()
208       set(OPENCV_MODULES_DISABLED_USER ${OPENCV_MODULES_DISABLED_USER} "${the_module}" CACHE INTERNAL "List of OpenCV modules explicitly disabled by user")
209     endif()
210
211     # add submodules if any
212     set(OPENCV_MODULE_${the_module}_CHILDREN "${OPENCV_MODULE_CHILDREN}" CACHE INTERNAL "List of ${the_module} submodules")
213
214     # add reverse wrapper dependencies
215     foreach (wrapper ${OPENCV_MODULE_${the_module}_WRAPPERS})
216       ocv_add_dependencies(opencv_${wrapper} OPTIONAL ${the_module})
217     endforeach()
218
219     # stop processing of current file
220     return()
221   else()
222     set(OPENCV_MODULE_${the_module}_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}" CACHE INTERNAL "")
223     if(NOT BUILD_${the_module})
224       return() # extra protection from redefinition
225     endif()
226     if((NOT OPENCV_MODULE_${the_module}_IS_PART_OF_WORLD AND NOT ${the_module} STREQUAL opencv_world) OR NOT ${BUILD_opencv_world})
227       project(${the_module})
228       add_definitions(
229         -D_USE_MATH_DEFINES  # M_PI constant in MSVS
230         -D__STDC_CONSTANT_MACROS -D__STDC_LIMIT_MACROS  # to use C libraries from C++ code (ffmpeg)
231       )
232     endif()
233   endif()
234 endmacro()
235
236 # excludes module from current configuration
237 macro(ocv_module_disable_ module)
238   set(__modname ${module})
239   if(NOT __modname MATCHES "^opencv_")
240     set(__modname opencv_${module})
241   endif()
242   list(APPEND OPENCV_MODULES_DISABLED_FORCE "${__modname}")
243   set(HAVE_${__modname} OFF CACHE INTERNAL "Module ${__modname} can not be built in current configuration")
244   set(OPENCV_MODULE_${__modname}_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}" CACHE INTERNAL "Location of ${__modname} module sources")
245   set(OPENCV_MODULES_DISABLED_FORCE "${OPENCV_MODULES_DISABLED_FORCE}" CACHE INTERNAL "List of OpenCV modules which can not be build in current configuration")
246   if(BUILD_${__modname})
247     # touch variable controlling build of the module to suppress "unused variable" CMake warning
248   endif()
249   unset(__modname)
250 endmacro()
251
252 macro(ocv_module_disable module)
253   ocv_module_disable_(${module})
254   return() # leave the current folder
255 endmacro()
256
257 # collect modules from specified directories
258 # NB: must be called only once!
259 macro(ocv_glob_modules)
260   if(DEFINED OPENCV_INITIAL_PASS)
261     message(FATAL_ERROR "OpenCV has already loaded its modules. Calling ocv_glob_modules second time is not allowed.")
262   endif()
263   set(__directories_observed "")
264
265   # collect modules
266   set(OPENCV_INITIAL_PASS ON)
267   set(OPENCV_PROCESSING_EXTRA_MODULES 0)
268   foreach(__path ${ARGN})
269     if("${__path}" STREQUAL "EXTRA")
270       set(OPENCV_PROCESSING_EXTRA_MODULES 1)
271     else()
272       get_filename_component(__path "${__path}" ABSOLUTE)
273
274       list(FIND __directories_observed "${__path}" __pathIdx)
275       if(__pathIdx GREATER -1)
276         message(FATAL_ERROR "The directory ${__path} is observed for OpenCV modules second time.")
277       endif()
278       list(APPEND __directories_observed "${__path}")
279
280       set(__count 0)
281       file(GLOB __ocvmodules RELATIVE "${__path}" "${__path}/*")
282       if(__ocvmodules)
283         list(SORT __ocvmodules)
284         foreach(mod ${__ocvmodules})
285           get_filename_component(__modpath "${__path}/${mod}" ABSOLUTE)
286           if(EXISTS "${__modpath}/CMakeLists.txt")
287
288             list(FIND __directories_observed "${__modpath}" __pathIdx)
289             if(__pathIdx GREATER -1)
290               message(FATAL_ERROR "The module from ${__modpath} is already loaded.")
291             endif()
292             list(APPEND __directories_observed "${__modpath}")
293
294             add_subdirectory("${__modpath}" "${CMAKE_CURRENT_BINARY_DIR}/${mod}/.${mod}")
295
296             if (DEFINED OPENCV_MODULE_opencv_${mod}_LOCATION)
297               math(EXPR __count "${__count} + 1")
298             endif()
299           endif()
300         endforeach()
301       endif()
302       if (OPENCV_PROCESSING_EXTRA_MODULES AND ${__count} LESS 1)
303         message(SEND_ERROR "No extra modules found in folder: ${__path}\nPlease provide path to 'opencv_contrib/modules' folder.")
304       endif()
305     endif()
306   endforeach()
307   ocv_clear_vars(__ocvmodules __directories_observed __path __modpath __pathIdx)
308
309   # resolve dependencies
310   __ocv_resolve_dependencies()
311
312   # create modules
313   set(OPENCV_INITIAL_PASS OFF PARENT_SCOPE)
314   set(OPENCV_INITIAL_PASS OFF)
315   if(${BUILD_opencv_world})
316     foreach(m ${OPENCV_MODULES_BUILD})
317       set(the_module "${m}")
318       if("${m}" STREQUAL opencv_world)
319         add_subdirectory("${OPENCV_MODULE_opencv_world_LOCATION}" "${CMAKE_CURRENT_BINARY_DIR}/world")
320       elseif(NOT OPENCV_MODULE_${m}_IS_PART_OF_WORLD AND NOT ${m} STREQUAL opencv_world)
321         message(STATUS "Processing module ${m}...")
322         if(m MATCHES "^opencv_")
323           string(REGEX REPLACE "^opencv_" "" __shortname "${m}")
324           add_subdirectory("${OPENCV_MODULE_${m}_LOCATION}" "${CMAKE_CURRENT_BINARY_DIR}/${__shortname}")
325         else()
326           message(WARNING "Check module name: ${m}")
327           add_subdirectory("${OPENCV_MODULE_${m}_LOCATION}" "${CMAKE_CURRENT_BINARY_DIR}/${m}")
328         endif()
329       endif()
330     endforeach()
331   else()
332     foreach(m ${OPENCV_MODULES_BUILD})
333       set(the_module "${m}")
334       if(m MATCHES "^opencv_")
335         string(REGEX REPLACE "^opencv_" "" __shortname "${m}")
336         add_subdirectory("${OPENCV_MODULE_${m}_LOCATION}" "${CMAKE_CURRENT_BINARY_DIR}/${__shortname}")
337       else()
338         message(WARNING "Check module name: ${m}")
339         add_subdirectory("${OPENCV_MODULE_${m}_LOCATION}" "${CMAKE_CURRENT_BINARY_DIR}/${m}")
340       endif()
341     endforeach()
342   endif()
343   unset(__shortname)
344 endmacro()
345
346
347 # disables OpenCV module with missing dependencies
348 function(__ocv_module_turn_off the_module)
349   list(REMOVE_ITEM OPENCV_MODULES_DISABLED_AUTO "${the_module}")
350   list(APPEND OPENCV_MODULES_DISABLED_AUTO "${the_module}")
351   list(REMOVE_ITEM OPENCV_MODULES_BUILD "${the_module}")
352   list(REMOVE_ITEM OPENCV_MODULES_PUBLIC "${the_module}")
353   set(HAVE_${the_module} OFF CACHE INTERNAL "Module ${the_module} can not be built in current configuration")
354
355   set(OPENCV_MODULES_DISABLED_AUTO "${OPENCV_MODULES_DISABLED_AUTO}" CACHE INTERNAL "")
356   set(OPENCV_MODULES_BUILD "${OPENCV_MODULES_BUILD}" CACHE INTERNAL "")
357   set(OPENCV_MODULES_PUBLIC "${OPENCV_MODULES_PUBLIC}" CACHE INTERNAL "")
358 endfunction()
359
360 # sort modules by dependencies
361 function(__ocv_sort_modules_by_deps __lst)
362   ocv_list_sort(${__lst})
363   set(input ${${__lst}})
364   set(result "")
365   set(result_extra "")
366   while(input)
367     list(LENGTH input length_before)
368     foreach (m ${input})
369       # check if module is in the result already
370       if (NOT ";${result};" MATCHES ";${m};")
371         # scan through module dependencies...
372         set(unresolved_deps_found FALSE)
373         foreach (d ${OPENCV_MODULE_${m}_CHILDREN} ${OPENCV_MODULE_${m}_DEPS})
374           # ... which are not already in the result and are enabled
375           if ((NOT ";${result};" MATCHES ";${d};") AND HAVE_${d})
376             set(unresolved_deps_found TRUE)
377             break()
378           endif()
379         endforeach()
380         # chek if all dependencies for this module has been resolved
381         if (NOT unresolved_deps_found)
382           list(APPEND result ${m})
383           list(REMOVE_ITEM input ${m})
384         endif()
385       endif()
386     endforeach()
387     list(LENGTH input length_after)
388     # check for infinite loop or unresolved dependencies
389     if (NOT length_after LESS length_before)
390       if(NOT BUILD_SHARED_LIBS)
391         if (";${input};" MATCHES ";opencv_world;")
392           list(REMOVE_ITEM input "opencv_world")
393           list(APPEND result_extra "opencv_world")
394         else()
395           # We can't do here something
396           list(APPEND result ${input})
397           break()
398         endif()
399       else()
400         message(FATAL_ERROR WARNING "Unresolved dependencies or loop in dependency graph (${length_after})\n"
401           "Processed ${__lst}: ${${__lst}}\n"
402           "Good modules: ${result}\n"
403           "Bad modules: ${input}"
404         )
405         list(APPEND result ${input})
406         break()
407       endif()
408     endif()
409   endwhile()
410   set(${__lst} "${result};${result_extra}" PARENT_SCOPE)
411 endfunction()
412
413 # resolve dependensies
414 function(__ocv_resolve_dependencies)
415   foreach(m ${OPENCV_MODULES_DISABLED_USER})
416     set(HAVE_${m} OFF CACHE INTERNAL "Module ${m} will not be built in current configuration")
417   endforeach()
418   foreach(m ${OPENCV_MODULES_BUILD})
419     set(HAVE_${m} ON CACHE INTERNAL "Module ${m} will be built in current configuration")
420   endforeach()
421
422   # disable MODULES with unresolved dependencies
423   set(has_changes ON)
424   while(has_changes)
425     set(has_changes OFF)
426     foreach(m ${OPENCV_MODULES_BUILD})
427       set(__deps ${OPENCV_MODULE_${m}_REQ_DEPS} ${OPENCV_MODULE_${m}_PRIVATE_REQ_DEPS})
428       while(__deps)
429         ocv_list_pop_front(__deps d)
430         string(TOLOWER "${d}" upper_d)
431         if(NOT (HAVE_${d} OR HAVE_${upper_d} OR TARGET ${d} OR EXISTS ${d}))
432           if(d MATCHES "^opencv_") # TODO Remove this condition in the future and use HAVE_ variables only
433             message(STATUS "Module ${m} disabled because ${d} dependency can't be resolved!")
434             __ocv_module_turn_off(${m})
435             set(has_changes ON)
436             break()
437           else()
438             message(STATUS "Assume that non-module dependency is available: ${d} (for module ${m})")
439           endif()
440         endif()
441       endwhile()
442     endforeach()
443   endwhile()
444
445 #  message(STATUS "List of active modules: ${OPENCV_MODULES_BUILD}")
446
447   foreach(m ${OPENCV_MODULES_BUILD})
448     set(deps_${m} ${OPENCV_MODULE_${m}_REQ_DEPS})
449     foreach(d ${OPENCV_MODULE_${m}_OPT_DEPS})
450       if(NOT (";${deps_${m}};" MATCHES ";${d};"))
451         if(HAVE_${d} OR TARGET ${d})
452           list(APPEND deps_${m} ${d})
453         endif()
454       endif()
455     endforeach()
456 #    message(STATUS "Initial deps of ${m} (w/o private deps): ${deps_${m}}")
457   endforeach()
458
459   # propagate dependencies
460   set(has_changes ON)
461   while(has_changes)
462     set(has_changes OFF)
463     foreach(m2 ${OPENCV_MODULES_BUILD}) # transfer deps of m2 to m
464       foreach(m ${OPENCV_MODULES_BUILD})
465         if((NOT m STREQUAL m2) AND ";${deps_${m}};" MATCHES ";${m2};")
466           foreach(d ${deps_${m2}})
467             if(NOT (";${deps_${m}};" MATCHES ";${d};"))
468 #              message(STATUS "  Transfer dependency ${d} from ${m2} to ${m}")
469               list(APPEND deps_${m} ${d})
470               set(has_changes ON)
471             endif()
472             if(BUILD_opencv_world
473                 AND NOT "${m}" STREQUAL "opencv_world"
474                 AND NOT "${m2}" STREQUAL "opencv_world"
475                 AND OPENCV_MODULE_${m2}_IS_PART_OF_WORLD
476                 AND NOT OPENCV_MODULE_${m}_IS_PART_OF_WORLD)
477               if(NOT (";${deps_${m}};" MATCHES ";opencv_world;"))
478 #                message(STATUS "  Transfer dependency opencv_world alias ${m2} to ${m}")
479                 list(APPEND deps_${m} opencv_world)
480                 set(has_changes ON)
481               endif()
482             endif()
483           endforeach()
484         endif()
485       endforeach()
486     endforeach()
487   endwhile()
488
489   # process private deps
490   foreach(m ${OPENCV_MODULES_BUILD})
491     foreach(d ${OPENCV_MODULE_${m}_PRIVATE_REQ_DEPS})
492       if(NOT (";${deps_${m}};" MATCHES ";${d};"))
493         list(APPEND deps_${m} ${d})
494       endif()
495     endforeach()
496     foreach(d ${OPENCV_MODULE_${m}_PRIVATE_OPT_DEPS})
497       if(NOT (";${deps_${m}};" MATCHES ";${d};"))
498         if(HAVE_${d} OR TARGET ${d})
499           list(APPEND deps_${m} ${d})
500         endif()
501       endif()
502     endforeach()
503   endforeach()
504
505   ocv_list_sort(OPENCV_MODULES_BUILD)
506
507   foreach(m ${OPENCV_MODULES_BUILD})
508 #    message(STATUS "FULL deps of ${m}: ${deps_${m}}")
509     set(OPENCV_MODULE_${m}_DEPS ${deps_${m}})
510     set(OPENCV_MODULE_${m}_DEPS_EXT ${deps_${m}})
511     ocv_list_filterout(OPENCV_MODULE_${m}_DEPS_EXT "^opencv_[^ ]+$")
512     if(OPENCV_MODULE_${m}_DEPS_EXT AND OPENCV_MODULE_${m}_DEPS)
513       list(REMOVE_ITEM OPENCV_MODULE_${m}_DEPS ${OPENCV_MODULE_${m}_DEPS_EXT})
514     endif()
515   endforeach()
516
517   # reorder dependencies
518   foreach(m ${OPENCV_MODULES_BUILD})
519     __ocv_sort_modules_by_deps(OPENCV_MODULE_${m}_DEPS)
520
521     set(LINK_DEPS ${OPENCV_MODULE_${m}_DEPS})
522
523     # process world
524     if(BUILD_opencv_world)
525       if(OPENCV_MODULE_${m}_IS_PART_OF_WORLD)
526         list(APPEND OPENCV_WORLD_MODULES ${m})
527       endif()
528       foreach(m2 ${OPENCV_MODULES_BUILD})
529         if(OPENCV_MODULE_${m2}_IS_PART_OF_WORLD)
530           if(";${LINK_DEPS};" MATCHES ";${m2};")
531             list(REMOVE_ITEM LINK_DEPS ${m2})
532             if(NOT (";${LINK_DEPS};" MATCHES ";opencv_world;") AND NOT (${m} STREQUAL opencv_world))
533               list(APPEND LINK_DEPS opencv_world)
534             endif()
535           endif()
536           if(${m} STREQUAL opencv_world)
537             list(APPEND OPENCV_MODULE_opencv_world_DEPS_EXT ${OPENCV_MODULE_${m2}_DEPS_EXT})
538           endif()
539         endif()
540       endforeach()
541     endif()
542
543     set(OPENCV_MODULE_${m}_DEPS ${OPENCV_MODULE_${m}_DEPS} CACHE INTERNAL "Flattened dependencies of ${m} module")
544     set(OPENCV_MODULE_${m}_DEPS_EXT ${OPENCV_MODULE_${m}_DEPS_EXT} CACHE INTERNAL "Extra dependencies of ${m} module")
545     set(OPENCV_MODULE_${m}_DEPS_TO_LINK ${LINK_DEPS} CACHE INTERNAL "Flattened dependencies of ${m} module (for linker)")
546
547 #    message(STATUS "  module deps of ${m}: ${OPENCV_MODULE_${m}_DEPS}")
548 #    message(STATUS "  module link deps of ${m}: ${OPENCV_MODULE_${m}_DEPS_TO_LINK}")
549 #    message(STATUS "  extra deps of ${m}: ${OPENCV_MODULE_${m}_DEPS_EXT}")
550 #    message(STATUS "")
551   endforeach()
552
553   __ocv_sort_modules_by_deps(OPENCV_MODULES_BUILD)
554
555   set(OPENCV_MODULES_PUBLIC        ${OPENCV_MODULES_PUBLIC}        CACHE INTERNAL "List of OpenCV modules marked for export")
556   set(OPENCV_MODULES_BUILD         ${OPENCV_MODULES_BUILD}         CACHE INTERNAL "List of OpenCV modules included into the build")
557   set(OPENCV_MODULES_DISABLED_AUTO ${OPENCV_MODULES_DISABLED_AUTO} CACHE INTERNAL "List of OpenCV modules implicitly disabled due to dependencies")
558   set(OPENCV_WORLD_MODULES         ${OPENCV_WORLD_MODULES}         CACHE INTERNAL "List of OpenCV modules included into the world")
559 endfunction()
560
561
562 # setup include paths for the list of passed modules
563 macro(ocv_include_modules)
564   foreach(d ${ARGN})
565     if(d MATCHES "^opencv_" AND HAVE_${d})
566       if (EXISTS "${OPENCV_MODULE_${d}_LOCATION}/include")
567         ocv_include_directories("${OPENCV_MODULE_${d}_LOCATION}/include")
568       endif()
569     elseif(EXISTS "${d}")
570       ocv_include_directories("${d}")
571     endif()
572   endforeach()
573 endmacro()
574
575 # same as previous but with dependencies
576 macro(ocv_include_modules_recurse)
577   ocv_include_modules(${ARGN})
578   foreach(d ${ARGN})
579     if(d MATCHES "^opencv_" AND HAVE_${d} AND DEFINED OPENCV_MODULE_${d}_DEPS)
580       foreach (sub ${OPENCV_MODULE_${d}_DEPS})
581         ocv_include_modules(${sub})
582       endforeach()
583     endif()
584   endforeach()
585 endmacro()
586
587 # setup include paths for the list of passed modules
588 macro(ocv_target_include_modules target)
589   foreach(d ${ARGN})
590     if(d MATCHES "^opencv_" AND HAVE_${d})
591       if (EXISTS "${OPENCV_MODULE_${d}_LOCATION}/include")
592         ocv_target_include_directories(${target} "${OPENCV_MODULE_${d}_LOCATION}/include")
593       endif()
594     elseif(EXISTS "${d}")
595       ocv_target_include_directories(${target} "${d}")
596     endif()
597   endforeach()
598 endmacro()
599
600 # setup include paths for the list of passed modules and recursively add dependent modules
601 macro(ocv_target_include_modules_recurse target)
602   foreach(d ${ARGN})
603     if(d MATCHES "^opencv_" AND HAVE_${d})
604       if (EXISTS "${OPENCV_MODULE_${d}_LOCATION}/include")
605         ocv_target_include_directories(${target} "${OPENCV_MODULE_${d}_LOCATION}/include")
606       endif()
607       if(OPENCV_MODULE_${d}_DEPS)
608         ocv_target_include_modules(${target} ${OPENCV_MODULE_${d}_DEPS})
609       endif()
610     elseif(EXISTS "${d}")
611       ocv_target_include_directories(${target} "${d}")
612     endif()
613   endforeach()
614 endmacro()
615
616 # setup include path for OpenCV headers for specified module
617 # ocv_module_include_directories(<extra include directories/extra include modules>)
618 macro(ocv_module_include_directories)
619   ocv_target_include_directories(${the_module}
620       "${OPENCV_MODULE_${the_module}_LOCATION}/include"
621       "${OPENCV_MODULE_${the_module}_LOCATION}/src"
622       "${CMAKE_CURRENT_BINARY_DIR}" # for precompiled headers
623       )
624   ocv_target_include_modules(${the_module} ${OPENCV_MODULE_${the_module}_DEPS} ${ARGN})
625 endmacro()
626
627
628 # sets header and source files for the current module
629 # NB: all files specified as headers will be installed
630 # Usage:
631 # ocv_set_module_sources([HEADERS] <list of files> [SOURCES] <list of files>)
632 macro(ocv_set_module_sources)
633   ocv_debug_message("ocv_set_module_sources(" ${ARGN} ")")
634
635   set(OPENCV_MODULE_${the_module}_HEADERS "")
636   set(OPENCV_MODULE_${the_module}_SOURCES "")
637
638   foreach(f "HEADERS" ${ARGN})
639     if(f STREQUAL "HEADERS" OR f STREQUAL "SOURCES")
640       set(__filesvar "OPENCV_MODULE_${the_module}_${f}")
641     else()
642       list(APPEND ${__filesvar} "${f}")
643     endif()
644   endforeach()
645
646   # the hacky way to embeed any files into the OpenCV without modification of its build system
647   if(COMMAND ocv_get_module_external_sources)
648     ocv_get_module_external_sources()
649   endif()
650
651   if(OPENCV_MODULE_${the_module}_SOURCES_DISPATCHED)
652     list(APPEND OPENCV_MODULE_${the_module}_SOURCES ${OPENCV_MODULE_${the_module}_SOURCES_DISPATCHED})
653   endif()
654
655   # use full paths for module to be independent from the module location
656   ocv_convert_to_full_paths(OPENCV_MODULE_${the_module}_HEADERS)
657
658   set(OPENCV_MODULE_${the_module}_HEADERS ${OPENCV_MODULE_${the_module}_HEADERS} CACHE INTERNAL "List of header files for ${the_module}")
659   set(OPENCV_MODULE_${the_module}_SOURCES ${OPENCV_MODULE_${the_module}_SOURCES} CACHE INTERNAL "List of source files for ${the_module}")
660 endmacro()
661
662 # finds and sets headers and sources for the standard OpenCV module
663 # Usage:
664 # ocv_glob_module_sources([EXCLUDE_CUDA] <extra sources&headers in the same format as used in ocv_set_module_sources>)
665 macro(ocv_glob_module_sources)
666   ocv_debug_message("ocv_glob_module_sources(" ${ARGN} ")")
667   set(_argn ${ARGN})
668   list(FIND _argn "EXCLUDE_CUDA" exclude_cuda)
669   if(NOT exclude_cuda EQUAL -1)
670     list(REMOVE_AT _argn ${exclude_cuda})
671   endif()
672
673   file(GLOB_RECURSE lib_srcs
674        "${CMAKE_CURRENT_LIST_DIR}/src/*.cpp"
675   )
676   file(GLOB_RECURSE lib_int_hdrs
677        "${CMAKE_CURRENT_LIST_DIR}/src/*.hpp"
678        "${CMAKE_CURRENT_LIST_DIR}/src/*.h"
679   )
680   file(GLOB lib_hdrs
681        "${CMAKE_CURRENT_LIST_DIR}/include/opencv2/*.hpp"
682        "${CMAKE_CURRENT_LIST_DIR}/include/opencv2/${name}/*.hpp"
683        "${CMAKE_CURRENT_LIST_DIR}/include/opencv2/${name}/*.h"
684        "${CMAKE_CURRENT_LIST_DIR}/include/opencv2/${name}/hal/*.hpp"
685        "${CMAKE_CURRENT_LIST_DIR}/include/opencv2/${name}/hal/*.h"
686        "${CMAKE_CURRENT_LIST_DIR}/include/opencv2/${name}/utils/*.hpp"
687        "${CMAKE_CURRENT_LIST_DIR}/include/opencv2/${name}/utils/*.h"
688   )
689   file(GLOB lib_hdrs_detail
690        "${CMAKE_CURRENT_LIST_DIR}/include/opencv2/${name}/detail/*.hpp"
691        "${CMAKE_CURRENT_LIST_DIR}/include/opencv2/${name}/detail/*.h"
692   )
693   if (APPLE)
694     file(GLOB_RECURSE lib_srcs_apple
695          "${CMAKE_CURRENT_LIST_DIR}/src/*.mm"
696     )
697     list(APPEND lib_srcs ${lib_srcs_apple})
698   endif()
699
700   ocv_source_group("Src" DIRBASE "${CMAKE_CURRENT_LIST_DIR}/src" FILES ${lib_srcs} ${lib_int_hdrs})
701   ocv_source_group("Include" DIRBASE "${CMAKE_CURRENT_LIST_DIR}/include" FILES ${lib_hdrs} ${lib_hdrs_detail})
702
703   set(lib_cuda_srcs "")
704   set(lib_cuda_hdrs "")
705   if(HAVE_CUDA AND exclude_cuda EQUAL -1)
706     file(GLOB lib_cuda_srcs
707          "${CMAKE_CURRENT_LIST_DIR}/src/cuda/*.cu"
708     )
709     file(GLOB lib_cuda_hdrs
710          "${CMAKE_CURRENT_LIST_DIR}/src/cuda/*.hpp"
711     )
712     source_group("Src\\Cuda"      FILES ${lib_cuda_srcs} ${lib_cuda_hdrs})
713   endif()
714
715   file(GLOB cl_kernels
716        "${CMAKE_CURRENT_LIST_DIR}/src/opencl/*.cl"
717   )
718   if(cl_kernels)
719     set(OCL_NAME opencl_kernels_${name})
720     add_custom_command(
721       OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${OCL_NAME}.cpp" "${CMAKE_CURRENT_BINARY_DIR}/${OCL_NAME}.hpp"
722       COMMAND ${CMAKE_COMMAND} "-DMODULE_NAME=${name}" "-DCL_DIR=${CMAKE_CURRENT_LIST_DIR}/src/opencl" "-DOUTPUT=${CMAKE_CURRENT_BINARY_DIR}/${OCL_NAME}.cpp" -P "${OpenCV_SOURCE_DIR}/cmake/cl2cpp.cmake"
723       DEPENDS ${cl_kernels} "${OpenCV_SOURCE_DIR}/cmake/cl2cpp.cmake")
724     ocv_source_group("Src\\opencl\\kernels" FILES ${cl_kernels})
725     ocv_source_group("Src\\opencl\\kernels\\autogenerated" FILES "${CMAKE_CURRENT_BINARY_DIR}/${OCL_NAME}.cpp" "${CMAKE_CURRENT_BINARY_DIR}/${OCL_NAME}.hpp")
726     list(APPEND lib_srcs ${cl_kernels} "${CMAKE_CURRENT_BINARY_DIR}/${OCL_NAME}.cpp" "${CMAKE_CURRENT_BINARY_DIR}/${OCL_NAME}.hpp")
727   endif()
728
729   ocv_set_module_sources(${_argn} HEADERS ${lib_hdrs} ${lib_hdrs_detail}
730                          SOURCES ${lib_srcs} ${lib_int_hdrs} ${lib_cuda_srcs} ${lib_cuda_hdrs})
731 endmacro()
732
733 # creates OpenCV module in current folder
734 # creates new target, configures standard dependencies, compilers flags, install rules
735 # Usage:
736 #   ocv_create_module(<extra link dependencies>)
737 #   ocv_create_module()
738 macro(ocv_create_module)
739   ocv_debug_message("${the_module}: ocv_create_module(" ${ARGN} ")")
740   if(NOT " ${ARGN}" STREQUAL " ")
741     set(OPENCV_MODULE_${the_module}_LINK_DEPS "${OPENCV_MODULE_${the_module}_LINK_DEPS};${ARGN}" CACHE INTERNAL "")
742   endif()
743   if(${BUILD_opencv_world} AND OPENCV_MODULE_${the_module}_IS_PART_OF_WORLD)
744     # nothing
745     set(the_module_target opencv_world)
746   else()
747     _ocv_create_module(${ARGN})
748     set(the_module_target ${the_module})
749   endif()
750
751   if(WINRT)
752     # removing APPCONTAINER from modules to run from console
753     # in case of usual starting of WinRT test apps output is missing
754     # so starting of console version w/o APPCONTAINER is required to get test results
755     # also this allows to use opencv_extra test data for these tests
756     if(NOT "${the_module}" STREQUAL "opencv_ts" AND NOT "${the_module}" STREQUAL "opencv_hal")
757       add_custom_command(TARGET ${the_module}
758                          POST_BUILD
759                          COMMAND link.exe /edit /APPCONTAINER:NO $(TargetPath))
760     endif()
761
762     if("${the_module}" STREQUAL "opencv_ts")
763       # copy required dll files; WinRT apps need these dlls that are usually substituted by Visual Studio
764       # however they are not on path and need to be placed with executables to run from console w/o APPCONTAINER
765       add_custom_command(TARGET ${the_module}
766         POST_BUILD
767         COMMAND copy /y "\"$(VCInstallDir)redist\\$(PlatformTarget)\\Microsoft.VC$(PlatformToolsetVersion).CRT\\msvcp$(PlatformToolsetVersion).dll\"" "\"${CMAKE_BINARY_DIR}\\bin\\$(Configuration)\\msvcp$(PlatformToolsetVersion)_app.dll\""
768         COMMAND copy /y "\"$(VCInstallDir)redist\\$(PlatformTarget)\\Microsoft.VC$(PlatformToolsetVersion).CRT\\msvcr$(PlatformToolsetVersion).dll\"" "\"${CMAKE_BINARY_DIR}\\bin\\$(Configuration)\\msvcr$(PlatformToolsetVersion)_app.dll\""
769         COMMAND copy /y "\"$(VCInstallDir)redist\\$(PlatformTarget)\\Microsoft.VC$(PlatformToolsetVersion).CRT\\vccorlib$(PlatformToolsetVersion).dll\"" "\"${CMAKE_BINARY_DIR}\\bin\\$(Configuration)\\vccorlib$(PlatformToolsetVersion)_app.dll\"")
770     endif()
771   endif()
772 endmacro()
773
774 macro(_ocv_create_module)
775
776   ocv_compiler_optimization_process_sources(OPENCV_MODULE_${the_module}_SOURCES OPENCV_MODULE_${the_module}_DEPS_EXT ${the_module})
777   set(OPENCV_MODULE_${the_module}_HEADERS ${OPENCV_MODULE_${the_module}_HEADERS} CACHE INTERNAL "List of header files for ${the_module}")
778   set(OPENCV_MODULE_${the_module}_SOURCES ${OPENCV_MODULE_${the_module}_SOURCES} CACHE INTERNAL "List of source files for ${the_module}")
779
780   # The condition we ought to be testing here is whether ocv_add_precompiled_headers will
781   # be called at some point in the future. We can't look into the future, though,
782   # so this will have to do.
783   if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/src/precomp.hpp" AND NOT ${the_module} STREQUAL opencv_world)
784     get_native_precompiled_header(${the_module} precomp.hpp)
785   endif()
786
787   set(sub_objs "")
788   set(sub_links "")
789   set(cuda_objs "")
790   if (OPENCV_MODULE_${the_module}_CHILDREN)
791     message(STATUS "Complex module ${the_module}")
792     foreach (m ${OPENCV_MODULE_${the_module}_CHILDREN})
793       if (BUILD_${m} AND TARGET ${m}_object)
794         get_target_property(_sub_links ${m} LINK_LIBRARIES)
795         list(APPEND sub_objs $<TARGET_OBJECTS:${m}_object>)
796         list(APPEND sub_links ${_sub_links})
797         message(STATUS "    + ${m}")
798       else()
799         message(STATUS "    - ${m}")
800       endif()
801       list(APPEND cuda_objs ${OPENCV_MODULE_${m}_CUDA_OBJECTS})
802     endforeach()
803   endif()
804
805   if(WIN32 AND BUILD_SHARED_LIBS AND NOT OPENCV_VS_VERSIONINFO_SKIP)
806     if(DEFINED OPENCV_VS_VERSIONINFO_FILE)
807       set(_VS_VERSION_FILE "${OPENCV_VS_VERSIONINFO_FILE}")
808     elseif(DEFINED OPENCV_VS_VERSIONINFO_${the_module}_FILE)
809       set(_VS_VERSION_FILE "${OPENCV_VS_VERSIONINFO_${the_module}_FILE}")
810     elseif(NOT OPENCV_VS_VERSIONINFO_SKIP_GENERATION)
811       set(_VS_VERSION_FILE "${CMAKE_CURRENT_BINARY_DIR}/vs_version.rc")
812       ocv_generate_vs_version_file("${_VS_VERSION_FILE}"
813         NAME "${the_module}"
814         FILEDESCRIPTION "OpenCV module: ${OPENCV_MODULE_${the_module}_DESCRIPTION}"
815         INTERNALNAME "${the_module}${OPENCV_DLLVERSION}"
816         ORIGINALFILENAME "${the_module}${OPENCV_DLLVERSION}.dll"
817       )
818     endif()
819     if(_VS_VERSION_FILE)
820       if(NOT EXISTS "${_VS_VERSION_FILE}")
821         message(STATUS "${the_module}: Required .rc file is missing: ${_VS_VERSION_FILE}")
822       endif()
823       source_group("Src" FILES "${_VS_VERSION_FILE}")
824     endif()
825   endif()
826
827   source_group("Include" FILES "${OPENCV_CONFIG_FILE_INCLUDE_DIR}/cvconfig.h" "${OPENCV_CONFIG_FILE_INCLUDE_DIR}/opencv2/opencv_modules.hpp")
828   source_group("Src" FILES "${${the_module}_pch}")
829   ocv_add_library(${the_module} ${OPENCV_MODULE_TYPE} ${OPENCV_MODULE_${the_module}_HEADERS} ${OPENCV_MODULE_${the_module}_SOURCES}
830     "${OPENCV_CONFIG_FILE_INCLUDE_DIR}/cvconfig.h" "${OPENCV_CONFIG_FILE_INCLUDE_DIR}/opencv2/opencv_modules.hpp"
831     ${${the_module}_pch} ${sub_objs}
832     ${_VS_VERSION_FILE}
833   )
834
835   if (cuda_objs)
836     target_link_libraries(${the_module} ${cuda_objs})
837   endif()
838
839   # TODO: is it needed?
840   if (sub_links)
841     ocv_list_filterout(sub_links "^opencv_")
842     ocv_list_unique(sub_links)
843     target_link_libraries(${the_module} ${sub_links})
844   endif()
845
846   unset(sub_objs)
847   unset(sub_links)
848   unset(cuda_objs)
849
850   set_target_properties(${the_module} PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};Module")
851   set_source_files_properties(${OPENCV_MODULE_${the_module}_HEADERS} ${OPENCV_MODULE_${the_module}_SOURCES} ${${the_module}_pch}
852     PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};Module")
853
854   if(NOT BUILD_SHARED_LIBS OR NOT INSTALL_CREATE_DISTRIB)
855     ocv_target_link_libraries(${the_module} ${OPENCV_MODULE_${the_module}_DEPS_TO_LINK})
856     ocv_target_link_libraries(${the_module} LINK_INTERFACE_LIBRARIES ${OPENCV_MODULE_${the_module}_DEPS_TO_LINK})
857     ocv_target_link_libraries(${the_module} ${OPENCV_MODULE_${the_module}_DEPS_EXT} ${OPENCV_LINKER_LIBS} ${IPP_LIBS} ${ARGN})
858     if (HAVE_CUDA)
859       ocv_target_link_libraries(${the_module} ${CUDA_LIBRARIES} ${CUDA_npp_LIBRARY})
860     endif()
861   else()
862     ocv_target_link_libraries(${the_module} LINK_PRIVATE ${OPENCV_MODULE_${the_module}_DEPS_TO_LINK})
863     ocv_target_link_libraries(${the_module} LINK_PRIVATE ${OPENCV_MODULE_${the_module}_DEPS_TO_LINK})
864     ocv_target_link_libraries(${the_module} LINK_PRIVATE ${OPENCV_MODULE_${the_module}_DEPS_EXT} ${OPENCV_LINKER_LIBS} ${IPP_LIBS} ${ARGN})
865     if (HAVE_CUDA)
866       ocv_target_link_libraries(${the_module} LINK_PRIVATE ${CUDA_LIBRARIES} ${CUDA_npp_LIBRARY})
867     endif()
868   endif()
869
870   add_dependencies(opencv_modules ${the_module})
871
872   if(ENABLE_SOLUTION_FOLDERS)
873     set_target_properties(${the_module} PROPERTIES FOLDER "modules")
874   endif()
875
876   set_target_properties(${the_module} PROPERTIES
877     OUTPUT_NAME "${the_module}${OPENCV_DLLVERSION}"
878     DEBUG_POSTFIX "${OPENCV_DEBUG_POSTFIX}"
879     COMPILE_PDB_NAME "${the_module}${OPENCV_DLLVERSION}"
880     COMPILE_PDB_NAME_DEBUG "${the_module}${OPENCV_DLLVERSION}${OPENCV_DEBUG_POSTFIX}"
881     ARCHIVE_OUTPUT_DIRECTORY ${LIBRARY_OUTPUT_PATH}
882     COMPILE_PDB_OUTPUT_DIRECTORY ${LIBRARY_OUTPUT_PATH}
883     LIBRARY_OUTPUT_DIRECTORY ${LIBRARY_OUTPUT_PATH}
884     RUNTIME_OUTPUT_DIRECTORY ${EXECUTABLE_OUTPUT_PATH}
885   )
886
887   # For dynamic link numbering convenions
888   if(NOT ANDROID)
889     # Android SDK build scripts can include only .so files into final .apk
890     # As result we should not set version properties for Android
891     set_target_properties(${the_module} PROPERTIES
892       VERSION ${OPENCV_LIBVERSION}
893       SOVERSION ${OPENCV_SOVERSION}
894     )
895   endif()
896
897   if((NOT DEFINED OPENCV_MODULE_TYPE AND BUILD_SHARED_LIBS)
898       OR (DEFINED OPENCV_MODULE_TYPE AND OPENCV_MODULE_TYPE STREQUAL SHARED))
899     set_target_properties(${the_module} PROPERTIES DEFINE_SYMBOL CVAPI_EXPORTS)
900   endif()
901
902   if (ENABLE_GNU_STL_DEBUG)
903     target_compile_definitions(${the_module} PUBLIC _GLIBCXX_DEBUG)
904   endif()
905
906   if(MSVC)
907     if(CMAKE_CROSSCOMPILING)
908       set_target_properties(${the_module} PROPERTIES LINK_FLAGS "/NODEFAULTLIB:secchk")
909     endif()
910     set_target_properties(${the_module} PROPERTIES LINK_FLAGS "/NODEFAULTLIB:libc /DEBUG")
911   endif()
912
913   get_target_property(_target_type ${the_module} TYPE)
914   if(OPENCV_MODULE_${the_module}_CLASS STREQUAL "PUBLIC" AND
915       ("${_target_type}" STREQUAL "SHARED_LIBRARY" OR (NOT BUILD_SHARED_LIBS OR NOT INSTALL_CREATE_DISTRIB)))
916     ocv_install_target(${the_module} EXPORT OpenCVModules OPTIONAL
917       RUNTIME DESTINATION ${OPENCV_BIN_INSTALL_PATH} COMPONENT libs
918       LIBRARY DESTINATION ${OPENCV_LIB_INSTALL_PATH} COMPONENT libs NAMELINK_SKIP
919       ARCHIVE DESTINATION ${OPENCV_LIB_INSTALL_PATH} COMPONENT dev
920       )
921   endif()
922   if("${_target_type}" STREQUAL "SHARED_LIBRARY")
923     install(TARGETS ${the_module}
924       LIBRARY DESTINATION ${OPENCV_LIB_INSTALL_PATH} COMPONENT dev NAMELINK_ONLY)
925   endif()
926
927   foreach(m ${OPENCV_MODULE_${the_module}_CHILDREN} ${the_module})
928     # only "public" headers need to be installed
929     if(OPENCV_MODULE_${m}_HEADERS AND ";${OPENCV_MODULES_PUBLIC};" MATCHES ";${m};")
930       foreach(hdr ${OPENCV_MODULE_${m}_HEADERS})
931         string(REGEX REPLACE "^.*opencv2/" "opencv2/" hdr2 "${hdr}")
932         if(NOT hdr2 MATCHES "private" AND hdr2 MATCHES "^(opencv2/?.*)/[^/]+.h(..)?$" )
933           install(FILES ${hdr} OPTIONAL DESTINATION "${OPENCV_INCLUDE_INSTALL_PATH}/${CMAKE_MATCH_1}" COMPONENT dev)
934         endif()
935       endforeach()
936     endif()
937   endforeach()
938
939   _ocv_add_precompiled_headers(${the_module})
940
941   if (TARGET ${the_module}_object)
942     # copy COMPILE_DEFINITIONS
943     get_target_property(main_defs ${the_module} COMPILE_DEFINITIONS)
944     if (main_defs)
945       set_target_properties(${the_module}_object PROPERTIES COMPILE_DEFINITIONS ${main_defs})
946     endif()
947     # use same PCH
948     if (TARGET pch_Generate_${the_module})
949       add_dependencies(${the_module}_object pch_Generate_${the_module} )
950     endif()
951   endif()
952 endmacro()
953
954 # opencv precompiled headers macro (can add pch to modules and tests)
955 # this macro must be called after any "add_definitions" commands, otherwise precompiled headers will not work
956 # Usage:
957 # ocv_add_precompiled_headers(${the_module})
958 macro(_ocv_add_precompiled_headers the_target)
959   ocv_debug_message("ocv_add_precompiled_headers(" ${the_target} ${ARGN} ")")
960
961   if("${the_target}" MATCHES "^opencv_test_.*$")
962     SET(pch_path "test/test_")
963   elseif("${the_target}" MATCHES "^opencv_perf_.*$")
964     SET(pch_path "perf/perf_")
965   else()
966     SET(pch_path "src/")
967   endif()
968   ocv_add_precompiled_header_to_target(${the_target} "${CMAKE_CURRENT_SOURCE_DIR}/${pch_path}precomp.hpp")
969   unset(pch_path)
970 endmacro()
971
972 # short command for adding simple OpenCV module
973 # see ocv_add_module for argument details
974 # Usage:
975 # ocv_define_module(module_name  [INTERNAL] [EXCLUDE_CUDA] [REQUIRED] [<list of dependencies>] [OPTIONAL <list of optional dependencies>] [WRAP <list of wrappers>])
976 macro(ocv_define_module module_name)
977   ocv_debug_message("ocv_define_module(" ${module_name} ${ARGN} ")")
978   set(_argn ${ARGN})
979   set(exclude_cuda "")
980   foreach(arg ${_argn})
981     if("${arg}" STREQUAL "EXCLUDE_CUDA")
982       set(exclude_cuda "${arg}")
983       list(REMOVE_ITEM _argn ${arg})
984     endif()
985   endforeach()
986
987   ocv_add_module(${module_name} ${_argn})
988   ocv_glob_module_sources(${exclude_cuda})
989   ocv_module_include_directories()
990   ocv_create_module()
991
992   ocv_add_accuracy_tests()
993   ocv_add_perf_tests()
994   ocv_add_samples()
995 endmacro()
996
997 # ensures that all passed modules are available
998 # sets OCV_DEPENDENCIES_FOUND variable to TRUE/FALSE
999 macro(ocv_check_dependencies)
1000   set(OCV_DEPENDENCIES_FOUND TRUE)
1001   foreach(d ${ARGN})
1002     if(d MATCHES "^opencv_[^ ]+$" AND NOT HAVE_${d})
1003       set(OCV_DEPENDENCIES_FOUND FALSE)
1004       break()
1005     endif()
1006   endforeach()
1007 endmacro()
1008
1009 # auxiliary macro to parse arguments of ocv_add_accuracy_tests and ocv_add_perf_tests commands
1010 macro(__ocv_parse_test_sources tests_type)
1011   set(OPENCV_${tests_type}_${the_module}_SOURCES "")
1012   set(OPENCV_${tests_type}_${the_module}_DEPS "")
1013   set(__file_group_name "")
1014   set(__file_group_sources "")
1015   foreach(arg "DEPENDS_ON" ${ARGN} "FILES")
1016     if(arg STREQUAL "FILES")
1017       set(__currentvar "__file_group_sources")
1018       if(__file_group_name AND __file_group_sources)
1019         source_group("${__file_group_name}" FILES ${__file_group_sources})
1020         list(APPEND OPENCV_${tests_type}_${the_module}_SOURCES ${__file_group_sources})
1021       endif()
1022       set(__file_group_name "")
1023       set(__file_group_sources "")
1024     elseif(arg STREQUAL "DEPENDS_ON")
1025       set(__currentvar "OPENCV_${tests_type}_${the_module}_DEPS")
1026     elseif(" ${__currentvar}" STREQUAL " __file_group_sources" AND NOT __file_group_name) # spaces to avoid CMP0054
1027       set(__file_group_name "${arg}")
1028     else()
1029       list(APPEND ${__currentvar} "${arg}")
1030     endif()
1031   endforeach()
1032   unset(__file_group_name)
1033   unset(__file_group_sources)
1034   unset(__currentvar)
1035 endmacro()
1036
1037 # this is a command for adding OpenCV performance tests to the module
1038 # ocv_add_perf_tests(<extra_dependencies>)
1039 function(ocv_add_perf_tests)
1040   ocv_debug_message("ocv_add_perf_tests(" ${ARGN} ")")
1041
1042   if(WINRT)
1043     set(OPENCV_DEBUG_POSTFIX "")
1044   endif()
1045
1046   set(perf_path "${CMAKE_CURRENT_LIST_DIR}/perf")
1047   if(BUILD_PERF_TESTS AND EXISTS "${perf_path}")
1048     __ocv_parse_test_sources(PERF ${ARGN})
1049
1050     # opencv_imgcodecs is required for imread/imwrite
1051     set(perf_deps opencv_ts ${the_module} opencv_imgcodecs ${OPENCV_MODULE_${the_module}_DEPS} ${OPENCV_MODULE_opencv_ts_DEPS})
1052     ocv_check_dependencies(${perf_deps})
1053
1054     if(OCV_DEPENDENCIES_FOUND)
1055       set(the_target "opencv_perf_${name}")
1056       # project(${the_target})
1057
1058       if(NOT OPENCV_PERF_${the_module}_SOURCES)
1059         file(GLOB_RECURSE perf_srcs "${perf_path}/*.cpp")
1060         file(GLOB_RECURSE perf_hdrs "${perf_path}/*.hpp" "${perf_path}/*.h")
1061         ocv_source_group("Src" DIRBASE "${perf_path}" FILES ${perf_srcs})
1062         ocv_source_group("Include" DIRBASE "${perf_path}" FILES ${perf_hdrs})
1063         set(OPENCV_PERF_${the_module}_SOURCES ${perf_srcs} ${perf_hdrs})
1064       endif()
1065
1066       if(NOT BUILD_opencv_world)
1067         get_native_precompiled_header(${the_target} perf_precomp.hpp)
1068       endif()
1069
1070       source_group("Src" FILES "${${the_target}_pch}")
1071       ocv_add_executable(${the_target} ${OPENCV_PERF_${the_module}_SOURCES} ${${the_target}_pch})
1072       ocv_target_include_modules(${the_target} ${perf_deps} "${perf_path}")
1073       ocv_target_link_libraries(${the_target} ${perf_deps} ${OPENCV_MODULE_${the_module}_DEPS} ${OPENCV_LINKER_LIBS})
1074       add_dependencies(opencv_perf_tests ${the_target})
1075
1076       set_target_properties(${the_target} PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};PerfTest")
1077       set_source_files_properties(${OPENCV_PERF_${the_module}_SOURCES} ${${the_target}_pch}
1078         PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};PerfTest")
1079
1080       # Additional target properties
1081       set_target_properties(${the_target} PROPERTIES
1082         DEBUG_POSTFIX "${OPENCV_DEBUG_POSTFIX}"
1083         RUNTIME_OUTPUT_DIRECTORY "${EXECUTABLE_OUTPUT_PATH}"
1084       )
1085       if(ENABLE_SOLUTION_FOLDERS)
1086         set_target_properties(${the_target} PROPERTIES FOLDER "tests performance")
1087       endif()
1088
1089       if(WINRT)
1090         # removing APPCONTAINER from tests to run from console
1091         # look for detailed description inside of ocv_create_module macro above
1092         add_custom_command(TARGET "opencv_perf_${name}"
1093                            POST_BUILD
1094                            COMMAND link.exe /edit /APPCONTAINER:NO $(TargetPath))
1095       endif()
1096
1097       if(NOT BUILD_opencv_world)
1098         _ocv_add_precompiled_headers(${the_target})
1099       endif()
1100
1101       ocv_add_test_from_target("${the_target}" "Performance" "${the_target}")
1102       ocv_add_test_from_target("opencv_sanity_${name}" "Sanity" "${the_target}"
1103                                "--perf_min_samples=1"
1104                                "--perf_force_samples=1"
1105                                "--perf_verify_sanity")
1106     else(OCV_DEPENDENCIES_FOUND)
1107       # TODO: warn about unsatisfied dependencies
1108     endif(OCV_DEPENDENCIES_FOUND)
1109     if(INSTALL_TESTS)
1110       install(TARGETS ${the_target} RUNTIME DESTINATION ${OPENCV_TEST_INSTALL_PATH} COMPONENT tests)
1111     endif()
1112   endif()
1113 endfunction()
1114
1115 # this is a command for adding OpenCV accuracy/regression tests to the module
1116 # ocv_add_accuracy_tests([FILES <source group name> <list of sources>] [DEPENDS_ON] <list of extra dependencies>)
1117 function(ocv_add_accuracy_tests)
1118   ocv_debug_message("ocv_add_accuracy_tests(" ${ARGN} ")")
1119
1120   if(WINRT)
1121     set(OPENCV_DEBUG_POSTFIX "")
1122   endif()
1123
1124   set(test_path "${CMAKE_CURRENT_LIST_DIR}/test")
1125   if(BUILD_TESTS AND EXISTS "${test_path}")
1126     __ocv_parse_test_sources(TEST ${ARGN})
1127
1128     # opencv_imgcodecs is required for imread/imwrite
1129     set(test_deps opencv_ts ${the_module} opencv_imgcodecs opencv_videoio ${OPENCV_MODULE_${the_module}_DEPS} ${OPENCV_MODULE_opencv_ts_DEPS})
1130     ocv_check_dependencies(${test_deps})
1131     if(OCV_DEPENDENCIES_FOUND)
1132       set(the_target "opencv_test_${name}")
1133       # project(${the_target})
1134
1135       if(NOT OPENCV_TEST_${the_module}_SOURCES)
1136         file(GLOB_RECURSE test_srcs "${test_path}/*.cpp")
1137         file(GLOB_RECURSE test_hdrs "${test_path}/*.hpp" "${test_path}/*.h")
1138         ocv_source_group("Src" DIRBASE "${test_path}" FILES ${test_srcs})
1139         ocv_source_group("Include" DIRBASE "${test_path}" FILES ${test_hdrs})
1140         set(OPENCV_TEST_${the_module}_SOURCES ${test_srcs} ${test_hdrs})
1141       endif()
1142
1143       if(NOT BUILD_opencv_world)
1144         get_native_precompiled_header(${the_target} test_precomp.hpp)
1145       endif()
1146
1147       source_group("Src" FILES "${${the_target}_pch}")
1148       ocv_add_executable(${the_target} ${OPENCV_TEST_${the_module}_SOURCES} ${${the_target}_pch})
1149       ocv_target_include_modules(${the_target} ${test_deps} "${test_path}")
1150       ocv_target_link_libraries(${the_target} ${test_deps} ${OPENCV_MODULE_${the_module}_DEPS} ${OPENCV_LINKER_LIBS})
1151       add_dependencies(opencv_tests ${the_target})
1152
1153       set_target_properties(${the_target} PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};AccuracyTest")
1154       set_source_files_properties(${OPENCV_TEST_${the_module}_SOURCES} ${${the_target}_pch}
1155         PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};AccuracyTest")
1156
1157       # Additional target properties
1158       set_target_properties(${the_target} PROPERTIES
1159         DEBUG_POSTFIX "${OPENCV_DEBUG_POSTFIX}"
1160         RUNTIME_OUTPUT_DIRECTORY "${EXECUTABLE_OUTPUT_PATH}"
1161       )
1162
1163       ocv_append_target_property(${the_target} COMPILE_DEFINITIONS "__OPENCV_TESTS=1")
1164
1165       if(ENABLE_SOLUTION_FOLDERS)
1166         set_target_properties(${the_target} PROPERTIES FOLDER "tests accuracy")
1167       endif()
1168
1169       if(OPENCV_TEST_BIGDATA)
1170         ocv_append_target_property(${the_target} COMPILE_DEFINITIONS "OPENCV_TEST_BIGDATA=1")
1171       endif()
1172
1173       if(NOT BUILD_opencv_world)
1174         _ocv_add_precompiled_headers(${the_target})
1175       endif()
1176
1177       ocv_add_test_from_target("${the_target}" "Accuracy" "${the_target}")
1178     else(OCV_DEPENDENCIES_FOUND)
1179       # TODO: warn about unsatisfied dependencies
1180     endif(OCV_DEPENDENCIES_FOUND)
1181
1182     if(INSTALL_TESTS)
1183       install(TARGETS ${the_target} RUNTIME DESTINATION ${OPENCV_TEST_INSTALL_PATH} COMPONENT tests)
1184     endif()
1185   endif()
1186 endfunction()
1187
1188 function(ocv_add_samples)
1189   ocv_debug_message("ocv_add_samples(" ${ARGN} ")")
1190
1191   set(samples_path "${CMAKE_CURRENT_SOURCE_DIR}/samples")
1192   string(REGEX REPLACE "^opencv_" "" module_id ${the_module})
1193
1194   if(BUILD_EXAMPLES AND EXISTS "${samples_path}")
1195     set(samples_deps ${the_module} ${OPENCV_MODULE_${the_module}_DEPS} opencv_imgcodecs opencv_videoio opencv_highgui ${ARGN})
1196     ocv_check_dependencies(${samples_deps})
1197
1198     if(OCV_DEPENDENCIES_FOUND)
1199       file(GLOB sample_sources "${samples_path}/*.cpp")
1200
1201       foreach(source ${sample_sources})
1202         get_filename_component(name "${source}" NAME_WE)
1203         set(the_target "example_${module_id}_${name}")
1204
1205         ocv_add_executable(${the_target} "${source}")
1206         ocv_target_include_modules(${the_target} ${samples_deps})
1207         ocv_target_link_libraries(${the_target} ${samples_deps})
1208         set_target_properties(${the_target} PROPERTIES PROJECT_LABEL "(sample) ${name}")
1209
1210         set_target_properties(${the_target} PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};Sample")
1211         set_source_files_properties("${source}"
1212           PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};Sample")
1213
1214         if(ENABLE_SOLUTION_FOLDERS)
1215           set_target_properties(${the_target} PROPERTIES
1216             OUTPUT_NAME "${module_id}-example-${name}"
1217             FOLDER "samples/${module_id}")
1218         endif()
1219
1220         if(WIN32)
1221           install(TARGETS ${the_target} RUNTIME DESTINATION "samples/${module_id}" COMPONENT samples)
1222         endif()
1223       endforeach()
1224     endif()
1225   endif()
1226
1227   if(INSTALL_C_EXAMPLES AND NOT WIN32 AND EXISTS "${samples_path}")
1228   file(GLOB DEPLOY_FILES_AND_DIRS "${samples_path}/*")
1229     foreach(ITEM ${DEPLOY_FILES_AND_DIRS})
1230         IF( IS_DIRECTORY "${ITEM}" )
1231             LIST( APPEND sample_dirs "${ITEM}" )
1232         ELSE()
1233             LIST( APPEND sample_files "${ITEM}" )
1234         ENDIF()
1235     endforeach()
1236     install(FILES ${sample_files}
1237             DESTINATION ${OPENCV_SAMPLES_SRC_INSTALL_PATH}/${module_id}
1238             PERMISSIONS OWNER_READ GROUP_READ WORLD_READ COMPONENT samples)
1239     install(DIRECTORY ${sample_dirs}
1240             DESTINATION ${OPENCV_SAMPLES_SRC_INSTALL_PATH}/${module_id}
1241             USE_SOURCE_PERMISSIONS COMPONENT samples)
1242   endif()
1243 endfunction()