Merge pull request #9541 from sturkmen72:patch-15
[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}.hpp" "${CMAKE_CURRENT_BINARY_DIR}/${OCL_NAME}.cpp"
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     ocv_source_group("Src\\opencl\\kernels" FILES ${cl_kernels})
727     ocv_source_group("Src\\opencl\\kernels\\autogenerated" FILES "${CMAKE_CURRENT_BINARY_DIR}/${OCL_NAME}.cpp" "${CMAKE_CURRENT_BINARY_DIR}/${OCL_NAME}.hpp")
728     list(APPEND lib_srcs ${cl_kernels} "${CMAKE_CURRENT_BINARY_DIR}/${OCL_NAME}.cpp" "${CMAKE_CURRENT_BINARY_DIR}/${OCL_NAME}.hpp")
729   endif()
730
731   ocv_set_module_sources(${_argn} HEADERS ${lib_hdrs} ${lib_hdrs_detail}
732                          SOURCES ${lib_srcs} ${lib_int_hdrs} ${lib_cuda_srcs} ${lib_cuda_hdrs})
733 endmacro()
734
735 # creates OpenCV module in current folder
736 # creates new target, configures standard dependencies, compilers flags, install rules
737 # Usage:
738 #   ocv_create_module(<extra link dependencies>)
739 #   ocv_create_module()
740 macro(ocv_create_module)
741   ocv_debug_message("${the_module}: ocv_create_module(" ${ARGN} ")")
742   if(NOT " ${ARGN}" STREQUAL " ")
743     set(OPENCV_MODULE_${the_module}_LINK_DEPS "${OPENCV_MODULE_${the_module}_LINK_DEPS};${ARGN}" CACHE INTERNAL "")
744   endif()
745   if(${BUILD_opencv_world} AND OPENCV_MODULE_${the_module}_IS_PART_OF_WORLD)
746     # nothing
747     set(the_module_target opencv_world)
748   else()
749     _ocv_create_module(${ARGN})
750     set(the_module_target ${the_module})
751   endif()
752
753   if(WINRT)
754     # removing APPCONTAINER from modules to run from console
755     # in case of usual starting of WinRT test apps output is missing
756     # so starting of console version w/o APPCONTAINER is required to get test results
757     # also this allows to use opencv_extra test data for these tests
758     if(NOT "${the_module}" STREQUAL "opencv_ts" AND NOT "${the_module}" STREQUAL "opencv_hal")
759       add_custom_command(TARGET ${the_module}
760                          POST_BUILD
761                          COMMAND link.exe /edit /APPCONTAINER:NO $(TargetPath))
762     endif()
763
764     if("${the_module}" STREQUAL "opencv_ts")
765       # copy required dll files; WinRT apps need these dlls that are usually substituted by Visual Studio
766       # however they are not on path and need to be placed with executables to run from console w/o APPCONTAINER
767       add_custom_command(TARGET ${the_module}
768         POST_BUILD
769         COMMAND copy /y "\"$(VCInstallDir)redist\\$(PlatformTarget)\\Microsoft.VC$(PlatformToolsetVersion).CRT\\msvcp$(PlatformToolsetVersion).dll\"" "\"${CMAKE_BINARY_DIR}\\bin\\$(Configuration)\\msvcp$(PlatformToolsetVersion)_app.dll\""
770         COMMAND copy /y "\"$(VCInstallDir)redist\\$(PlatformTarget)\\Microsoft.VC$(PlatformToolsetVersion).CRT\\msvcr$(PlatformToolsetVersion).dll\"" "\"${CMAKE_BINARY_DIR}\\bin\\$(Configuration)\\msvcr$(PlatformToolsetVersion)_app.dll\""
771         COMMAND copy /y "\"$(VCInstallDir)redist\\$(PlatformTarget)\\Microsoft.VC$(PlatformToolsetVersion).CRT\\vccorlib$(PlatformToolsetVersion).dll\"" "\"${CMAKE_BINARY_DIR}\\bin\\$(Configuration)\\vccorlib$(PlatformToolsetVersion)_app.dll\"")
772     endif()
773   endif()
774 endmacro()
775
776 macro(_ocv_create_module)
777
778   ocv_compiler_optimization_process_sources(OPENCV_MODULE_${the_module}_SOURCES OPENCV_MODULE_${the_module}_DEPS_EXT ${the_module})
779   set(OPENCV_MODULE_${the_module}_HEADERS ${OPENCV_MODULE_${the_module}_HEADERS} CACHE INTERNAL "List of header files for ${the_module}")
780   set(OPENCV_MODULE_${the_module}_SOURCES ${OPENCV_MODULE_${the_module}_SOURCES} CACHE INTERNAL "List of source files for ${the_module}")
781
782   # The condition we ought to be testing here is whether ocv_add_precompiled_headers will
783   # be called at some point in the future. We can't look into the future, though,
784   # so this will have to do.
785   if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/src/precomp.hpp" AND NOT ${the_module} STREQUAL opencv_world)
786     get_native_precompiled_header(${the_module} precomp.hpp)
787   endif()
788
789   set(sub_objs "")
790   set(cuda_objs "")
791   if (OPENCV_MODULE_${the_module}_CHILDREN)
792     message(STATUS "Complex module ${the_module}")
793     foreach (m ${OPENCV_MODULE_${the_module}_CHILDREN})
794       if (BUILD_${m} AND TARGET ${m}_object)
795         list(APPEND sub_objs $<TARGET_OBJECTS:${m}_object>)
796         message(STATUS "    + ${m}")
797       else()
798         message(STATUS "    - ${m}")
799       endif()
800       list(APPEND cuda_objs ${OPENCV_MODULE_${m}_CUDA_OBJECTS})
801     endforeach()
802   endif()
803
804   if(WIN32
805       AND (BUILD_SHARED_LIBS AND NOT "x${OPENCV_MODULE_TYPE}" STREQUAL "xSTATIC")
806       AND NOT OPENCV_VS_VERSIONINFO_SKIP)
807     if(DEFINED OPENCV_VS_VERSIONINFO_FILE)
808       set(_VS_VERSION_FILE "${OPENCV_VS_VERSIONINFO_FILE}")
809     elseif(DEFINED OPENCV_VS_VERSIONINFO_${the_module}_FILE)
810       set(_VS_VERSION_FILE "${OPENCV_VS_VERSIONINFO_${the_module}_FILE}")
811     elseif(NOT OPENCV_VS_VERSIONINFO_SKIP_GENERATION)
812       set(_VS_VERSION_FILE "${CMAKE_CURRENT_BINARY_DIR}/vs_version.rc")
813       ocv_generate_vs_version_file("${_VS_VERSION_FILE}"
814         NAME "${the_module}"
815         FILEDESCRIPTION "OpenCV module: ${OPENCV_MODULE_${the_module}_DESCRIPTION}"
816         INTERNALNAME "${the_module}${OPENCV_DLLVERSION}"
817         ORIGINALFILENAME "${the_module}${OPENCV_DLLVERSION}.dll"
818       )
819     endif()
820     if(_VS_VERSION_FILE)
821       if(NOT EXISTS "${_VS_VERSION_FILE}")
822         message(STATUS "${the_module}: Required .rc file is missing: ${_VS_VERSION_FILE}")
823       endif()
824       source_group("Src" FILES "${_VS_VERSION_FILE}")
825     endif()
826   endif()
827
828   source_group("Include" FILES "${OPENCV_CONFIG_FILE_INCLUDE_DIR}/cvconfig.h" "${OPENCV_CONFIG_FILE_INCLUDE_DIR}/opencv2/opencv_modules.hpp")
829   source_group("Src" FILES "${${the_module}_pch}")
830   ocv_add_library(${the_module} ${OPENCV_MODULE_TYPE} ${OPENCV_MODULE_${the_module}_HEADERS} ${OPENCV_MODULE_${the_module}_SOURCES}
831     "${OPENCV_CONFIG_FILE_INCLUDE_DIR}/cvconfig.h" "${OPENCV_CONFIG_FILE_INCLUDE_DIR}/opencv2/opencv_modules.hpp"
832     ${${the_module}_pch} ${sub_objs}
833     ${_VS_VERSION_FILE}
834   )
835
836   if (cuda_objs)
837     target_link_libraries(${the_module} LINK_PRIVATE ${cuda_objs})
838   endif()
839
840   unset(sub_objs)
841   unset(cuda_objs)
842
843   set_target_properties(${the_module} PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};Module")
844   set_source_files_properties(${OPENCV_MODULE_${the_module}_HEADERS} ${OPENCV_MODULE_${the_module}_SOURCES} ${${the_module}_pch}
845     PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};Module")
846
847   ocv_target_link_libraries(${the_module} LINK_PUBLIC ${OPENCV_MODULE_${the_module}_DEPS_TO_LINK})
848   ocv_target_link_libraries(${the_module} LINK_PUBLIC ${OPENCV_MODULE_${the_module}_DEPS_EXT})
849   ocv_target_link_libraries(${the_module} LINK_PRIVATE ${OPENCV_LINKER_LIBS} ${OPENCV_HAL_LINKER_LIBS} ${IPP_LIBS} ${ARGN})
850   if (HAVE_CUDA)
851     ocv_target_link_libraries(${the_module} LINK_PRIVATE ${CUDA_LIBRARIES} ${CUDA_npp_LIBRARY})
852   endif()
853
854   add_dependencies(opencv_modules ${the_module})
855
856   if(ENABLE_SOLUTION_FOLDERS)
857     set_target_properties(${the_module} PROPERTIES FOLDER "modules")
858   endif()
859
860   set_target_properties(${the_module} PROPERTIES
861     OUTPUT_NAME "${the_module}${OPENCV_DLLVERSION}"
862     DEBUG_POSTFIX "${OPENCV_DEBUG_POSTFIX}"
863     COMPILE_PDB_NAME "${the_module}${OPENCV_DLLVERSION}"
864     COMPILE_PDB_NAME_DEBUG "${the_module}${OPENCV_DLLVERSION}${OPENCV_DEBUG_POSTFIX}"
865     ARCHIVE_OUTPUT_DIRECTORY ${LIBRARY_OUTPUT_PATH}
866     COMPILE_PDB_OUTPUT_DIRECTORY ${LIBRARY_OUTPUT_PATH}
867     LIBRARY_OUTPUT_DIRECTORY ${LIBRARY_OUTPUT_PATH}
868     RUNTIME_OUTPUT_DIRECTORY ${EXECUTABLE_OUTPUT_PATH}
869   )
870
871   # For dynamic link numbering convenions
872   if(NOT ANDROID)
873     # Android SDK build scripts can include only .so files into final .apk
874     # As result we should not set version properties for Android
875     set_target_properties(${the_module} PROPERTIES
876       VERSION ${OPENCV_LIBVERSION}
877       SOVERSION ${OPENCV_SOVERSION}
878     )
879   endif()
880
881   if((NOT DEFINED OPENCV_MODULE_TYPE AND BUILD_SHARED_LIBS)
882       OR (DEFINED OPENCV_MODULE_TYPE AND OPENCV_MODULE_TYPE STREQUAL SHARED))
883     set_target_properties(${the_module} PROPERTIES DEFINE_SYMBOL CVAPI_EXPORTS)
884   endif()
885
886   if (ENABLE_GNU_STL_DEBUG)
887     target_compile_definitions(${the_module} PUBLIC _GLIBCXX_DEBUG)
888   endif()
889
890   if(MSVC)
891     if(CMAKE_CROSSCOMPILING)
892       set_target_properties(${the_module} PROPERTIES LINK_FLAGS "/NODEFAULTLIB:secchk")
893     endif()
894     set_target_properties(${the_module} PROPERTIES LINK_FLAGS "/NODEFAULTLIB:libc /DEBUG")
895   endif()
896
897   get_target_property(_target_type ${the_module} TYPE)
898   if(OPENCV_MODULE_${the_module}_CLASS STREQUAL "PUBLIC" AND
899       ("${_target_type}" STREQUAL "SHARED_LIBRARY" OR (NOT BUILD_SHARED_LIBS OR NOT INSTALL_CREATE_DISTRIB)))
900     ocv_install_target(${the_module} EXPORT OpenCVModules OPTIONAL
901       RUNTIME DESTINATION ${OPENCV_BIN_INSTALL_PATH} COMPONENT libs
902       LIBRARY DESTINATION ${OPENCV_LIB_INSTALL_PATH} COMPONENT libs NAMELINK_SKIP
903       ARCHIVE DESTINATION ${OPENCV_LIB_INSTALL_PATH} COMPONENT dev
904       )
905   endif()
906   if("${_target_type}" STREQUAL "SHARED_LIBRARY")
907     install(TARGETS ${the_module}
908       LIBRARY DESTINATION ${OPENCV_LIB_INSTALL_PATH} COMPONENT dev NAMELINK_ONLY)
909   endif()
910
911   foreach(m ${OPENCV_MODULE_${the_module}_CHILDREN} ${the_module})
912     # only "public" headers need to be installed
913     if(OPENCV_MODULE_${m}_HEADERS AND ";${OPENCV_MODULES_PUBLIC};" MATCHES ";${m};")
914       foreach(hdr ${OPENCV_MODULE_${m}_HEADERS})
915         string(REGEX REPLACE "^.*opencv2/" "opencv2/" hdr2 "${hdr}")
916         if(NOT hdr2 MATCHES "private" AND hdr2 MATCHES "^(opencv2/?.*)/[^/]+.h(..)?$" )
917           install(FILES ${hdr} OPTIONAL DESTINATION "${OPENCV_INCLUDE_INSTALL_PATH}/${CMAKE_MATCH_1}" COMPONENT dev)
918         endif()
919       endforeach()
920     endif()
921   endforeach()
922
923   _ocv_add_precompiled_headers(${the_module})
924
925   if (TARGET ${the_module}_object)
926     # copy COMPILE_DEFINITIONS
927     get_target_property(main_defs ${the_module} COMPILE_DEFINITIONS)
928     if (main_defs)
929       set_target_properties(${the_module}_object PROPERTIES COMPILE_DEFINITIONS ${main_defs})
930     endif()
931     # use same PCH
932     if (TARGET pch_Generate_${the_module})
933       add_dependencies(${the_module}_object pch_Generate_${the_module} )
934     endif()
935   endif()
936 endmacro()
937
938 # opencv precompiled headers macro (can add pch to modules and tests)
939 # this macro must be called after any "add_definitions" commands, otherwise precompiled headers will not work
940 # Usage:
941 # ocv_add_precompiled_headers(${the_module})
942 macro(_ocv_add_precompiled_headers the_target)
943   ocv_debug_message("ocv_add_precompiled_headers(" ${the_target} ${ARGN} ")")
944
945   if("${the_target}" MATCHES "^opencv_test_.*$")
946     SET(pch_path "test/test_")
947   elseif("${the_target}" MATCHES "^opencv_perf_.*$")
948     SET(pch_path "perf/perf_")
949   else()
950     SET(pch_path "src/")
951   endif()
952   ocv_add_precompiled_header_to_target(${the_target} "${CMAKE_CURRENT_SOURCE_DIR}/${pch_path}precomp.hpp")
953   unset(pch_path)
954 endmacro()
955
956 # short command for adding simple OpenCV module
957 # see ocv_add_module for argument details
958 # Usage:
959 # ocv_define_module(module_name  [INTERNAL] [EXCLUDE_CUDA] [REQUIRED] [<list of dependencies>] [OPTIONAL <list of optional dependencies>] [WRAP <list of wrappers>])
960 macro(ocv_define_module module_name)
961   ocv_debug_message("ocv_define_module(" ${module_name} ${ARGN} ")")
962   set(_argn ${ARGN})
963   set(exclude_cuda "")
964   foreach(arg ${_argn})
965     if("${arg}" STREQUAL "EXCLUDE_CUDA")
966       set(exclude_cuda "${arg}")
967       list(REMOVE_ITEM _argn ${arg})
968     endif()
969   endforeach()
970
971   ocv_add_module(${module_name} ${_argn})
972   ocv_glob_module_sources(${exclude_cuda})
973   ocv_module_include_directories()
974   ocv_create_module()
975
976   ocv_add_accuracy_tests()
977   ocv_add_perf_tests()
978   ocv_add_samples()
979 endmacro()
980
981 # ensures that all passed modules are available
982 # sets OCV_DEPENDENCIES_FOUND variable to TRUE/FALSE
983 macro(ocv_check_dependencies)
984   set(OCV_DEPENDENCIES_FOUND TRUE)
985   foreach(d ${ARGN})
986     if(d MATCHES "^opencv_[^ ]+$" AND NOT HAVE_${d})
987       set(OCV_DEPENDENCIES_FOUND FALSE)
988       break()
989     endif()
990   endforeach()
991 endmacro()
992
993 # auxiliary macro to parse arguments of ocv_add_accuracy_tests and ocv_add_perf_tests commands
994 macro(__ocv_parse_test_sources tests_type)
995   set(OPENCV_${tests_type}_${the_module}_SOURCES "")
996   set(OPENCV_${tests_type}_${the_module}_DEPS "")
997   set(__file_group_name "")
998   set(__file_group_sources "")
999   foreach(arg "DEPENDS_ON" ${ARGN} "FILES")
1000     if(arg STREQUAL "FILES")
1001       set(__currentvar "__file_group_sources")
1002       if(__file_group_name AND __file_group_sources)
1003         source_group("${__file_group_name}" FILES ${__file_group_sources})
1004         list(APPEND OPENCV_${tests_type}_${the_module}_SOURCES ${__file_group_sources})
1005       endif()
1006       set(__file_group_name "")
1007       set(__file_group_sources "")
1008     elseif(arg STREQUAL "DEPENDS_ON")
1009       set(__currentvar "OPENCV_${tests_type}_${the_module}_DEPS")
1010     elseif(" ${__currentvar}" STREQUAL " __file_group_sources" AND NOT __file_group_name) # spaces to avoid CMP0054
1011       set(__file_group_name "${arg}")
1012     else()
1013       list(APPEND ${__currentvar} "${arg}")
1014     endif()
1015   endforeach()
1016   unset(__file_group_name)
1017   unset(__file_group_sources)
1018   unset(__currentvar)
1019 endmacro()
1020
1021 # this is a command for adding OpenCV performance tests to the module
1022 # ocv_add_perf_tests(<extra_dependencies>)
1023 function(ocv_add_perf_tests)
1024   ocv_debug_message("ocv_add_perf_tests(" ${ARGN} ")")
1025
1026   if(WINRT)
1027     set(OPENCV_DEBUG_POSTFIX "")
1028   endif()
1029
1030   set(perf_path "${CMAKE_CURRENT_LIST_DIR}/perf")
1031   if(BUILD_PERF_TESTS AND EXISTS "${perf_path}")
1032     __ocv_parse_test_sources(PERF ${ARGN})
1033
1034     # opencv_imgcodecs is required for imread/imwrite
1035     set(perf_deps opencv_ts ${the_module} opencv_imgcodecs ${OPENCV_MODULE_${the_module}_DEPS} ${OPENCV_MODULE_opencv_ts_DEPS})
1036     ocv_check_dependencies(${perf_deps})
1037
1038     if(OCV_DEPENDENCIES_FOUND)
1039       set(the_target "opencv_perf_${name}")
1040       # project(${the_target})
1041
1042       if(NOT OPENCV_PERF_${the_module}_SOURCES)
1043         file(GLOB_RECURSE perf_srcs "${perf_path}/*.cpp")
1044         file(GLOB_RECURSE perf_hdrs "${perf_path}/*.hpp" "${perf_path}/*.h")
1045         ocv_source_group("Src" DIRBASE "${perf_path}" FILES ${perf_srcs})
1046         ocv_source_group("Include" DIRBASE "${perf_path}" FILES ${perf_hdrs})
1047         set(OPENCV_PERF_${the_module}_SOURCES ${perf_srcs} ${perf_hdrs})
1048       endif()
1049
1050       ocv_compiler_optimization_process_sources(OPENCV_PERF_${the_module}_SOURCES OPENCV_PERF_${the_module}_DEPS ${the_target})
1051
1052       if(NOT BUILD_opencv_world)
1053         get_native_precompiled_header(${the_target} perf_precomp.hpp)
1054       endif()
1055
1056       source_group("Src" FILES "${${the_target}_pch}")
1057       ocv_add_executable(${the_target} ${OPENCV_PERF_${the_module}_SOURCES} ${${the_target}_pch})
1058       ocv_target_include_modules(${the_target} ${perf_deps} "${perf_path}")
1059       ocv_target_link_libraries(${the_target} LINK_PRIVATE ${perf_deps} ${OPENCV_MODULE_${the_module}_DEPS} ${OPENCV_LINKER_LIBS})
1060       add_dependencies(opencv_perf_tests ${the_target})
1061
1062       set_target_properties(${the_target} PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};PerfTest")
1063       set_source_files_properties(${OPENCV_PERF_${the_module}_SOURCES} ${${the_target}_pch}
1064         PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};PerfTest")
1065
1066       # Additional target properties
1067       set_target_properties(${the_target} PROPERTIES
1068         DEBUG_POSTFIX "${OPENCV_DEBUG_POSTFIX}"
1069         RUNTIME_OUTPUT_DIRECTORY "${EXECUTABLE_OUTPUT_PATH}"
1070       )
1071       if(ENABLE_SOLUTION_FOLDERS)
1072         set_target_properties(${the_target} PROPERTIES FOLDER "tests performance")
1073       endif()
1074
1075       if(WINRT)
1076         # removing APPCONTAINER from tests to run from console
1077         # look for detailed description inside of ocv_create_module macro above
1078         add_custom_command(TARGET "opencv_perf_${name}"
1079                            POST_BUILD
1080                            COMMAND link.exe /edit /APPCONTAINER:NO $(TargetPath))
1081       endif()
1082
1083       if(NOT BUILD_opencv_world)
1084         _ocv_add_precompiled_headers(${the_target})
1085       endif()
1086
1087       ocv_add_test_from_target("${the_target}" "Performance" "${the_target}")
1088       ocv_add_test_from_target("opencv_sanity_${name}" "Sanity" "${the_target}"
1089                                "--perf_min_samples=1"
1090                                "--perf_force_samples=1"
1091                                "--perf_verify_sanity")
1092     else(OCV_DEPENDENCIES_FOUND)
1093       # TODO: warn about unsatisfied dependencies
1094     endif(OCV_DEPENDENCIES_FOUND)
1095     if(INSTALL_TESTS)
1096       install(TARGETS ${the_target} RUNTIME DESTINATION ${OPENCV_TEST_INSTALL_PATH} COMPONENT tests)
1097     endif()
1098   endif()
1099 endfunction()
1100
1101 # this is a command for adding OpenCV accuracy/regression tests to the module
1102 # ocv_add_accuracy_tests([FILES <source group name> <list of sources>] [DEPENDS_ON] <list of extra dependencies>)
1103 function(ocv_add_accuracy_tests)
1104   ocv_debug_message("ocv_add_accuracy_tests(" ${ARGN} ")")
1105
1106   if(WINRT)
1107     set(OPENCV_DEBUG_POSTFIX "")
1108   endif()
1109
1110   set(test_path "${CMAKE_CURRENT_LIST_DIR}/test")
1111   if(BUILD_TESTS AND EXISTS "${test_path}")
1112     __ocv_parse_test_sources(TEST ${ARGN})
1113
1114     # opencv_imgcodecs is required for imread/imwrite
1115     set(test_deps opencv_ts ${the_module} opencv_imgcodecs opencv_videoio ${OPENCV_MODULE_${the_module}_DEPS} ${OPENCV_MODULE_opencv_ts_DEPS})
1116     ocv_check_dependencies(${test_deps})
1117     if(OCV_DEPENDENCIES_FOUND)
1118       set(the_target "opencv_test_${name}")
1119       # project(${the_target})
1120
1121       if(NOT OPENCV_TEST_${the_module}_SOURCES)
1122         file(GLOB_RECURSE test_srcs "${test_path}/*.cpp")
1123         file(GLOB_RECURSE test_hdrs "${test_path}/*.hpp" "${test_path}/*.h")
1124         ocv_source_group("Src" DIRBASE "${test_path}" FILES ${test_srcs})
1125         ocv_source_group("Include" DIRBASE "${test_path}" FILES ${test_hdrs})
1126         set(OPENCV_TEST_${the_module}_SOURCES ${test_srcs} ${test_hdrs})
1127       endif()
1128
1129       ocv_compiler_optimization_process_sources(OPENCV_TEST_${the_module}_SOURCES OPENCV_TEST_${the_module}_DEPS ${the_target})
1130
1131       if(NOT BUILD_opencv_world)
1132         get_native_precompiled_header(${the_target} test_precomp.hpp)
1133       endif()
1134
1135       source_group("Src" FILES "${${the_target}_pch}")
1136       ocv_add_executable(${the_target} ${OPENCV_TEST_${the_module}_SOURCES} ${${the_target}_pch})
1137       ocv_target_include_modules(${the_target} ${test_deps} "${test_path}")
1138       ocv_target_link_libraries(${the_target} LINK_PRIVATE ${test_deps} ${OPENCV_MODULE_${the_module}_DEPS} ${OPENCV_LINKER_LIBS})
1139       add_dependencies(opencv_tests ${the_target})
1140
1141       set_target_properties(${the_target} PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};AccuracyTest")
1142       set_source_files_properties(${OPENCV_TEST_${the_module}_SOURCES} ${${the_target}_pch}
1143         PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};AccuracyTest")
1144
1145       # Additional target properties
1146       set_target_properties(${the_target} PROPERTIES
1147         DEBUG_POSTFIX "${OPENCV_DEBUG_POSTFIX}"
1148         RUNTIME_OUTPUT_DIRECTORY "${EXECUTABLE_OUTPUT_PATH}"
1149       )
1150
1151       ocv_append_target_property(${the_target} COMPILE_DEFINITIONS "__OPENCV_TESTS=1")
1152
1153       if(ENABLE_SOLUTION_FOLDERS)
1154         set_target_properties(${the_target} PROPERTIES FOLDER "tests accuracy")
1155       endif()
1156
1157       if(OPENCV_TEST_BIGDATA)
1158         ocv_append_target_property(${the_target} COMPILE_DEFINITIONS "OPENCV_TEST_BIGDATA=1")
1159       endif()
1160
1161       if(NOT BUILD_opencv_world)
1162         _ocv_add_precompiled_headers(${the_target})
1163       endif()
1164
1165       ocv_add_test_from_target("${the_target}" "Accuracy" "${the_target}")
1166     else(OCV_DEPENDENCIES_FOUND)
1167       # TODO: warn about unsatisfied dependencies
1168     endif(OCV_DEPENDENCIES_FOUND)
1169
1170     if(INSTALL_TESTS)
1171       install(TARGETS ${the_target} RUNTIME DESTINATION ${OPENCV_TEST_INSTALL_PATH} COMPONENT tests)
1172     endif()
1173   endif()
1174 endfunction()
1175
1176 function(ocv_add_samples)
1177   ocv_debug_message("ocv_add_samples(" ${ARGN} ")")
1178
1179   set(samples_path "${CMAKE_CURRENT_SOURCE_DIR}/samples")
1180   string(REGEX REPLACE "^opencv_" "" module_id ${the_module})
1181
1182   if(BUILD_EXAMPLES AND EXISTS "${samples_path}")
1183     set(samples_deps ${the_module} ${OPENCV_MODULE_${the_module}_DEPS} opencv_imgcodecs opencv_videoio opencv_highgui ${ARGN})
1184     ocv_check_dependencies(${samples_deps})
1185
1186     if(OCV_DEPENDENCIES_FOUND)
1187       file(GLOB sample_sources "${samples_path}/*.cpp")
1188
1189       foreach(source ${sample_sources})
1190         get_filename_component(name "${source}" NAME_WE)
1191         set(the_target "example_${module_id}_${name}")
1192
1193         ocv_add_executable(${the_target} "${source}")
1194         ocv_target_include_modules(${the_target} ${samples_deps})
1195         ocv_target_link_libraries(${the_target} LINK_PRIVATE ${samples_deps})
1196         set_target_properties(${the_target} PROPERTIES PROJECT_LABEL "(sample) ${name}")
1197
1198         set_target_properties(${the_target} PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};Sample")
1199         set_source_files_properties("${source}"
1200           PROPERTIES LABELS "${OPENCV_MODULE_${the_module}_LABEL};Sample")
1201
1202         if(ENABLE_SOLUTION_FOLDERS)
1203           set_target_properties(${the_target} PROPERTIES
1204             OUTPUT_NAME "${module_id}-example-${name}"
1205             FOLDER "samples/${module_id}")
1206         endif()
1207
1208         if(WIN32)
1209           install(TARGETS ${the_target} RUNTIME DESTINATION "samples/${module_id}" COMPONENT samples)
1210         endif()
1211       endforeach()
1212     endif()
1213   endif()
1214
1215   if(INSTALL_C_EXAMPLES AND NOT WIN32 AND EXISTS "${samples_path}")
1216   file(GLOB DEPLOY_FILES_AND_DIRS "${samples_path}/*")
1217     foreach(ITEM ${DEPLOY_FILES_AND_DIRS})
1218         IF( IS_DIRECTORY "${ITEM}" )
1219             LIST( APPEND sample_dirs "${ITEM}" )
1220         ELSE()
1221             LIST( APPEND sample_files "${ITEM}" )
1222         ENDIF()
1223     endforeach()
1224     install(FILES ${sample_files}
1225             DESTINATION ${OPENCV_SAMPLES_SRC_INSTALL_PATH}/${module_id}
1226             PERMISSIONS OWNER_READ GROUP_READ WORLD_READ COMPONENT samples)
1227     install(DIRECTORY ${sample_dirs}
1228             DESTINATION ${OPENCV_SAMPLES_SRC_INSTALL_PATH}/${module_id}
1229             USE_SOURCE_PERMISSIONS COMPONENT samples)
1230   endif()
1231 endfunction()