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