summaryrefslogtreecommitdiffstats
path: root/Modules/Qt4Macros.cmake
blob: cb6ae4398dc43286f9477f89fae03939f97efd36 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.

#[=======================================================================[.rst:
Qt4Macros
---------



This file is included by FindQt4.cmake, don't include it directly.
#]=======================================================================]

######################################
#
#       Macros for building Qt files
#
######################################


macro (QT4_EXTRACT_OPTIONS _qt4_files _qt4_options _qt4_target)
  set(${_qt4_files})
  set(${_qt4_options})
  set(_QT4_DOING_OPTIONS FALSE)
  set(_QT4_DOING_TARGET FALSE)
  foreach(_currentArg ${ARGN})
    if ("x${_currentArg}" STREQUAL "xOPTIONS")
      set(_QT4_DOING_OPTIONS TRUE)
    elseif ("x${_currentArg}" STREQUAL "xTARGET")
      set(_QT4_DOING_TARGET TRUE)
    else ()
      if(_QT4_DOING_TARGET)
        set(${_qt4_target} "${_currentArg}")
      elseif(_QT4_DOING_OPTIONS)
        list(APPEND ${_qt4_options} "${_currentArg}")
      else()
        list(APPEND ${_qt4_files} "${_currentArg}")
      endif()
    endif ()
  endforeach()
endmacro ()


# macro used to create the names of output files preserving relative dirs
macro (QT4_MAKE_OUTPUT_FILE infile prefix ext outfile )
  string(LENGTH ${CMAKE_CURRENT_BINARY_DIR} _binlength)
  string(LENGTH ${infile} _infileLength)
  set(_checkinfile ${CMAKE_CURRENT_SOURCE_DIR})
  if(_infileLength GREATER _binlength)
    string(SUBSTRING "${infile}" 0 ${_binlength} _checkinfile)
    if(_checkinfile STREQUAL "${CMAKE_CURRENT_BINARY_DIR}")
      file(RELATIVE_PATH rel ${CMAKE_CURRENT_BINARY_DIR} ${infile})
    else()
      file(RELATIVE_PATH rel ${CMAKE_CURRENT_SOURCE_DIR} ${infile})
    endif()
  else()
    file(RELATIVE_PATH rel ${CMAKE_CURRENT_SOURCE_DIR} ${infile})
  endif()
  if(WIN32 AND rel MATCHES "^([a-zA-Z]):(.*)$") # absolute path
    set(rel "${CMAKE_MATCH_1}_${CMAKE_MATCH_2}")
  endif()
  set(_outfile "${CMAKE_CURRENT_BINARY_DIR}/${rel}")
  string(REPLACE ".." "__" _outfile ${_outfile})
  get_filename_component(outpath ${_outfile} PATH)
  get_filename_component(_outfile ${_outfile} NAME_WE)
  file(MAKE_DIRECTORY ${outpath})
  set(${outfile} ${outpath}/${prefix}${_outfile}.${ext})
endmacro ()


macro (QT4_GET_MOC_FLAGS _moc_flags)
  set(${_moc_flags})
  get_directory_property(_inc_DIRS INCLUDE_DIRECTORIES)

  foreach(_current ${_inc_DIRS})
    if("${_current}" MATCHES "\\.framework/?$")
      string(REGEX REPLACE "/[^/]+\\.framework" "" framework_path "${_current}")
      set(${_moc_flags} ${${_moc_flags}} "-F${framework_path}")
    else()
      set(${_moc_flags} ${${_moc_flags}} "-I${_current}")
    endif()
  endforeach()

  get_directory_property(_defines COMPILE_DEFINITIONS)
  foreach(_current ${_defines})
    set(${_moc_flags} ${${_moc_flags}} "-D${_current}")
  endforeach()

  if(Q_WS_WIN)
    set(${_moc_flags} ${${_moc_flags}} -DWIN32)
  endif()

endmacro()


# helper macro to set up a moc rule
function (QT4_CREATE_MOC_COMMAND infile outfile moc_flags moc_options moc_target)
  # For Windows, create a parameters file to work around command line length limit
  # Pass the parameters in a file.  Set the working directory to
  # be that containing the parameters file and reference it by
  # just the file name.  This is necessary because the moc tool on
  # MinGW builds does not seem to handle spaces in the path to the
  # file given with the @ syntax.
  get_filename_component(_moc_outfile_name "${outfile}" NAME)
  get_filename_component(_moc_outfile_dir "${outfile}" PATH)
  if(_moc_outfile_dir)
    set(_moc_working_dir WORKING_DIRECTORY ${_moc_outfile_dir})
  endif()
  set (_moc_parameters_file ${outfile}_parameters)
  set (_moc_parameters ${moc_flags} ${moc_options} -o "${outfile}" "${infile}")
  string (REPLACE ";" "\n" _moc_parameters "${_moc_parameters}")

  if(moc_target)
    set (_moc_parameters_file ${_moc_parameters_file}$<$<BOOL:$<CONFIGURATION>>:_$<CONFIGURATION>>)
    set(targetincludes "$<TARGET_PROPERTY:${moc_target},INCLUDE_DIRECTORIES>")
    set(targetdefines "$<TARGET_PROPERTY:${moc_target},COMPILE_DEFINITIONS>")

    set(targetincludes "$<$<BOOL:${targetincludes}>:-I$<JOIN:${targetincludes},\n-I>\n>")
    set(targetdefines "$<$<BOOL:${targetdefines}>:-D$<JOIN:${targetdefines},\n-D>\n>")

    file (GENERATE
      OUTPUT ${_moc_parameters_file}
      CONTENT "${targetdefines}${targetincludes}${_moc_parameters}\n"
    )

    set(targetincludes)
    set(targetdefines)
  else()
    set(CMAKE_CONFIGURABLE_FILE_CONTENT "${_moc_parameters}")
    configure_file("${CMAKE_ROOT}/Modules/CMakeConfigurableFile.in"
                   "${_moc_parameters_file}" @ONLY)
  endif()

  set(_moc_extra_parameters_file @${_moc_parameters_file})
  add_custom_command(OUTPUT ${outfile}
                      COMMAND Qt4::moc ${_moc_extra_parameters_file}
                      DEPENDS ${infile} ${_moc_parameters_file}
                      ${_moc_working_dir}
                      VERBATIM)
endfunction ()


macro (QT4_GENERATE_MOC infile outfile )
  # get include dirs and flags
  QT4_GET_MOC_FLAGS(moc_flags)
  get_filename_component(abs_infile ${infile} ABSOLUTE)
  set(_outfile "${outfile}")
  if(NOT IS_ABSOLUTE "${outfile}")
    set(_outfile "${CMAKE_CURRENT_BINARY_DIR}/${outfile}")
  endif()

  if (${ARGC} GREATER 3 AND "x${ARGV2}" STREQUAL "xTARGET")
    set(moc_target ${ARGV3})
  endif()
  QT4_CREATE_MOC_COMMAND(${abs_infile} ${_outfile} "${moc_flags}" "" "${moc_target}")
  set_property(SOURCE ${outfile} PROPERTY SKIP_AUTOMOC TRUE)  # don't run automoc on this file
  set_property(SOURCE ${outfile} PROPERTY SKIP_AUTOUIC TRUE)  # don't run autouic on this file
endmacro ()


# QT4_WRAP_CPP(outfiles inputfile ... )

macro (QT4_WRAP_CPP outfiles )
  # get include dirs
  QT4_GET_MOC_FLAGS(moc_flags)
  QT4_EXTRACT_OPTIONS(moc_files moc_options moc_target ${ARGN})

  foreach (it ${moc_files})
    get_filename_component(it ${it} ABSOLUTE)
    QT4_MAKE_OUTPUT_FILE(${it} moc_ cxx outfile)
    QT4_CREATE_MOC_COMMAND(${it} ${outfile} "${moc_flags}" "${moc_options}" "${moc_target}")
    set_property(SOURCE ${outfile} PROPERTY SKIP_AUTOMOC TRUE)  # don't run automoc on this file
    set_property(SOURCE ${outfile} PROPERTY SKIP_AUTOUIC TRUE)  # don't run autouic on this file
    set(${outfiles} ${${outfiles}} ${outfile})
  endforeach()

endmacro ()


# QT4_WRAP_UI(outfiles inputfile ... )

macro (QT4_WRAP_UI outfiles )
  QT4_EXTRACT_OPTIONS(ui_files ui_options ui_target ${ARGN})

  foreach (it ${ui_files})
    get_filename_component(outfile ${it} NAME_WE)
    get_filename_component(infile ${it} ABSOLUTE)
    set(outfile ${CMAKE_CURRENT_BINARY_DIR}/ui_${outfile}.h)
    add_custom_command(OUTPUT ${outfile}
      COMMAND Qt4::uic
      ARGS ${ui_options} -o ${outfile} ${infile}
      MAIN_DEPENDENCY ${infile} VERBATIM)
    set_property(SOURCE ${outfile} PROPERTY SKIP_AUTOMOC TRUE)  # don't run automoc on this file
    set_property(SOURCE ${outfile} PROPERTY SKIP_AUTOUIC TRUE)  # don't run autouic on this file
    set(${outfiles} ${${outfiles}} ${outfile})
  endforeach ()

endmacro ()


# QT4_ADD_RESOURCES(outfiles inputfile ... )

macro (QT4_ADD_RESOURCES outfiles )
  QT4_EXTRACT_OPTIONS(rcc_files rcc_options rcc_target ${ARGN})

  foreach (it ${rcc_files})
    get_filename_component(outfilename ${it} NAME_WE)
    get_filename_component(infile ${it} ABSOLUTE)
    get_filename_component(rc_path ${infile} PATH)
    set(outfile ${CMAKE_CURRENT_BINARY_DIR}/qrc_${outfilename}.cxx)

    set(_RC_DEPENDS)
    if(EXISTS "${infile}")
      #  parse file for dependencies
      #  all files are absolute paths or relative to the location of the qrc file
      file(READ "${infile}" _RC_FILE_CONTENTS)
      string(REGEX MATCHALL "<file[^<]+" _RC_FILES "${_RC_FILE_CONTENTS}")
      foreach(_RC_FILE ${_RC_FILES})
        string(REGEX REPLACE "^<file[^>]*>" "" _RC_FILE "${_RC_FILE}")
        if(NOT IS_ABSOLUTE "${_RC_FILE}")
          set(_RC_FILE "${rc_path}/${_RC_FILE}")
        endif()
        set(_RC_DEPENDS ${_RC_DEPENDS} "${_RC_FILE}")
      endforeach()
      unset(_RC_FILES)
      unset(_RC_FILE_CONTENTS)
      # Since this cmake macro is doing the dependency scanning for these files,
      # let's make a configured file and add it as a dependency so cmake is run
      # again when dependencies need to be recomputed.
      QT4_MAKE_OUTPUT_FILE("${infile}" "" "qrc.depends" out_depends)
      configure_file("${infile}" "${out_depends}" COPYONLY)
    else()
      # The .qrc file does not exist (yet). Let's add a dependency and hope
      # that it will be generated later
      set(out_depends)
    endif()

    add_custom_command(OUTPUT ${outfile}
      COMMAND Qt4::rcc
      ARGS ${rcc_options} -name ${outfilename} -o ${outfile} ${infile}
      MAIN_DEPENDENCY ${infile}
      DEPENDS ${_RC_DEPENDS} "${out_depends}" VERBATIM)
    set_property(SOURCE ${outfile} PROPERTY SKIP_AUTOMOC TRUE)  # don't run automoc on this file
    set_property(SOURCE ${outfile} PROPERTY SKIP_AUTOUIC TRUE)  # don't run autouic on this file
    set(${outfiles} ${${outfiles}} ${outfile})
  endforeach ()

endmacro ()


macro(QT4_ADD_DBUS_INTERFACE _sources _interface _basename)
  get_filename_component(_infile ${_interface} ABSOLUTE)
  set(_header "${CMAKE_CURRENT_BINARY_DIR}/${_basename}.h")
  set(_impl   "${CMAKE_CURRENT_BINARY_DIR}/${_basename}.cpp")
  set(_moc    "${CMAKE_CURRENT_BINARY_DIR}/${_basename}.moc")

  get_property(_nonamespace SOURCE ${_interface} PROPERTY NO_NAMESPACE)
  if(_nonamespace)
    set(_params -N -m)
  else()
    set(_params -m)
  endif()

  get_property(_classname SOURCE ${_interface} PROPERTY CLASSNAME)
  if(_classname)
    set(_params ${_params} -c ${_classname})
  endif()

  get_property(_include SOURCE ${_interface} PROPERTY INCLUDE)
  if(_include)
    set(_params ${_params} -i ${_include})
  endif()

  add_custom_command(OUTPUT "${_impl}" "${_header}"
      COMMAND Qt4::qdbusxml2cpp ${_params} -p ${_basename} ${_infile}
      DEPENDS ${_infile} VERBATIM)

  set_property(SOURCE ${_impl} PROPERTY SKIP_AUTOMOC TRUE)  # don't run automoc on this file
  set_property(SOURCE ${_impl} PROPERTY SKIP_AUTOUIC TRUE)  # don't run autouic on this file

  QT4_GENERATE_MOC("${_header}" "${_moc}")

  list(APPEND ${_sources} "${_impl}" "${_header}" "${_moc}")
  MACRO_ADD_FILE_DEPENDENCIES("${_impl}" "${_moc}")

endmacro()


macro(QT4_ADD_DBUS_INTERFACES _sources)
  foreach (_current_FILE ${ARGN})
    get_filename_component(_infile ${_current_FILE} ABSOLUTE)
    get_filename_component(_basename ${_current_FILE} NAME)
    # get the part before the ".xml" suffix
    string(TOLOWER ${_basename} _basename)
    string(REGEX REPLACE "(.*\\.)?([^\\.]+)\\.xml" "\\2" _basename ${_basename})
    QT4_ADD_DBUS_INTERFACE(${_sources} ${_infile} ${_basename}interface)
  endforeach ()
endmacro()


macro(QT4_GENERATE_DBUS_INTERFACE _header) # _customName OPTIONS -some -options )
  QT4_EXTRACT_OPTIONS(_customName _qt4_dbus_options _qt4_dbus_target ${ARGN})

  get_filename_component(_in_file ${_header} ABSOLUTE)
  get_filename_component(_basename ${_header} NAME_WE)

  if (_customName)
    if (IS_ABSOLUTE ${_customName})
      get_filename_component(_containingDir ${_customName} PATH)
      if (NOT EXISTS ${_containingDir})
        file(MAKE_DIRECTORY "${_containingDir}")
      endif()
      set(_target ${_customName})
    else()
      set(_target ${CMAKE_CURRENT_BINARY_DIR}/${_customName})
    endif()
  else ()
    set(_target ${CMAKE_CURRENT_BINARY_DIR}/${_basename}.xml)
  endif ()

  add_custom_command(OUTPUT ${_target}
      COMMAND Qt4::qdbuscpp2xml ${_qt4_dbus_options} ${_in_file} -o ${_target}
      DEPENDS ${_in_file} VERBATIM
  )
endmacro()


macro(QT4_ADD_DBUS_ADAPTOR _sources _xml_file _include _parentClass) # _optionalBasename _optionalClassName)
  get_filename_component(_infile ${_xml_file} ABSOLUTE)

  unset(_optionalBasename)
  if(${ARGC} GREATER 4)
    set(_optionalBasename "${ARGV4}")
  endif()
  if (_optionalBasename)
    set(_basename ${_optionalBasename} )
  else ()
    string(REGEX REPLACE "(.*[/\\.])?([^\\.]+)\\.xml" "\\2adaptor" _basename ${_infile})
    string(TOLOWER ${_basename} _basename)
  endif ()

  unset(_optionalClassName)
  if(${ARGC} GREATER 5)
    set(_optionalClassName "${ARGV5}")
  endif()
  set(_header "${CMAKE_CURRENT_BINARY_DIR}/${_basename}.h")
  set(_impl   "${CMAKE_CURRENT_BINARY_DIR}/${_basename}.cpp")
  set(_moc    "${CMAKE_CURRENT_BINARY_DIR}/${_basename}.moc")

  if(_optionalClassName)
    add_custom_command(OUTPUT "${_impl}" "${_header}"
       COMMAND Qt4::qdbusxml2cpp -m -a ${_basename} -c ${_optionalClassName} -i ${_include} -l ${_parentClass} ${_infile}
       DEPENDS ${_infile} VERBATIM
    )
  else()
    add_custom_command(OUTPUT "${_impl}" "${_header}"
       COMMAND Qt4::qdbusxml2cpp -m -a ${_basename} -i ${_include} -l ${_parentClass} ${_infile}
       DEPENDS ${_infile} VERBATIM
     )
  endif()

  QT4_GENERATE_MOC("${_header}" "${_moc}")
  set_property(SOURCE ${_impl} PROPERTY SKIP_AUTOMOC TRUE)  # don't run automoc on this file
  set_property(SOURCE ${_impl} PROPERTY SKIP_AUTOUIC TRUE)  # don't run autouic on this file
  MACRO_ADD_FILE_DEPENDENCIES("${_impl}" "${_moc}")

  list(APPEND ${_sources} "${_impl}" "${_header}" "${_moc}")
endmacro()


macro(QT4_AUTOMOC)
  if(NOT CMAKE_MINIMUM_REQUIRED_VERSION VERSION_LESS 2.8.11)
    message(DEPRECATION "The qt4_automoc macro is obsolete. Use the CMAKE_AUTOMOC feature instead.")
  endif()
  QT4_GET_MOC_FLAGS(_moc_INCS)

  set(_matching_FILES )
  foreach (_current_FILE ${ARGN})

    get_filename_component(_abs_FILE ${_current_FILE} ABSOLUTE)
    # if "SKIP_AUTOMOC" is set to true, we will not handle this file here.
    # This is required to make uic work correctly:
    # we need to add generated .cpp files to the sources (to compile them),
    # but we cannot let automoc handle them, as the .cpp files don't exist yet when
    # cmake is run for the very first time on them -> however the .cpp files might
    # exist at a later run. at that time we need to skip them, so that we don't add two
    # different rules for the same moc file
    get_property(_skip SOURCE ${_abs_FILE} PROPERTY SKIP_AUTOMOC)

    if ( NOT _skip AND EXISTS ${_abs_FILE} )

      file(READ ${_abs_FILE} _contents)

      get_filename_component(_abs_PATH ${_abs_FILE} PATH)

      string(REGEX MATCHALL "# *include +[^ ]+\\.moc[\">]" _match "${_contents}")
      if(_match)
        foreach (_current_MOC_INC ${_match})
          string(REGEX MATCH "[^ <\"]+\\.moc" _current_MOC "${_current_MOC_INC}")

          get_filename_component(_basename ${_current_MOC} NAME_WE)
          if(EXISTS ${_abs_PATH}/${_basename}.hpp)
            set(_header ${_abs_PATH}/${_basename}.hpp)
          else()
            set(_header ${_abs_PATH}/${_basename}.h)
          endif()
          set(_moc    ${CMAKE_CURRENT_BINARY_DIR}/${_current_MOC})
          QT4_CREATE_MOC_COMMAND(${_header} ${_moc} "${_moc_INCS}" "" "")
          MACRO_ADD_FILE_DEPENDENCIES(${_abs_FILE} ${_moc})
        endforeach ()
      endif()
    endif ()
  endforeach ()
endmacro()


macro(QT4_CREATE_TRANSLATION _qm_files)
  QT4_EXTRACT_OPTIONS(_lupdate_files _lupdate_options _lupdate_target ${ARGN})
  set(_my_sources)
  set(_my_dirs)
  set(_my_tsfiles)
  set(_ts_pro)
  foreach (_file ${_lupdate_files})
    get_filename_component(_ext ${_file} EXT)
    get_filename_component(_abs_FILE ${_file} ABSOLUTE)
    if(_ext MATCHES "ts")
      list(APPEND _my_tsfiles ${_abs_FILE})
    else()
      if(NOT _ext)
        list(APPEND _my_dirs ${_abs_FILE})
      else()
        list(APPEND _my_sources ${_abs_FILE})
      endif()
    endif()
  endforeach()
  foreach(_ts_file ${_my_tsfiles})
    if(_my_sources)
      # make a .pro file to call lupdate on, so we don't make our commands too
      # long for some systems
      get_filename_component(_ts_name ${_ts_file} NAME)
      set(_ts_pro ${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/${_ts_name}_lupdate.pro)
      set(_pro_srcs)
      foreach(_pro_src ${_my_sources})
        string(APPEND _pro_srcs " \\\n  \"${_pro_src}\"")
      endforeach()
      set(_pro_includes)
      get_directory_property(_inc_DIRS INCLUDE_DIRECTORIES)
      list(REMOVE_DUPLICATES _inc_DIRS)
      foreach(_pro_include ${_inc_DIRS})
        get_filename_component(_abs_include "${_pro_include}" ABSOLUTE)
        string(APPEND _pro_includes " \\\n  \"${_abs_include}\"")
      endforeach()
      file(GENERATE OUTPUT ${_ts_pro} CONTENT "SOURCES =${_pro_srcs}\nINCLUDEPATH =${_pro_includes}\n")
    endif()
    add_custom_command(OUTPUT ${_ts_file}
        COMMAND Qt4::lupdate
        ARGS ${_lupdate_options} ${_ts_pro} ${_my_dirs} -ts ${_ts_file}
        DEPENDS ${_my_sources} ${_ts_pro} VERBATIM)
  endforeach()
  QT4_ADD_TRANSLATION(${_qm_files} ${_my_tsfiles})
endmacro()


macro(QT4_ADD_TRANSLATION _qm_files)
  foreach (_current_FILE ${ARGN})
    get_filename_component(_abs_FILE ${_current_FILE} ABSOLUTE)
    get_filename_component(qm ${_abs_FILE} NAME)
    # everything before the last dot has to be considered the file name (including other dots)
    string(REGEX REPLACE "\\.[^.]*$" "" FILE_NAME ${qm})
    get_source_file_property(output_location ${_abs_FILE} OUTPUT_LOCATION)
    if(output_location)
      file(MAKE_DIRECTORY "${output_location}")
      set(qm "${output_location}/${FILE_NAME}.qm")
    else()
      set(qm "${CMAKE_CURRENT_BINARY_DIR}/${FILE_NAME}.qm")
    endif()

    add_custom_command(OUTPUT ${qm}
       COMMAND Qt4::lrelease
       ARGS ${_abs_FILE} -qm ${qm}
       DEPENDS ${_abs_FILE} VERBATIM
    )
    set(${_qm_files} ${${_qm_files}} ${qm})
  endforeach ()
endmacro()

function(qt4_use_modules _target _link_type)
  if(NOT CMAKE_MINIMUM_REQUIRED_VERSION VERSION_LESS 2.8.11)
    message(DEPRECATION "The qt4_use_modules function is obsolete. Use target_link_libraries with IMPORTED targets instead.")
  endif()
  if ("${_link_type}" STREQUAL "LINK_PUBLIC" OR "${_link_type}" STREQUAL "LINK_PRIVATE")
    set(modules ${ARGN})
    set(link_type ${_link_type})
  else()
    set(modules ${_link_type} ${ARGN})
  endif()
  foreach(_module ${modules})
    string(TOUPPER ${_module} _ucmodule)
    set(_targetPrefix QT_QT${_ucmodule})
    if (_ucmodule STREQUAL QAXCONTAINER OR _ucmodule STREQUAL QAXSERVER)
      if (NOT QT_Q${_ucmodule}_FOUND)
        message(FATAL_ERROR "Can not use \"${_module}\" module which has not yet been found.")
      endif()
      set(_targetPrefix QT_Q${_ucmodule})
    else()
      if (NOT QT_QT${_ucmodule}_FOUND)
        message(FATAL_ERROR "Can not use \"${_module}\" module which has not yet been found.")
      endif()
      if ("${_ucmodule}" STREQUAL "MAIN")
        message(FATAL_ERROR "Can not use \"${_module}\" module with qt4_use_modules.")
      endif()
    endif()
    target_link_libraries(${_target} ${link_type} ${${_targetPrefix}_LIBRARIES})
    set_property(TARGET ${_target} APPEND PROPERTY INCLUDE_DIRECTORIES ${${_targetPrefix}_INCLUDE_DIR} ${QT_HEADERS_DIR} ${QT_MKSPECS_DIR}/default)
    set_property(TARGET ${_target} APPEND PROPERTY COMPILE_DEFINITIONS ${${_targetPrefix}_COMPILE_DEFINITIONS})
  endforeach()
endfunction()
neterm} argument to \code{""} so that the output will be uniformly newline free. The context diff format normally has a header for filenames and modification times. Any or all of these may be specified using strings for \var{fromfile}, \var{tofile}, \var{fromfiledate}, and \var{tofiledate}. The modification times are normally expressed in the format returned by \function{time.ctime()}. If not specified, the strings default to blanks. \file{Tools/scripts/diff.py} is a command-line front-end for this function. \versionadded{2.3} \end{funcdesc} \begin{funcdesc}{get_close_matches}{word, possibilities\optional{, n\optional{, cutoff}}} Return a list of the best ``good enough'' matches. \var{word} is a sequence for which close matches are desired (typically a string), and \var{possibilities} is a list of sequences against which to match \var{word} (typically a list of strings). Optional argument \var{n} (default \code{3}) is the maximum number of close matches to return; \var{n} must be greater than \code{0}. Optional argument \var{cutoff} (default \code{0.6}) is a float in the range [0, 1]. Possibilities that don't score at least that similar to \var{word} are ignored. The best (no more than \var{n}) matches among the possibilities are returned in a list, sorted by similarity score, most similar first. \begin{verbatim} >>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy']) ['apple', 'ape'] >>> import keyword >>> get_close_matches('wheel', keyword.kwlist) ['while'] >>> get_close_matches('apple', keyword.kwlist) [] >>> get_close_matches('accept', keyword.kwlist) ['except'] \end{verbatim} \end{funcdesc} \begin{funcdesc}{ndiff}{a, b\optional{, linejunk\optional{, charjunk}}} Compare \var{a} and \var{b} (lists of strings); return a \class{Differ}-style delta (a generator generating the delta lines). Optional keyword parameters \var{linejunk} and \var{charjunk} are for filter functions (or \code{None}): \var{linejunk}: A function that accepts a single string argument, and returns true if the string is junk, or false if not. The default is (\code{None}), starting with Python 2.3. Before then, the default was the module-level function \function{IS_LINE_JUNK()}, which filters out lines without visible characters, except for at most one pound character (\character{\#}). As of Python 2.3, the underlying \class{SequenceMatcher} class does a dynamic analysis of which lines are so frequent as to constitute noise, and this usually works better than the pre-2.3 default. \var{charjunk}: A function that accepts a character (a string of length 1), and returns if the character is junk, or false if not. The default is module-level function \function{IS_CHARACTER_JUNK()}, which filters out whitespace characters (a blank or tab; note: bad idea to include newline in this!). \file{Tools/scripts/ndiff.py} is a command-line front-end to this function. \begin{verbatim} >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), ... 'ore\ntree\nemu\n'.splitlines(1)) >>> print ''.join(diff), - one ? ^ + ore ? ^ - two - three ? - + tree + emu \end{verbatim} \end{funcdesc} \begin{funcdesc}{restore}{sequence, which} Return one of the two sequences that generated a delta. Given a \var{sequence} produced by \method{Differ.compare()} or \function{ndiff()}, extract lines originating from file 1 or 2 (parameter \var{which}), stripping off line prefixes. Example: \begin{verbatim} >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), ... 'ore\ntree\nemu\n'.splitlines(1)) >>> diff = list(diff) # materialize the generated delta into a list >>> print ''.join(restore(diff, 1)), one two three >>> print ''.join(restore(diff, 2)), ore tree emu \end{verbatim} \end{funcdesc} \begin{funcdesc}{unified_diff}{a, b\optional{, fromfile\optional{, tofile \optional{, fromfiledate\optional{, tofiledate\optional{, n \optional{, lineterm}}}}}}} Compare \var{a} and \var{b} (lists of strings); return a delta (a generator generating the delta lines) in unified diff format. Unified diffs are a compact way of showing just the lines that have changed plus a few lines of context. The changes are shown in a inline style (instead of separate before/after blocks). The number of context lines is set by \var{n} which defaults to three. By default, the diff control lines (those with \code{---}, \code{+++}, or \code{@@}) are created with a trailing newline. This is helpful so that inputs created from \function{file.readlines()} result in diffs that are suitable for use with \function{file.writelines()} since both the inputs and outputs have trailing newlines. For inputs that do not have trailing newlines, set the \var{lineterm} argument to \code{""} so that the output will be uniformly newline free. The context diff format normally has a header for filenames and modification times. Any or all of these may be specified using strings for \var{fromfile}, \var{tofile}, \var{fromfiledate}, and \var{tofiledate}. The modification times are normally expressed in the format returned by \function{time.ctime()}. If not specified, the strings default to blanks. \file{Tools/scripts/diff.py} is a command-line front-end for this function. \versionadded{2.3} \end{funcdesc} \begin{funcdesc}{IS_LINE_JUNK}{line} Return true for ignorable lines. The line \var{line} is ignorable if \var{line} is blank or contains a single \character{\#}, otherwise it is not ignorable. Used as a default for parameter \var{linejunk} in \function{ndiff()} before Python 2.3. \end{funcdesc} \begin{funcdesc}{IS_CHARACTER_JUNK}{ch} Return true for ignorable characters. The character \var{ch} is ignorable if \var{ch} is a space or tab, otherwise it is not ignorable. Used as a default for parameter \var{charjunk} in \function{ndiff()}. \end{funcdesc} \begin{seealso} \seetitle[http://www.ddj.com/documents/s=1103/ddj8807c/] {Pattern Matching: The Gestalt Approach}{Discussion of a similar algorithm by John W. Ratcliff and D. E. Metzener. This was published in \citetitle[http://www.ddj.com/]{Dr. Dobb's Journal} in July, 1988.} \end{seealso} \subsection{SequenceMatcher Objects \label{sequence-matcher}} The \class{SequenceMatcher} class has this constructor: \begin{classdesc}{SequenceMatcher}{\optional{isjunk\optional{, a\optional{, b}}}} Optional argument \var{isjunk} must be \code{None} (the default) or a one-argument function that takes a sequence element and returns true if and only if the element is ``junk'' and should be ignored. Passing \code{None} for \var{b} is equivalent to passing \code{lambda x: 0}; in other words, no elements are ignored. For example, pass: \begin{verbatim} lambda x: x in " \t" \end{verbatim} if you're comparing lines as sequences of characters, and don't want to synch up on blanks or hard tabs. The optional arguments \var{a} and \var{b} are sequences to be compared; both default to empty strings. The elements of both sequences must be hashable. \end{classdesc} \class{SequenceMatcher} objects have the following methods: \begin{methoddesc}{set_seqs}{a, b} Set the two sequences to be compared. \end{methoddesc} \class{SequenceMatcher} computes and caches detailed information about the second sequence, so if you want to compare one sequence against many sequences, use \method{set_seq2()} to set the commonly used sequence once and call \method{set_seq1()} repeatedly, once for each of the other sequences. \begin{methoddesc}{set_seq1}{a} Set the first sequence to be compared. The second sequence to be compared is not changed. \end{methoddesc} \begin{methoddesc}{set_seq2}{b} Set the second sequence to be compared. The first sequence to be compared is not changed. \end{methoddesc} \begin{methoddesc}{find_longest_match}{alo, ahi, blo, bhi} Find longest matching block in \code{\var{a}[\var{alo}:\var{ahi}]} and \code{\var{b}[\var{blo}:\var{bhi}]}. If \var{isjunk} was omitted or \code{None}, \method{get_longest_match()} returns \code{(\var{i}, \var{j}, \var{k})} such that \code{\var{a}[\var{i}:\var{i}+\var{k}]} is equal to \code{\var{b}[\var{j}:\var{j}+\var{k}]}, where \code{\var{alo} <= \var{i} <= \var{i}+\var{k} <= \var{ahi}} and \code{\var{blo} <= \var{j} <= \var{j}+\var{k} <= \var{bhi}}. For all \code{(\var{i'}, \var{j'}, \var{k'})} meeting those conditions, the additional conditions \code{\var{k} >= \var{k'}}, \code{\var{i} <= \var{i'}}, and if \code{\var{i} == \var{i'}}, \code{\var{j} <= \var{j'}} are also met. In other words, of all maximal matching blocks, return one that starts earliest in \var{a}, and of all those maximal matching blocks that start earliest in \var{a}, return the one that starts earliest in \var{b}. \begin{verbatim} >>> s = SequenceMatcher(None, " abcd", "abcd abcd") >>> s.find_longest_match(0, 5, 0, 9) (0, 4, 5) \end{verbatim} If \var{isjunk} was provided, first the longest matching block is determined as above, but with the additional restriction that no junk element appears in the block. Then that block is extended as far as possible by matching (only) junk elements on both sides. So the resulting block never matches on junk except as identical junk happens to be adjacent to an interesting match. Here's the same example as before, but considering blanks to be junk. That prevents \code{' abcd'} from matching the \code{' abcd'} at the tail end of the second sequence directly. Instead only the \code{'abcd'} can match, and matches the leftmost \code{'abcd'} in the second sequence: \begin{verbatim} >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd") >>> s.find_longest_match(0, 5, 0, 9) (1, 0, 4) \end{verbatim} If no blocks match, this returns \code{(\var{alo}, \var{blo}, 0)}. \end{methoddesc} \begin{methoddesc}{get_matching_blocks}{} Return list of triples describing matching subsequences. Each triple is of the form \code{(\var{i}, \var{j}, \var{n})}, and means that \code{\var{a}[\var{i}:\var{i}+\var{n}] == \var{b}[\var{j}:\var{j}+\var{n}]}. The triples are monotonically increasing in \var{i} and \var{j}. The last triple is a dummy, and has the value \code{(len(\var{a}), len(\var{b}), 0)}. It is the only triple with \code{\var{n} == 0}. % Explain why a dummy is used! \begin{verbatim} >>> s = SequenceMatcher(None, "abxcd", "abcd") >>> s.get_matching_blocks() [(0, 0, 2), (3, 2, 2), (5, 4, 0)] \end{verbatim} \end{methoddesc} \begin{methoddesc}{get_opcodes}{} Return list of 5-tuples describing how to turn \var{a} into \var{b}. Each tuple is of the form \code{(\var{tag}, \var{i1}, \var{i2}, \var{j1}, \var{j2})}. The first tuple has \code{\var{i1} == \var{j1} == 0}, and remaining tuples have \var{i1} equal to the \var{i2} from the preceeding tuple, and, likewise, \var{j1} equal to the previous \var{j2}. The \var{tag} values are strings, with these meanings: \begin{tableii}{l|l}{code}{Value}{Meaning} \lineii{'replace'}{\code{\var{a}[\var{i1}:\var{i2}]} should be replaced by \code{\var{b}[\var{j1}:\var{j2}]}.} \lineii{'delete'}{\code{\var{a}[\var{i1}:\var{i2}]} should be deleted. Note that \code{\var{j1} == \var{j2}} in this case.} \lineii{'insert'}{\code{\var{b}[\var{j1}:\var{j2}]} should be inserted at \code{\var{a}[\var{i1}:\var{i1}]}. Note that \code{\var{i1} == \var{i2}} in this case.} \lineii{'equal'}{\code{\var{a}[\var{i1}:\var{i2}] == \var{b}[\var{j1}:\var{j2}]} (the sub-sequences are equal).} \end{tableii} For example: \begin{verbatim} >>> a = "qabxcd" >>> b = "abycdf" >>> s = SequenceMatcher(None, a, b) >>> for tag, i1, i2, j1, j2 in s.get_opcodes(): ... print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])) delete a[0:1] (q) b[0:0] () equal a[1:3] (ab) b[0:2] (ab) replace a[3:4] (x) b[2:3] (y) equal a[4:6] (cd) b[3:5] (cd) insert a[6:6] () b[5:6] (f) \end{verbatim} \end{methoddesc} \begin{methoddesc}{get_grouped_opcodes}{\optional{n}} Return a generator of groups with up to \var{n} lines of context. Starting with the groups returned by \method{get_opcodes()}, this method splits out smaller change clusters and eliminates intervening ranges which have no changes. The groups are returned in the same format as \method{get_opcodes()}. \versionadded{2.3} \end{methoddesc} \begin{methoddesc}{ratio}{} Return a measure of the sequences' similarity as a float in the range [0, 1]. Where T is the total number of elements in both sequences, and M is the number of matches, this is 2.0*M / T. Note that this is \code{1.0} if the sequences are identical, and \code{0.0} if they have nothing in common. This is expensive to compute if \method{get_matching_blocks()} or \method{get_opcodes()} hasn't already been called, in which case you may want to try \method{quick_ratio()} or \method{real_quick_ratio()} first to get an upper bound. \end{methoddesc} \begin{methoddesc}{quick_ratio}{} Return an upper bound on \method{ratio()} relatively quickly. This isn't defined beyond that it is an upper bound on \method{ratio()}, and is faster to compute. \end{methoddesc} \begin{methoddesc}{real_quick_ratio}{} Return an upper bound on \method{ratio()} very quickly. This isn't defined beyond that it is an upper bound on \method{ratio()}, and is faster to compute than either \method{ratio()} or \method{quick_ratio()}. \end{methoddesc} The three methods that return the ratio of matching to total characters can give different results due to differing levels of approximation, although \method{quick_ratio()} and \method{real_quick_ratio()} are always at least as large as \method{ratio()}: \begin{verbatim} >>> s = SequenceMatcher(None, "abcd", "bcde") >>> s.ratio() 0.75 >>> s.quick_ratio() 0.75 >>> s.real_quick_ratio() 1.0 \end{verbatim} \subsection{SequenceMatcher Examples \label{sequencematcher-examples}} This example compares two strings, considering blanks to be ``junk:'' \begin{verbatim} >>> s = SequenceMatcher(lambda x: x == " ", ... "private Thread currentThread;", ... "private volatile Thread currentThread;") \end{verbatim} \method{ratio()} returns a float in [0, 1], measuring the similarity of the sequences. As a rule of thumb, a \method{ratio()} value over 0.6 means the sequences are close matches: \begin{verbatim} >>> print round(s.ratio(), 3) 0.866 \end{verbatim} If you're only interested in where the sequences match, \method{get_matching_blocks()} is handy: \begin{verbatim} >>> for block in s.get_matching_blocks(): ... print "a[%d] and b[%d] match for %d elements" % block a[0] and b[0] match for 8 elements a[8] and b[17] match for 6 elements a[14] and b[23] match for 15 elements a[29] and b[38] match for 0 elements \end{verbatim} Note that the last tuple returned by \method{get_matching_blocks()} is always a dummy, \code{(len(\var{a}), len(\var{b}), 0)}, and this is the only case in which the last tuple element (number of elements matched) is \code{0}. If you want to know how to change the first sequence into the second, use \method{get_opcodes()}: \begin{verbatim} >>> for opcode in s.get_opcodes(): ... print "%6s a[%d:%d] b[%d:%d]" % opcode equal a[0:8] b[0:8] insert a[8:8] b[8:17] equal a[8:14] b[17:23] equal a[14:29] b[23:38] \end{verbatim} See also the function \function{get_close_matches()} in this module, which shows how simple code building on \class{SequenceMatcher} can be used to do useful work. \subsection{Differ Objects \label{differ-objects}} Note that \class{Differ}-generated deltas make no claim to be \strong{minimal} diffs. To the contrary, minimal diffs are often counter-intuitive, because they synch up anywhere possible, sometimes accidental matches 100 pages apart. Restricting synch points to contiguous matches preserves some notion of locality, at the occasional cost of producing a longer diff. The \class{Differ} class has this constructor: \begin{classdesc}{Differ}{\optional{linejunk\optional{, charjunk}}} Optional keyword parameters \var{linejunk} and \var{charjunk} are for filter functions (or \code{None}): \var{linejunk}: A function that accepts a single string argument, and returns true if the string is junk. The default is \code{None}, meaning that no line is considered junk. \var{charjunk}: A function that accepts a single character argument (a string of length 1), and returns true if the character is junk. The default is \code{None}, meaning that no character is considered junk. \end{classdesc} \class{Differ} objects are used (deltas generated) via a single method: \begin{methoddesc}{compare}{a, b} Compare two sequences of lines, and generate the delta (a sequence of lines). Each sequence must contain individual single-line strings ending with newlines. Such sequences can be obtained from the \method{readlines()} method of file-like objects. The delta generated also consists of newline-terminated strings, ready to be printed as-is via the \method{writelines()} method of a file-like object. \end{methoddesc} \subsection{Differ Example \label{differ-examples}} This example compares two texts. First we set up the texts, sequences of individual single-line strings ending with newlines (such sequences can also be obtained from the \method{readlines()} method of file-like objects): \begin{verbatim} >>> text1 = ''' 1. Beautiful is better than ugly. ... 2. Explicit is better than implicit. ... 3. Simple is better than complex. ... 4. Complex is better than complicated. ... '''.splitlines(1) >>> len(text1) 4 >>> text1[0][-1] '\n' >>> text2 = ''' 1. Beautiful is better than ugly. ... 3. Simple is better than complex. ... 4. Complicated is better than complex. ... 5. Flat is better than nested. ... '''.splitlines(1) \end{verbatim} Next we instantiate a Differ object: \begin{verbatim} >>> d = Differ() \end{verbatim} Note that when instantiating a \class{Differ} object we may pass functions to filter out line and character ``junk.'' See the \method{Differ()} constructor for details. Finally, we compare the two: \begin{verbatim} >>> result = list(d.compare(text1, text2)) \end{verbatim} \code{result} is a list of strings, so let's pretty-print it: \begin{verbatim} >>> from pprint import pprint >>> pprint(result) [' 1. Beautiful is better than ugly.\n', '- 2. Explicit is better than implicit.\n', '- 3. Simple is better than complex.\n', '+ 3. Simple is better than complex.\n', '? ++ \n', '- 4. Complex is better than complicated.\n', '? ^ ---- ^ \n', '+ 4. Complicated is better than complex.\n', '? ++++ ^ ^ \n', '+ 5. Flat is better than nested.\n'] \end{verbatim} As a single multi-line string it looks like this: \begin{verbatim} >>> import sys >>> sys.stdout.writelines(result) 1. Beautiful is better than ugly. - 2. Explicit is better than implicit. - 3. Simple is better than complex. + 3. Simple is better than complex. ? ++ - 4. Complex is better than complicated. ? ^ ---- ^ + 4. Complicated is better than complex. ? ++++ ^ ^ + 5. Flat is better than nested. \end{verbatim}