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