cmQtAutoGeneratorInitializer.cxx 38.1 KB
Newer Older
1
2
/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
   file Copyright.txt or https://cmake.org/licensing for details.  */
3
#include "cmQtAutoGeneratorInitializer.h"
4
#include "cmQtAutoGeneratorCommon.h"
5

6
7
#include "cmAlgorithms.h"
#include "cmCustomCommandLines.h"
8
#include "cmFilePathChecksum.h"
9
#include "cmGeneratorTarget.h"
10
#include "cmGlobalGenerator.h"
11
12
#include "cmLocalGenerator.h"
#include "cmMakefile.h"
13
#include "cmOutputConverter.h"
14
#include "cmSourceFile.h"
Daniel Pfeifer's avatar
Daniel Pfeifer committed
15
#include "cmSourceGroup.h"
16
#include "cmState.h"
17
18
#include "cmSystemTools.h"
#include "cmTarget.h"
19
#include "cm_sys_stat.h"
20
#include "cmake.h"
21
22

#if defined(_WIN32) && !defined(__CYGWIN__)
23
#include "cmGlobalVisualStudioGenerator.h"
24
25
#endif

26
27
#include "cmConfigure.h"
#include "cmsys/FStream.hxx"
28
29
30
31
32
33
34
#include <algorithm>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>

35
36
37
38
39
40
41
42
43
44
static void utilCopyTargetProperty(cmTarget* destinationTarget,
                                   cmTarget* sourceTarget,
                                   const std::string& propertyName)
{
  const char* propertyValue = sourceTarget->GetProperty(propertyName);
  if (propertyValue) {
    destinationTarget->SetProperty(propertyName, propertyValue);
  }
}

45
46
47
48
49
inline static bool PropertyEnabled(cmSourceFile* sourceFile, const char* key)
{
  return cmSystemTools::IsOn(sourceFile->GetPropertyForUser(key));
}

50
51
52
53
54
55
56
static std::string GetSafeProperty(cmGeneratorTarget const* target,
                                   const char* key)
{
  const char* tmp = target->GetProperty(key);
  return std::string((tmp != CM_NULLPTR) ? tmp : "");
}

57
58
59
static std::string GetAutogenTargetName(cmGeneratorTarget const* target)
{
  std::string autogenTargetName = target->GetName();
60
  autogenTargetName += "_autogen";
61
62
63
  return autogenTargetName;
}

64
static std::string GetAutogenTargetFilesDir(cmGeneratorTarget const* target)
65
66
67
68
69
70
{
  cmMakefile* makefile = target->Target->GetMakefile();
  std::string targetDir = makefile->GetCurrentBinaryDirectory();
  targetDir += makefile->GetCMakeInstance()->GetCMakeFilesDirectory();
  targetDir += "/";
  targetDir += GetAutogenTargetName(target);
71
  targetDir += ".dir";
72
73
74
75
76
  return targetDir;
}

static std::string GetAutogenTargetBuildDir(cmGeneratorTarget const* target)
{
77
78
79
80
81
82
83
  std::string targetDir = GetSafeProperty(target, "AUTOGEN_BUILD_DIR");
  if (targetDir.empty()) {
    cmMakefile* makefile = target->Target->GetMakefile();
    targetDir = makefile->GetCurrentBinaryDirectory();
    targetDir += "/";
    targetDir += GetAutogenTargetName(target);
  }
84
85
86
  return targetDir;
}

87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
static std::string GetQtMajorVersion(cmGeneratorTarget const* target)
{
  cmMakefile* makefile = target->Target->GetMakefile();
  std::string qtMajorVersion = makefile->GetSafeDefinition("QT_VERSION_MAJOR");
  if (qtMajorVersion.empty()) {
    qtMajorVersion = makefile->GetSafeDefinition("Qt5Core_VERSION_MAJOR");
  }
  const char* targetQtVersion =
    target->GetLinkInterfaceDependentStringProperty("QT_MAJOR_VERSION", "");
  if (targetQtVersion != CM_NULLPTR) {
    qtMajorVersion = targetQtVersion;
  }
  return qtMajorVersion;
}

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
static std::string GetQtMinorVersion(cmGeneratorTarget const* target,
                                     const std::string& qtMajorVersion)
{
  cmMakefile* makefile = target->Target->GetMakefile();
  std::string qtMinorVersion;
  if (qtMajorVersion == "5") {
    qtMinorVersion = makefile->GetSafeDefinition("Qt5Core_VERSION_MINOR");
  }
  if (qtMinorVersion.empty()) {
    qtMinorVersion = makefile->GetSafeDefinition("QT_VERSION_MINOR");
  }

  const char* targetQtVersion =
    target->GetLinkInterfaceDependentStringProperty("QT_MINOR_VERSION", "");
  if (targetQtVersion != CM_NULLPTR) {
    qtMinorVersion = targetQtVersion;
  }
  return qtMinorVersion;
}

static bool QtVersionGreaterOrEqual(const std::string& major,
                                    const std::string& minor,
                                    unsigned long requestMajor,
                                    unsigned long requestMinor)
{
  unsigned long majorUL(0);
  unsigned long minorUL(0);
  if (cmSystemTools::StringToULong(major.c_str(), &majorUL) &&
      cmSystemTools::StringToULong(minor.c_str(), &minorUL)) {
    return (majorUL > requestMajor) ||
      (majorUL == requestMajor && minorUL >= requestMinor);
  }
  return false;
}

137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
static void GetCompileDefinitionsAndDirectories(
  cmGeneratorTarget const* target, const std::string& config,
  std::string& incs, std::string& defs)
{
  cmLocalGenerator* localGen = target->GetLocalGenerator();
  {
    std::vector<std::string> includeDirs;
    // Get the include dirs for this target, without stripping the implicit
    // include dirs off, see
    // https://gitlab.kitware.com/cmake/cmake/issues/13667
    localGen->GetIncludeDirectories(includeDirs, target, "CXX", config, false);
    incs = cmJoin(includeDirs, ";");
  }
  {
    std::set<std::string> defines;
    localGen->AddCompileDefinitions(defines, target, config, "CXX");
    defs += cmJoin(defines, ";");
  }
}

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
static bool IsMultiConfig(cmGlobalGenerator* globalGen)
{
  // FIXME: Xcode does not support per-config sources, yet.
  //        (EXCLUDED_SOURCE_FILE_NAMES)
  //        Treat it as a single configuration generator meanwhile.
  if (globalGen->GetName().find("Xcode") != std::string::npos) {
    return false;
  }
  return globalGen->IsMultiConfig();
}

static std::vector<std::string> GetConfigurations(
  cmMakefile* makefile, std::string* config = CM_NULLPTR)
{
  std::vector<std::string> configs;
  {
    std::string cfg = makefile->GetConfigurations(configs);
    if (config != CM_NULLPTR) {
      *config = cfg;
    }
  }
  // Add empty configuration on demand
  if (configs.empty()) {
    configs.push_back("");
  }
  return configs;
}

static std::vector<std::string> GetConfigurationSuffixes(cmMakefile* makefile)
{
  std::vector<std::string> suffixes;
  if (IsMultiConfig(makefile->GetGlobalGenerator())) {
    makefile->GetConfigurations(suffixes);
    for (std::vector<std::string>::iterator it = suffixes.begin();
         it != suffixes.end(); ++it) {
      it->insert(0, "_");
    }
  }
  if (suffixes.empty()) {
    suffixes.push_back("");
  }
  return suffixes;
}

201
202
203
204
205
206
207
208
209
210
211
212
213
214
static void AddDefinitionEscaped(cmMakefile* makefile, const char* key,
                                 const std::string& value)
{
  makefile->AddDefinition(key,
                          cmOutputConverter::EscapeForCMake(value).c_str());
}

static void AddDefinitionEscaped(cmMakefile* makefile, const char* key,
                                 const std::vector<std::string>& values)
{
  makefile->AddDefinition(
    key, cmOutputConverter::EscapeForCMake(cmJoin(values, ";")).c_str());
}

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
static bool AddToSourceGroup(cmMakefile* makefile, const std::string& fileName,
                             cmQtAutoGeneratorCommon::GeneratorType genType)
{
  cmSourceGroup* sourceGroup = CM_NULLPTR;
  // Acquire source group
  {
    const char* groupName = CM_NULLPTR;
    // Use generator specific group name
    switch (genType) {
      case cmQtAutoGeneratorCommon::MOC:
        groupName =
          makefile->GetState()->GetGlobalProperty("AUTOMOC_SOURCE_GROUP");
        break;
      case cmQtAutoGeneratorCommon::RCC:
        groupName =
          makefile->GetState()->GetGlobalProperty("AUTORCC_SOURCE_GROUP");
        break;
      default:
        break;
    }
    // Use default group name on demand
    if ((groupName == CM_NULLPTR) || (*groupName == 0)) {
      groupName =
        makefile->GetState()->GetGlobalProperty("AUTOGEN_SOURCE_GROUP");
    }
    // Generate a source group on demand
    if ((groupName != CM_NULLPTR) && (*groupName != 0)) {
      {
        const char* delimiter =
          makefile->GetDefinition("SOURCE_GROUP_DELIMITER");
        if (delimiter == CM_NULLPTR) {
          delimiter = "\\";
        }
        std::vector<std::string> folders =
          cmSystemTools::tokenize(groupName, delimiter);
        sourceGroup = makefile->GetSourceGroup(folders);
        if (sourceGroup == CM_NULLPTR) {
          makefile->AddSourceGroup(folders);
          sourceGroup = makefile->GetSourceGroup(folders);
        }
      }
      if (sourceGroup == CM_NULLPTR) {
        cmSystemTools::Error(
          "Autogen: Could not create or find source group: ",
          cmQtAutoGeneratorCommon::Quoted(groupName).c_str());
        return false;
      }
    }
  }
  if (sourceGroup != CM_NULLPTR) {
    sourceGroup->AddGroupFile(fileName);
  }
  return true;
}

270
271
272
273
274
275
276
277
278
279
280
static void AddGeneratedSource(cmMakefile* makefile,
                               const std::string& filename,
                               cmQtAutoGeneratorCommon::GeneratorType genType)
{
  cmSourceFile* gFile = makefile->GetOrCreateSource(filename, true);
  gFile->SetProperty("GENERATED", "1");
  gFile->SetProperty("SKIP_AUTOGEN", "On");

  AddToSourceGroup(makefile, filename, genType);
}

281
static void AcquireScanFiles(cmGeneratorTarget const* target,
282
283
                             std::vector<std::string>& mocUicSources,
                             std::vector<std::string>& mocUicHeaders,
284
285
                             std::vector<std::string>& mocSkipList,
                             std::vector<std::string>& uicSkipList)
286
{
287
288
  const bool mocTarget = target->GetPropertyAsBool("AUTOMOC");
  const bool uicTarget = target->GetPropertyAsBool("AUTOUIC");
289

290
291
  std::vector<cmSourceFile*> srcFiles;
  target->GetConfigCommonSourceFiles(srcFiles);
292
293
  for (std::vector<cmSourceFile*>::const_iterator fileIt = srcFiles.begin();
       fileIt != srcFiles.end(); ++fileIt) {
294
    cmSourceFile* sf = *fileIt;
295
296
297
298
299
300
301
    const cmSystemTools::FileFormat fileType =
      cmSystemTools::GetFileFormat(sf->GetExtension().c_str());

    if (!(fileType == cmSystemTools::CXX_FILE_FORMAT) &&
        !(fileType == cmSystemTools::HEADER_FILE_FORMAT)) {
      continue;
    }
302
303
    const std::string absFile =
      cmsys::SystemTools::GetRealPath(sf->GetFullPath());
304
    // Skip flags
305
306
307
    const bool skipAll = PropertyEnabled(sf, "SKIP_AUTOGEN");
    const bool mocSkip = skipAll || PropertyEnabled(sf, "SKIP_AUTOMOC");
    const bool uicSkip = skipAll || PropertyEnabled(sf, "SKIP_AUTOUIC");
308
309
310
311
    // Add file name to skip lists.
    // Do this even when the file is not added to the sources/headers lists
    // because the file name may be extracted from an other file when
    // processing
312
313
    if (mocSkip) {
      mocSkipList.push_back(absFile);
314
    }
315
316
    if (uicSkip) {
      uicSkipList.push_back(absFile);
317
    }
318

319
    if ((mocTarget && !mocSkip) || (uicTarget && !uicSkip)) {
320
321
322
323
324
325
326
327
328
329
330
      // Add file name to sources or headers list
      switch (fileType) {
        case cmSystemTools::CXX_FILE_FORMAT:
          mocUicSources.push_back(absFile);
          break;
        case cmSystemTools::HEADER_FILE_FORMAT:
          mocUicHeaders.push_back(absFile);
          break;
        default:
          break;
      }
331
    }
332
  }
333
334
}

335
static void MocSetupAutoTarget(
336
  cmGeneratorTarget const* target, const std::string& autogenTargetName,
337
338
  std::string const& qtMajorVersion, std::string const& config,
  std::vector<std::string> const& configs,
339
  std::vector<std::string> const& mocSkipList,
340
341
  std::map<std::string, std::string>& configMocIncludes,
  std::map<std::string, std::string>& configMocDefines)
342
{
343
  cmLocalGenerator* lg = target->GetLocalGenerator();
344
  cmMakefile* makefile = target->Target->GetMakefile();
345

346
347
348
349
350
351
  AddDefinitionEscaped(makefile, "_moc_options",
                       GetSafeProperty(target, "AUTOMOC_MOC_OPTIONS"));
  AddDefinitionEscaped(makefile, "_moc_skip", mocSkipList);
  AddDefinitionEscaped(makefile, "_moc_relaxed_mode",
                       makefile->IsOn("CMAKE_AUTOMOC_RELAXED_MODE") ? "TRUE"
                                                                    : "FALSE");
352
353
  AddDefinitionEscaped(makefile, "_moc_depend_filters",
                       GetSafeProperty(target, "AUTOMOC_DEPEND_FILTERS"));
354

355
356
357
358
359
360
  if (QtVersionGreaterOrEqual(
        qtMajorVersion, GetQtMinorVersion(target, qtMajorVersion), 5, 8)) {
    AddDefinitionEscaped(
      makefile, "_moc_predefs_cmd",
      makefile->GetSafeDefinition("CMAKE_CXX_COMPILER_PREDEFINES_COMMAND"));
  }
361
362
  // Moc includes and compile definitions
  {
363
364
365
366
367
368
369
370
    // Default settings
    std::string incs;
    std::string compileDefs;
    GetCompileDefinitionsAndDirectories(target, config, incs, compileDefs);
    AddDefinitionEscaped(makefile, "_moc_incs", incs);
    AddDefinitionEscaped(makefile, "_moc_compile_defs", compileDefs);

    // Configuration specific settings
371
372
    for (std::vector<std::string>::const_iterator li = configs.begin();
         li != configs.end(); ++li) {
373
374
375
376
377
378
      std::string configIncs;
      std::string configCompileDefs;
      GetCompileDefinitionsAndDirectories(target, *li, configIncs,
                                          configCompileDefs);
      if (configIncs != incs) {
        configMocIncludes[*li] = cmOutputConverter::EscapeForCMake(configIncs);
379
      }
380
381
382
      if (configCompileDefs != compileDefs) {
        configMocDefines[*li] =
          cmOutputConverter::EscapeForCMake(configCompileDefs);
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
  // Moc executable
  {
    std::string err;
    const char* mocExec = CM_NULLPTR;
    if (qtMajorVersion == "5") {
      cmGeneratorTarget* qt5Moc = lg->FindGeneratorTargetToUse("Qt5::moc");
      if (qt5Moc != CM_NULLPTR) {
        mocExec = qt5Moc->ImportedGetLocation("");
      } else {
        err = "Qt5::moc target not found " + autogenTargetName;
      }
    } else if (qtMajorVersion == "4") {
      cmGeneratorTarget* qt4Moc = lg->FindGeneratorTargetToUse("Qt4::moc");
      if (qt4Moc != CM_NULLPTR) {
        mocExec = qt4Moc->ImportedGetLocation("");
      } else {
        err = "Qt4::moc target not found " + autogenTargetName;
      }
    } else {
      err = "The CMAKE_AUTOMOC feature supports only Qt 4 and Qt 5 ";
      err += autogenTargetName;
408
    }
409
410
411
412
413
414
    // Add definition or error
    if (err.empty()) {
      AddDefinitionEscaped(makefile, "_qt_moc_executable",
                           mocExec ? mocExec : "");
    } else {
      cmSystemTools::Error(err.c_str());
415
416
    }
  }
417
418
}

419
static void UicGetOpts(cmGeneratorTarget const* target,
420
                       const std::string& config, std::string& optString)
421
422
{
  std::vector<std::string> opts;
423
  target->GetAutoUicOptions(opts, config);
424
425
426
  optString = cmJoin(opts, ";");
}

427
static void UicSetupAutoTarget(
428
429
  cmGeneratorTarget const* target, std::string const& qtMajorVersion,
  std::string const& config, std::vector<std::string> const& configs,
430
  std::vector<std::string> const& uicSkipList,
431
  std::map<std::string, std::string>& configUicOptions)
432
{
433
  cmLocalGenerator* lg = target->GetLocalGenerator();
434
  cmMakefile* makefile = target->Target->GetMakefile();
435

436
  AddDefinitionEscaped(makefile, "_uic_skip", uicSkipList);
437

438
439
440
441
442
443
444
445
446
447
448
449
  // Uic search paths
  {
    std::vector<std::string> uicSearchPaths;
    cmSystemTools::ExpandListArgument(
      GetSafeProperty(target, "AUTOUIC_SEARCH_PATHS"), uicSearchPaths);
    const std::string srcDir = makefile->GetCurrentSourceDirectory();
    for (std::vector<std::string>::iterator it = uicSearchPaths.begin();
         it != uicSearchPaths.end(); ++it) {
      *it = cmSystemTools::CollapseFullPath(*it, srcDir);
    }
    AddDefinitionEscaped(makefile, "_uic_search_paths", uicSearchPaths);
  }
450
451
  // Uic target options
  {
452
453
454
455
    // Default settings
    std::string uicOpts;
    UicGetOpts(target, config, uicOpts);
    AddDefinitionEscaped(makefile, "_uic_target_options", uicOpts);
456

457
    // Configuration specific settings
458
459
    for (std::vector<std::string>::const_iterator li = configs.begin();
         li != configs.end(); ++li) {
460
461
462
      std::string configUicOpts;
      UicGetOpts(target, *li, configUicOpts);
      if (configUicOpts != uicOpts) {
463
        configUicOptions[*li] =
464
          cmOutputConverter::EscapeForCMake(configUicOpts);
465
466
      }
    }
467
  }
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
  // Uic files options
  {
    std::vector<std::string> uiFileFiles;
    std::vector<std::string> uiFileOptions;
    {
      std::set<std::string> skipped;
      skipped.insert(uicSkipList.begin(), uicSkipList.end());

      const std::vector<cmSourceFile*> uiFilesWithOptions =
        makefile->GetQtUiFilesWithOptions();
      for (std::vector<cmSourceFile*>::const_iterator fileIt =
             uiFilesWithOptions.begin();
           fileIt != uiFilesWithOptions.end(); ++fileIt) {
        cmSourceFile* sf = *fileIt;
        const std::string absFile =
          cmsys::SystemTools::GetRealPath(sf->GetFullPath());
        if (skipped.insert(absFile).second) {
          // The file wasn't skipped
          uiFileFiles.push_back(absFile);
          {
            std::string opts = sf->GetProperty("AUTOUIC_OPTIONS");
489
490
            cmSystemTools::ReplaceString(opts, ";",
                                         cmQtAutoGeneratorCommon::listSep);
491
492
493
494
            uiFileOptions.push_back(opts);
          }
        }
      }
495
    }
496
497
    AddDefinitionEscaped(makefile, "_qt_uic_options_files", uiFileFiles);
    AddDefinitionEscaped(makefile, "_qt_uic_options_options", uiFileOptions);
498
  }
499

500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
  // Uic executable
  {
    std::string err;
    const char* uicExec = CM_NULLPTR;
    if (qtMajorVersion == "5") {
      cmGeneratorTarget* qt5Uic = lg->FindGeneratorTargetToUse("Qt5::uic");
      if (qt5Uic != CM_NULLPTR) {
        uicExec = qt5Uic->ImportedGetLocation("");
      } else {
        // Project does not use Qt5Widgets, but has AUTOUIC ON anyway
      }
    } else if (qtMajorVersion == "4") {
      cmGeneratorTarget* qt4Uic = lg->FindGeneratorTargetToUse("Qt4::uic");
      if (qt4Uic != CM_NULLPTR) {
        uicExec = qt4Uic->ImportedGetLocation("");
      } else {
        err = "Qt4::uic target not found " + target->GetName();
      }
518
    } else {
519
520
      err = "The CMAKE_AUTOUIC feature supports only Qt 4 and Qt 5 ";
      err += target->GetName();
521
    }
522
523
524
525
526
527
    // Add definition or error
    if (err.empty()) {
      AddDefinitionEscaped(makefile, "_qt_uic_executable",
                           uicExec ? uicExec : "");
    } else {
      cmSystemTools::Error(err.c_str());
528
529
    }
  }
530
531
}

532
533
static std::string RccGetExecutable(cmGeneratorTarget const* target,
                                    const std::string& qtMajorVersion)
534
{
535
  std::string rccExec;
536
  cmLocalGenerator* lg = target->GetLocalGenerator();
537
  if (qtMajorVersion == "5") {
538
    cmGeneratorTarget* qt5Rcc = lg->FindGeneratorTargetToUse("Qt5::rcc");
539
540
541
542
543
    if (qt5Rcc != CM_NULLPTR) {
      rccExec = qt5Rcc->ImportedGetLocation("");
    } else {
      cmSystemTools::Error("Qt5::rcc target not found ",
                           target->GetName().c_str());
544
    }
545
  } else if (qtMajorVersion == "4") {
546
    cmGeneratorTarget* qt4Rcc = lg->FindGeneratorTargetToUse("Qt4::rcc");
547
548
549
550
551
    if (qt4Rcc != CM_NULLPTR) {
      rccExec = qt4Rcc->ImportedGetLocation("");
    } else {
      cmSystemTools::Error("Qt4::rcc target not found ",
                           target->GetName().c_str());
552
    }
553
554
555
556
  } else {
    cmSystemTools::Error(
      "The CMAKE_AUTORCC feature supports only Qt 4 and Qt 5 ",
      target->GetName().c_str());
557
  }
558
  return rccExec;
559
560
}

561
static void RccMergeOptions(std::vector<std::string>& opts,
562
563
                            const std::vector<std::string>& fileOpts,
                            bool isQt5)
564
{
565
566
  static const char* valueOptions[] = { "name", "root", "compress",
                                        "threshold" };
567
  std::vector<std::string> extraOpts;
568
569
  for (std::vector<std::string>::const_iterator fit = fileOpts.begin();
       fit != fileOpts.end(); ++fit) {
570
    std::vector<std::string>::iterator existingIt =
571
      std::find(opts.begin(), opts.end(), *fit);
572
    if (existingIt != opts.end()) {
573
574
575
576
577
578
      const char* optName = fit->c_str();
      if (*optName == '-') {
        ++optName;
        if (isQt5 && *optName == '-') {
          ++optName;
        }
579
      }
580
581
582
583
584
585
586
587
588
589
      // Test if this is a value option and change the existing value
      if ((optName != fit->c_str()) &&
          std::find_if(cmArrayBegin(valueOptions), cmArrayEnd(valueOptions),
                       cmStrCmp(optName)) != cmArrayEnd(valueOptions)) {
        const std::vector<std::string>::iterator existValueIt(existingIt + 1);
        const std::vector<std::string>::const_iterator fileValueIt(fit + 1);
        if ((existValueIt != opts.end()) && (fileValueIt != fileOpts.end())) {
          *existValueIt = *fileValueIt;
          ++fit;
        }
590
      }
591
    } else {
592
      extraOpts.push_back(*fit);
593
    }
594
  }
595
596
597
  opts.insert(opts.end(), extraOpts.begin(), extraOpts.end());
}

598
599
static void RccSetupAutoTarget(cmGeneratorTarget const* target,
                               const std::string& qtMajorVersion)
600
{
601
  cmMakefile* makefile = target->Target->GetMakefile();
602
  const bool qtMajorVersion5 = (qtMajorVersion == "5");
603
  const std::string rccCommand = RccGetExecutable(target, qtMajorVersion);
604
605
606
607
608
  std::vector<std::string> _rcc_files;
  std::vector<std::string> _rcc_inputs;
  std::vector<std::string> rccFileFiles;
  std::vector<std::string> rccFileOptions;
  std::vector<std::string> rccOptionsTarget;
609
  if (const char* opts = target->GetProperty("AUTORCC_OPTIONS")) {
610
    cmSystemTools::ExpandListArgument(opts, rccOptionsTarget);
611
  }
612

613
614
  std::vector<cmSourceFile*> srcFiles;
  target->GetConfigCommonSourceFiles(srcFiles);
615
616
  for (std::vector<cmSourceFile*>::const_iterator fileIt = srcFiles.begin();
       fileIt != srcFiles.end(); ++fileIt) {
617
    cmSourceFile* sf = *fileIt;
618
    if ((sf->GetExtension() == "qrc") &&
619
620
        !PropertyEnabled(sf, "SKIP_AUTOGEN") &&
        !PropertyEnabled(sf, "SKIP_AUTORCC")) {
621
622
623
624
625
626
627
628
      const std::string absFile =
        cmsys::SystemTools::GetRealPath(sf->GetFullPath());
      // qrc file
      _rcc_files.push_back(absFile);
      // qrc file entries
      {
        std::string entriesList = "{";
        // Read input file list only for non generated .qrc files.
629
        if (!PropertyEnabled(sf, "GENERATED")) {
630
631
632
633
634
635
636
          std::string error;
          std::vector<std::string> files;
          if (cmQtAutoGeneratorCommon::RccListInputs(
                qtMajorVersion, rccCommand, absFile, files, &error)) {
            entriesList += cmJoin(files, cmQtAutoGeneratorCommon::listSep);
          } else {
            cmSystemTools::Error(error.c_str());
637
          }
638
        }
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
        entriesList += "}";
        _rcc_inputs.push_back(entriesList);
      }
      // rcc options for this qrc file
      {
        // Merged target and file options
        std::vector<std::string> rccOptions(rccOptionsTarget);
        if (const char* prop = sf->GetProperty("AUTORCC_OPTIONS")) {
          std::vector<std::string> optsVec;
          cmSystemTools::ExpandListArgument(prop, optsVec);
          RccMergeOptions(rccOptions, optsVec, qtMajorVersion5);
        }
        // Only store non empty options lists
        if (!rccOptions.empty()) {
          rccFileFiles.push_back(absFile);
          rccFileOptions.push_back(
            cmJoin(rccOptions, cmQtAutoGeneratorCommon::listSep));
656
        }
657
658
      }
    }
659
  }
660

661
  AddDefinitionEscaped(makefile, "_qt_rcc_executable", rccCommand);
662
663
664
665
  AddDefinitionEscaped(makefile, "_rcc_files", _rcc_files);
  AddDefinitionEscaped(makefile, "_rcc_inputs", _rcc_inputs);
  AddDefinitionEscaped(makefile, "_rcc_options_files", rccFileFiles);
  AddDefinitionEscaped(makefile, "_rcc_options_options", rccFileOptions);
666
}
667

668
void cmQtAutoGeneratorInitializer::InitializeAutogenSources(
669
  cmGeneratorTarget* target)
670
{
671
  if (target->GetPropertyAsBool("AUTOMOC")) {
672
    cmMakefile* makefile = target->Target->GetMakefile();
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
    const std::vector<std::string> suffixes =
      GetConfigurationSuffixes(makefile);
    // Get build directory
    const std::string autogenBuildDir = GetAutogenTargetBuildDir(target);
    // Register all compilation files as generated
    for (std::vector<std::string>::const_iterator it = suffixes.begin();
         it != suffixes.end(); ++it) {
      std::string mcFile = autogenBuildDir + "/mocs_compilation";
      mcFile += *it;
      mcFile += ".cpp";
      AddGeneratedSource(makefile, mcFile, cmQtAutoGeneratorCommon::MOC);
    }
    // Mocs compilation file
    if (IsMultiConfig(target->GetGlobalGenerator())) {
      target->AddSource(autogenBuildDir + "/mocs_compilation_$<CONFIG>.cpp");
    } else {
      target->AddSource(autogenBuildDir + "/mocs_compilation.cpp");
690
    }
691
  }
692
693
694
}

void cmQtAutoGeneratorInitializer::InitializeAutogenTarget(
695
  cmLocalGenerator* lg, cmGeneratorTarget* target)
696
{
697
  cmMakefile* makefile = target->Target->GetMakefile();
698

699
  // Create a custom target for running generators at buildtime
700
701
702
  const bool mocEnabled = target->GetPropertyAsBool("AUTOMOC");
  const bool uicEnabled = target->GetPropertyAsBool("AUTOUIC");
  const bool rccEnabled = target->GetPropertyAsBool("AUTORCC");
703
  const bool multiConfig = IsMultiConfig(target->GetGlobalGenerator());
704
  const std::string autogenTargetName = GetAutogenTargetName(target);
705
  const std::string autogenBuildDir = GetAutogenTargetBuildDir(target);
706
707
  const std::string workingDirectory =
    cmSystemTools::CollapseFullPath("", makefile->GetCurrentBinaryDirectory());
708
  const std::string qtMajorVersion = GetQtMajorVersion(target);
709
  const std::string rccCommand = RccGetExecutable(target, qtMajorVersion);
710
  const std::vector<std::string> suffixes = GetConfigurationSuffixes(makefile);
711
712
  std::vector<std::string> autogenDepends;
  std::vector<std::string> autogenProvides;
713

714
715
716
717
  // Remove build directories on cleanup
  makefile->AppendProperty("ADDITIONAL_MAKE_CLEAN_FILES",
                           autogenBuildDir.c_str(), false);

718
719
  // Remove old settings on cleanup
  {
720
721
722
723
724
725
726
    std::string base = GetAutogenTargetFilesDir(target);
    for (std::vector<std::string>::const_iterator it = suffixes.begin();
         it != suffixes.end(); ++it) {
      std::string fname = base + "/AutogenOldSettings" + *it + ".cmake";
      makefile->AppendProperty("ADDITIONAL_MAKE_CLEAN_FILES", fname.c_str(),
                               false);
    }
727
728
  }

729
730
731
732
733
734
735
736
737
738
  // Compose command lines
  cmCustomCommandLines commandLines;
  {
    cmCustomCommandLine currentLine;
    currentLine.push_back(cmSystemTools::GetCMakeCommand());
    currentLine.push_back("-E");
    currentLine.push_back("cmake_autogen");
    currentLine.push_back(GetAutogenTargetFilesDir(target));
    currentLine.push_back("$<CONFIGURATION>");
    commandLines.push_back(currentLine);
739
  }
740

741
742
743
744
  // Compose target comment
  std::string autogenComment;
  {
    std::vector<std::string> toolNames;
745
    if (mocEnabled) {
746
      toolNames.push_back("MOC");
747
    }
748
    if (uicEnabled) {
749
      toolNames.push_back("UIC");
750
    }
751
    if (rccEnabled) {
752
      toolNames.push_back("RCC");
753
754
755
    }

    std::string tools = toolNames[0];
756
    toolNames.erase(toolNames.begin());
757
758
759
760
761
762
763
764
    while (toolNames.size() > 1) {
      tools += ", " + toolNames[0];
      toolNames.erase(toolNames.begin());
    }
    if (toolNames.size() == 1) {
      tools += " and " + toolNames[0];
    }
    autogenComment = "Automatic " + tools + " for target " + target->GetName();
765
  }
766

767
768
769
770
771
772
773
774
775
776
  // Add moc compilation to generated files list
  if (mocEnabled) {
    for (std::vector<std::string>::const_iterator it = suffixes.begin();
         it != suffixes.end(); ++it) {
      std::string mcFile = autogenBuildDir + "/mocs_compilation";
      mcFile += *it;
      mcFile += ".cpp";
      autogenProvides.push_back(mcFile);
    }
  }
777

778
  // Add autogen includes directory to the origin target INCLUDE_DIRECTORIES
779
  if (mocEnabled || uicEnabled) {
780
781
782
    if (multiConfig) {
      target->AddIncludeDirectory(autogenBuildDir + "/include_$<CONFIG>",
                                  true);
783

784
785
786
    } else {
      target->AddIncludeDirectory(autogenBuildDir + "/include", true);
    }
787
788
  }

789
790
791
#if defined(_WIN32) && !defined(__CYGWIN__)
  bool usePRE_BUILD = false;
  cmGlobalGenerator* gg = lg->GetGlobalGenerator();
792
  if (gg->GetName().find("Visual Studio") != std::string::npos) {
793
    // Under VS use a PRE_BUILD event instead of a separate target to
794
795
796
    // reduce the number of targets loaded into the IDE.
    // This also works around a VS 11 bug that may skip updating the target:
    //  https://connect.microsoft.com/VisualStudio/feedback/details/769495
797
    usePRE_BUILD = true;
798
  }
799
800
#endif

801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
  // Initialize autogen target dependencies
  if (const char* deps = target->GetProperty("AUTOGEN_TARGET_DEPENDS")) {
    cmSystemTools::ExpandListArgument(deps, autogenDepends);
  }
  // Add link library targets to the autogen dependencies
  {
    const cmTarget::LinkLibraryVectorType& libVec =
      target->Target->GetOriginalLinkLibraries();
    for (cmTarget::LinkLibraryVectorType::const_iterator it = libVec.begin();
         it != libVec.end(); ++it) {
      const std::string& libName = it->first;
      if (makefile->FindTargetToUse(libName) != CM_NULLPTR) {
        autogenDepends.push_back(libName);
      }
    }
  }
  {
818
    cmFilePathChecksum fpathCheckSum(makefile);
819
    // Iterate over all source files
820
821
822
823
824
    std::vector<cmSourceFile*> srcFiles;
    target->GetConfigCommonSourceFiles(srcFiles);
    for (std::vector<cmSourceFile*>::const_iterator fileIt = srcFiles.begin();
         fileIt != srcFiles.end(); ++fileIt) {
      cmSourceFile* sf = *fileIt;
825
      if (!PropertyEnabled(sf, "SKIP_AUTOGEN")) {
826
        std::string const& ext = sf->GetExtension();
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
        // Add generated file that will be scanned by moc or uic to
        // the dependencies
        if (mocEnabled || uicEnabled) {
          const cmSystemTools::FileFormat fileType =
            cmSystemTools::GetFileFormat(ext.c_str());
          if ((fileType == cmSystemTools::CXX_FILE_FORMAT) ||
              (fileType == cmSystemTools::HEADER_FILE_FORMAT)) {
            if (PropertyEnabled(sf, "GENERATED")) {
              if ((mocEnabled && !PropertyEnabled(sf, "SKIP_AUTOMOC")) ||
                  (uicEnabled && !PropertyEnabled(sf, "SKIP_AUTOUIC"))) {
                autogenDepends.push_back(
                  cmsys::SystemTools::GetRealPath(sf->GetFullPath()));
#if defined(_WIN32) && !defined(__CYGWIN__)
                // Cannot use PRE_BUILD with generated files
                usePRE_BUILD = false;
#endif
              }
            }
          }
        }
        // Process rcc enabled files
        if (rccEnabled && (ext == "qrc") &&
            !PropertyEnabled(sf, "SKIP_AUTORCC")) {
850
851
852
          const std::string absFile =
            cmsys::SystemTools::GetRealPath(sf->GetFullPath());

853
854
          // Compose rcc output file name
          {
855
856
857
858
            std::string rccOutBase = autogenBuildDir + "/";
            rccOutBase += fpathCheckSum.getPart(absFile);
            rccOutBase += "/qrc_";
            rccOutBase +=
859
860
              cmsys::SystemTools::GetFilenameWithoutLastExtension(absFile);

861
862
863
864
865
866
867
868
869
870
871
            // Register rcc ouput file as generated
            for (std::vector<std::string>::const_iterator it =
                   suffixes.begin();
                 it != suffixes.end(); ++it) {
              std::string rccOutCfg = rccOutBase;
              rccOutCfg += *it;
              rccOutCfg += ".cpp";
              AddGeneratedSource(makefile, rccOutCfg,
                                 cmQtAutoGeneratorCommon::RCC);
              autogenProvides.push_back(rccOutCfg);
            }
872
            // Add rcc output file to origin target sources
873
874
875
876
            if (multiConfig) {
              target->AddSource(rccOutBase + "_$<CONFIG>.cpp");
            } else {
              target->AddSource(rccOutBase + ".cpp");
877
            }
878
          }
879

880
881
882
883
884
885
886
887
888
889
890
891
892
          if (PropertyEnabled(sf, "GENERATED")) {
            // Add generated qrc file to the dependencies
            autogenDepends.push_back(absFile);
          } else {
            // Run cmake again when .qrc file changes
            makefile->AddCMakeDependFile(absFile);

            // Add the qrc input files to the dependencies
            std::string error;
            if (!cmQtAutoGeneratorCommon::RccListInputs(
                  qtMajorVersion, rccCommand, absFile, autogenDepends,
                  &error)) {
              cmSystemTools::Error(error.c_str());
893
            }
894
          }
895
896
897
898
899
900
#if defined(_WIN32) && !defined(__CYGWIN__)
          // Cannot use PRE_BUILD because the resource files themselves
          // may not be sources within the target so VS may not know the
          // target needs to re-build at all.
          usePRE_BUILD = false;
#endif
901
902
903
        }
      }
    }
904
  }
905
906

#if defined(_WIN32) && !defined(__CYGWIN__)
907
908
909
910
911
912
913
914
915
916
  if (usePRE_BUILD) {
    // If the autogen target depends on an other target don't use PRE_BUILD
    for (std::vector<std::string>::iterator it = autogenDepends.begin();
         it != autogenDepends.end(); ++it) {
      if (makefile->FindTargetToUse(*it) != CM_NULLPTR) {
        usePRE_BUILD = false;
        break;
      }
    }
  }
917
  if (usePRE_BUILD) {
918
919
920
921
    // Add the pre-build command directly to bypass the OBJECT_LIBRARY
    // rejection in cmMakefile::AddCustomCommandToTarget because we know
    // PRE_BUILD will work for an OBJECT_LIBRARY in this specific case.
    std::vector<std::string> no_output;
922
    cmCustomCommand cc(makefile, no_output, autogenProvides, autogenDepends,
923
924
925
926
                       commandLines, autogenComment.c_str(),
                       workingDirectory.c_str());
    cc.SetEscapeOldStyle(false);
    cc.SetEscapeAllowMakeVars(true);
927
    target->Target->AddPreBuildCommand(cc);
928
  } else
929
#endif
930
  {
931
    cmTarget* autogenTarget = makefile->AddUtilityCommand(
932
      autogenTargetName, true, workingDirectory.c_str(),
933
      /*byproducts=*/autogenProvides, autogenDepends, commandLines, false,
934
      autogenComment.c_str());
935
936

    cmGeneratorTarget* gt = new cmGeneratorTarget(autogenTarget, lg);
937
    lg->AddGeneratorTarget(gt);
938
939

    // Set target folder
940
941
942
943
944
945
946
    const char* autogenFolder =
      makefile->GetState()->GetGlobalProperty("AUTOMOC_TARGETS_FOLDER");
    if (!autogenFolder) {
      autogenFolder =
        makefile->GetState()->GetGlobalProperty("AUTOGEN_TARGETS_FOLDER");
    }
    if (autogenFolder && *autogenFolder) {
947
      autogenTarget->SetProperty("FOLDER", autogenFolder);
948
    } else {
949
      // inherit FOLDER property from target (#13688)
950
      utilCopyTargetProperty(gt->Target, target->Target, "FOLDER");
951
    }
952

953
    target->Target->AddUtility(autogenTargetName);
954
  }
955
956
957
}

void cmQtAutoGeneratorInitializer::SetupAutoGenerateTarget(
958
  cmGeneratorTarget const* target)
959
{
960
  cmMakefile* makefile = target->Target->GetMakefile();
961
962
963
964
965

  // forget the variables added here afterwards again:
  cmMakefile::ScopePushPop varScope(makefile);
  static_cast<void>(varScope);

966
967
968
969
970
971
  // Get configurations
  std::string config;
  const std::vector<std::string> configs(GetConfigurations(makefile, &config));

  // Configurations settings buffers
  std::map<std::string, std::string> configSuffix;
972
  std::map<std::string, std::string> configMocIncludes;
973
  std::map<std::string, std::string> configMocDefines;
974
  std::map<std::string, std::string> configUicOptions;
975
976
977
978
979
980
981
982
983
984

  // Configuration suffix
  if (IsMultiConfig(target->GetGlobalGenerator())) {
    for (std::vector<std::string>::const_iterator it = configs.begin();
         it != configs.end(); ++it) {
      configSuffix[*it] = "_" + *it;
    }
  }

  // Basic setup
985
  {
986
987
988
    const bool mocEnabled = target->GetPropertyAsBool("AUTOMOC");
    const bool uicEnabled = target->GetPropertyAsBool("AUTOUIC");
    const bool rccEnabled = target->GetPropertyAsBool("AUTORCC");
989
990
    const std::string autogenTargetName = GetAutogenTargetName(target);
    const std::string qtMajorVersion = GetQtMajorVersion(target);
991

992
993
    std::vector<std::string> sources;
    std::vector<std::string> headers;
994

995
996
997
    if (mocEnabled || uicEnabled || rccEnabled) {
      std::vector<std::string> mocSkipList;
      std::vector<std::string> uicSkipList;
998
      AcquireScanFiles(target, sources, headers, mocSkipList, uicSkipList);
999
      if (mocEnabled) {
1000
1001
1002
        MocSetupAutoTarget(target, autogenTargetName, qtMajorVersion, config,
                           configs, mocSkipList, configMocIncludes,
                           configMocDefines);
1003
1004
      }
      if (uicEnabled) {
1005
1006
        UicSetupAutoTarget(target, qtMajorVersion, config, configs,
                           uicSkipList, configUicOptions);
1007
1008
1009
1010
      }
      if (rccEnabled) {
        RccSetupAutoTarget(target, qtMajorVersion);
      }
1011
    }
1012

1013
1014
    AddDefinitionEscaped(makefile, "_autogen_build_dir",
                         GetAutogenTargetBuildDir(target));
1015
    AddDefinitionEscaped(makefile, "_qt_version_major", qtMajorVersion);
1016
1017
    AddDefinitionEscaped(makefile, "_sources", sources);
    AddDefinitionEscaped(makefile, "_headers", headers);
1018
  }
1019

1020
1021
1022
1023
1024
1025
1026
1027
  // Generate info file
  std::string infoFile = GetAutogenTargetFilesDir(target);
  infoFile += "/AutogenInfo.cmake";
  {
    std::string inf = cmSystemTools::GetCMakeRoot();
    inf += "/Modules/AutogenInfo.cmake.in";
    makefile->ConfigureFile(inf.c_str(), infoFile.c_str(), false, true, false);
  }
1028

1029
1030
1031
  // Append custom definitions to info file on demand
  if (!configSuffix.empty() || !configMocDefines.empty() ||
      !configMocIncludes.empty() || !configUicOptions.empty()) {
1032
1033
1034

    // Ensure we have write permission in case .in was read-only.
    mode_t perm = 0;
1035
#if defined(_WIN32) && !defined(__CYGWIN__)
1036
    mode_t mode_write = S_IWRITE;
1037
#else
1038
    mode_t mode_write = S_IWUSR;
1039
#endif
1040
    cmSystemTools::GetPermissions(infoFile, perm);
1041
    if (!(perm & mode_write)) {
1042
      cmSystemTools::SetPermissions(infoFile, perm | mode_write);
1043
1044
    }

1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
    // Open and write file
    cmsys::ofstream ofs(infoFile.c_str(), std::ios::app);
    if (ofs) {
      ofs << "# Configuration specific options\n";
      for (std::map<std::string, std::string>::iterator
             it = configSuffix.begin(),
             end = configSuffix.end();
           it != end; ++it) {
        ofs << "set(AM_CONFIG_SUFFIX_" << it->first << " " << it->second
            << ")\n";
1055
      }
1056
1057
1058
1059
1060
1061
      for (std::map<std::string, std::string>::iterator
             it = configMocDefines.begin(),
             end = configMocDefines.end();
           it != end; ++it) {
        ofs << "set(AM_MOC_DEFINITIONS_" << it->first << " " << it->second
            << ")\n";
1062
      }
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
      for (std::map<std::string, std::string>::iterator
             it = configMocIncludes.begin(),
             end = configMocIncludes.end();
           it != end; ++it) {
        ofs << "set(AM_MOC_INCLUDES_" << it->first << " " << it->second
            << ")\n";
      }
      for (std::map<std::string, std::string>::iterator
             it = configUicOptions.begin(),
             end = configUicOptions.end();
           it != end; ++it) {
        ofs << "set(AM_UIC_TARGET_OPTIONS_" << it->first << " " << it->second
            << ")\n";
1076
      }
1077
1078
1079
1080
1081
1082
    } else {
      // File open error
      std::string error = "Internal CMake error when trying to open file: ";
      error += cmQtAutoGeneratorCommon::Quoted(infoFile);
      error += " for writing.";
      cmSystemTools::Error(error.c_str());
1083
    }
1084
  }
1085
}