cmQtAutoGeneratorInitializer.cxx 45.8 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 "cmQtAutoGen.h"
4
5
#include "cmQtAutoGeneratorInitializer.h"

6
#include "cmAlgorithms.h"
7
#include "cmCustomCommand.h"
8
#include "cmCustomCommandLines.h"
9
#include "cmFilePathChecksum.h"
10
#include "cmGeneratorTarget.h"
11
#include "cmGlobalGenerator.h"
12
#include "cmLinkItem.h"
13
14
#include "cmLocalGenerator.h"
#include "cmMakefile.h"
15
#include "cmOutputConverter.h"
16
#include "cmPolicies.h"
17
#include "cmProcessOutput.h"
18
#include "cmSourceFile.h"
Daniel Pfeifer's avatar
Daniel Pfeifer committed
19
#include "cmSourceGroup.h"
20
#include "cmState.h"
21
#include "cmStateTypes.h"
22
23
#include "cmSystemTools.h"
#include "cmTarget.h"
24
#include "cm_sys_stat.h"
25
#include "cmake.h"
26
#include "cmsys/FStream.hxx"
27

28
#include <algorithm>
29
#include <array>
30
#include <deque>
31
32
#include <map>
#include <set>
33
#include <sstream>
34
35
36
37
#include <string>
#include <utility>
#include <vector>

38
inline static const char* SafeString(const char* value)
39
{
Daniel Pfeifer's avatar
Daniel Pfeifer committed
40
  return (value != nullptr) ? value : "";
41
42
}

43
44
inline static std::string GetSafeProperty(cmGeneratorTarget const* target,
                                          const char* key)
45
{
46
  return std::string(SafeString(target->GetProperty(key)));
47
48
}

49
50
51
52
53
54
inline static std::string GetSafeProperty(cmSourceFile const* sf,
                                          const char* key)
{
  return std::string(SafeString(sf->GetProperty(key)));
}

55
static void AddDefinitionEscaped(cmMakefile* makefile, const char* key,
56
                                 std::string const& value)
57
58
59
60
61
62
63
64
65
66
67
68
{
  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());
}

69
70
71
72
73
74
75
static void AddDefinitionEscaped(cmMakefile* makefile, const char* key,
                                 const std::set<std::string>& values)
{
  makefile->AddDefinition(
    key, cmOutputConverter::EscapeForCMake(cmJoin(values, ";")).c_str());
}

76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
static void AddDefinitionEscaped(
  cmMakefile* makefile, const char* key,
  const std::vector<std::vector<std::string>>& lists)
{
  std::vector<std::string> seplist;
  for (const std::vector<std::string>& list : lists) {
    std::string blist = "{";
    blist += cmJoin(list, ";");
    blist += "}";
    seplist.push_back(std::move(blist));
  }
  makefile->AddDefinition(key, cmOutputConverter::EscapeForCMake(
                                 cmJoin(seplist, cmQtAutoGen::listSep))
                                 .c_str());
}

92
static bool AddToSourceGroup(cmMakefile* makefile, std::string const& fileName,
93
                             cmQtAutoGen::Generator genType)
94
{
Daniel Pfeifer's avatar
Daniel Pfeifer committed
95
  cmSourceGroup* sourceGroup = nullptr;
96
97
  // Acquire source group
  {
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
    std::string property;
    std::string groupName;
    {
      std::array<std::string, 2> props;
      // Use generator specific group name
      switch (genType) {
        case cmQtAutoGen::MOC:
          props[0] = "AUTOMOC_SOURCE_GROUP";
          break;
        case cmQtAutoGen::RCC:
          props[0] = "AUTORCC_SOURCE_GROUP";
          break;
        default:
          props[0] = "AUTOGEN_SOURCE_GROUP";
          break;
      }
      props[1] = "AUTOGEN_SOURCE_GROUP";
      for (std::string& prop : props) {
        const char* propName = makefile->GetState()->GetGlobalProperty(prop);
        if ((propName != nullptr) && (*propName != '\0')) {
          groupName = propName;
          property = std::move(prop);
          break;
        }
      }
123
124
    }
    // Generate a source group on demand
125
    if (!groupName.empty()) {
126
      sourceGroup = makefile->GetOrCreateSourceGroup(groupName);
Daniel Pfeifer's avatar
Daniel Pfeifer committed
127
      if (sourceGroup == nullptr) {
128
129
130
131
132
133
        std::ostringstream ost;
        ost << cmQtAutoGen::GeneratorNameUpper(genType);
        ost << ": " << property;
        ost << ": Could not find or create the source group ";
        ost << cmQtAutoGen::Quoted(groupName);
        cmSystemTools::Error(ost.str().c_str());
134
135
136
137
        return false;
      }
    }
  }
Daniel Pfeifer's avatar
Daniel Pfeifer committed
138
  if (sourceGroup != nullptr) {
139
140
141
142
143
    sourceGroup->AddGroupFile(fileName);
  }
  return true;
}

144
static void AddCleanFile(cmMakefile* makefile, std::string const& fileName)
145
146
147
148
149
{
  makefile->AppendProperty("ADDITIONAL_MAKE_CLEAN_FILES", fileName.c_str(),
                           false);
}

150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
static std::string FileProjectRelativePath(cmMakefile* makefile,
                                           std::string const& fileName)
{
  std::string res;
  {
    std::string pSource = cmSystemTools::RelativePath(
      makefile->GetCurrentSourceDirectory(), fileName.c_str());
    std::string pBinary = cmSystemTools::RelativePath(
      makefile->GetCurrentBinaryDirectory(), fileName.c_str());
    if (pSource.size() < pBinary.size()) {
      res = std::move(pSource);
    } else if (pBinary.size() < fileName.size()) {
      res = std::move(pBinary);
    } else {
      res = fileName;
    }
  }
  return res;
}

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
/* @brief Tests if targetDepend is a STATIC_LIBRARY and if any of its
 * recursive STATIC_LIBRARY dependencies depends on targetOrigin
 * (STATIC_LIBRARY cycle).
 */
static bool StaticLibraryCycle(cmGeneratorTarget const* targetOrigin,
                               cmGeneratorTarget const* targetDepend,
                               std::string const& config)
{
  bool cycle = false;
  if ((targetOrigin->GetType() == cmStateEnums::STATIC_LIBRARY) &&
      (targetDepend->GetType() == cmStateEnums::STATIC_LIBRARY)) {
    std::set<cmGeneratorTarget const*> knownLibs;
    std::deque<cmGeneratorTarget const*> testLibs;

    // Insert initial static_library dependency
    knownLibs.insert(targetDepend);
    testLibs.push_back(targetDepend);

    while (!testLibs.empty()) {
      cmGeneratorTarget const* testTarget = testLibs.front();
      testLibs.pop_front();
      // Check if the test target is the origin target (cycle)
      if (testTarget == targetOrigin) {
        cycle = true;
        break;
      }
      // Collect all static_library dependencies from the test target
      cmLinkImplementationLibraries const* libs =
        testTarget->GetLinkImplementationLibraries(config);
      if (libs != nullptr) {
        for (cmLinkItem const& item : libs->Libraries) {
          cmGeneratorTarget const* depTarget = item.Target;
          if ((depTarget != nullptr) &&
              (depTarget->GetType() == cmStateEnums::STATIC_LIBRARY) &&
              knownLibs.insert(depTarget).second) {
            testLibs.push_back(depTarget);
          }
        }
      }
    }
  }
  return cycle;
}

214
215
216
217
218
219
220
221
222
cmQtAutoGeneratorInitializer::cmQtAutoGeneratorInitializer(
  cmGeneratorTarget* target, bool mocEnabled, bool uicEnabled, bool rccEnabled,
  std::string const& qtVersionMajor)
  : Target(target)
  , MocEnabled(mocEnabled)
  , UicEnabled(uicEnabled)
  , RccEnabled(rccEnabled)
  , QtVersionMajor(qtVersionMajor)
  , MultiConfig(cmQtAutoGen::WRAP)
223
{
224
225
226
  this->QtVersionMinor = cmQtAutoGeneratorInitializer::GetQtMinorVersion(
    target, this->QtVersionMajor);
}
227

228
229
230
231
232
void cmQtAutoGeneratorInitializer::InitCustomTargets()
{
  cmMakefile* makefile = this->Target->Target->GetMakefile();
  cmLocalGenerator* localGen = this->Target->GetLocalGenerator();
  cmGlobalGenerator* globalGen = localGen->GetGlobalGenerator();
233

234
235
236
237
  // Configurations
  this->ConfigDefault = makefile->GetConfigurations(this->ConfigsList);
  if (this->ConfigsList.empty()) {
    this->ConfigsList.push_back(this->ConfigDefault);
238
  }
239
240

  // Multi configuration
241
  {
242
243
244
    if (!globalGen->IsMultiConfig()) {
      this->MultiConfig = cmQtAutoGen::SINGLE;
    }
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
    // FIXME: Xcode does not support per-config sources, yet.
    //        (EXCLUDED_SOURCE_FILE_NAMES)
    // if (globalGen->GetName().find("Xcode") != std::string::npos) {
    //  return cmQtAutoGen::FULL;
    //}

    // FIXME: Visual Studio does not support per-config sources, yet.
    //        (EXCLUDED_SOURCE_FILE_NAMES)
    // if (globalGen->GetName().find("Visual Studio") != std::string::npos) {
    //  return cmQtAutoGen::FULL;
    //}
  }

  // Autogen target name
  this->AutogenTargetName = this->Target->GetName();
  this->AutogenTargetName += "_autogen";

  // Autogen directories
  {
    // Collapsed current binary directory
    std::string const cbd = cmSystemTools::CollapseFullPath(
      "", makefile->GetCurrentBinaryDirectory());

    // Autogen info dir
    this->DirInfo = cbd;
    this->DirInfo += makefile->GetCMakeInstance()->GetCMakeFilesDirectory();
    this->DirInfo += "/";
    this->DirInfo += this->AutogenTargetName;
    this->DirInfo += ".dir";
    cmSystemTools::ConvertToUnixSlashes(this->DirInfo);

    // Autogen build dir
    this->DirBuild = GetSafeProperty(this->Target, "AUTOGEN_BUILD_DIR");
    if (this->DirBuild.empty()) {
      this->DirBuild = cbd;
      this->DirBuild += "/";
      this->DirBuild += this->AutogenTargetName;
283
    }
284
285
286
287
288
    cmSystemTools::ConvertToUnixSlashes(this->DirBuild);

    // Working directory
    this->DirWork = cbd;
    cmSystemTools::ConvertToUnixSlashes(this->DirWork);
289
  }
290

291
  // Autogen files
292
  {
293
294
    this->AutogenInfoFile = this->DirInfo;
    this->AutogenInfoFile += "/AutogenInfo.cmake";
295

296
297
298
    this->AutogenSettingsFile = this->DirInfo;
    this->AutogenSettingsFile += "/AutogenOldSettings.cmake";
  }
299

300
301
302
303
304
305
306
307
308
309
310
311
312
313
  // Autogen target FOLDER property
  {
    const char* folder =
      makefile->GetState()->GetGlobalProperty("AUTOMOC_TARGETS_FOLDER");
    if (folder == nullptr) {
      folder =
        makefile->GetState()->GetGlobalProperty("AUTOGEN_TARGETS_FOLDER");
    }
    // Inherit FOLDER property from target (#13688)
    if (folder == nullptr) {
      folder = SafeString(this->Target->Target->GetProperty("FOLDER"));
    }
    if (folder != nullptr) {
      this->AutogenFolder = folder;
314
315
    }
  }
316

317
318
319
  std::set<std::string> autogenDependFiles;
  std::set<cmTarget*> autogenDependTargets;
  std::vector<std::string> autogenProvides;
320

321
322
323
  // Remove build directories on cleanup
  AddCleanFile(makefile, this->DirBuild);
  // Remove old settings on cleanup
324
  {
325
326
327
328
329
330
331
332
333
334
335
    std::string base = this->DirInfo;
    base += "/AutogenOldSettings";
    if (this->MultiConfig == cmQtAutoGen::SINGLE) {
      AddCleanFile(makefile, base.append(".cmake"));
    } else {
      for (std::string const& cfg : this->ConfigsList) {
        std::string filename = base;
        filename += "_";
        filename += cfg;
        filename += ".cmake";
        AddCleanFile(makefile, filename);
336
      }
337
    }
338
339
  }

340
  // Add moc compilation to generated files list
341
342
343
  if (this->MocEnabled) {
    std::string const mocsComp = this->DirBuild + "/mocs_compilation.cpp";
    auto files = this->AddGeneratedSource(mocsComp, cmQtAutoGen::MOC);
344
345
346
    for (std::string& file : files) {
      autogenProvides.push_back(std::move(file));
    }
347
  }
348

349
  // Add autogen includes directory to the origin target INCLUDE_DIRECTORIES
350
351
352
  if (this->MocEnabled || this->UicEnabled) {
    std::string includeDir = this->DirBuild + "/include";
    if (this->MultiConfig != cmQtAutoGen::SINGLE) {
353
      includeDir += "_$<CONFIG>";
354
    }
355
    this->Target->AddIncludeDirectory(includeDir, true);
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
  // Acquire rcc executable and features
  if (this->RccEnabled) {
    {
      std::string err;
      if (this->QtVersionMajor == "5") {
        cmGeneratorTarget* tgt =
          localGen->FindGeneratorTargetToUse("Qt5::rcc");
        if (tgt != nullptr) {
          this->RccExecutable = SafeString(tgt->ImportedGetLocation(""));
        } else {
          err = "AUTORCC: Qt5::rcc target not found";
        }
      } else if (QtVersionMajor == "4") {
        cmGeneratorTarget* tgt =
          localGen->FindGeneratorTargetToUse("Qt4::rcc");
        if (tgt != nullptr) {
          this->RccExecutable = SafeString(tgt->ImportedGetLocation(""));
        } else {
          err = "AUTORCC: Qt4::rcc target not found";
        }
      } else {
        err = "The AUTORCC feature supports only Qt 4 and Qt 5";
      }
      if (!err.empty()) {
        err += " (";
        err += this->Target->GetName();
        err += ")";
        cmSystemTools::Error(err.c_str());
      }
    }
    // Detect if rcc supports (-)-list
    if (!this->RccExecutable.empty() && (this->QtVersionMajor == "5")) {
      std::vector<std::string> command;
      command.push_back(this->RccExecutable);
      command.push_back("--help");
      std::string rccStdOut;
      std::string rccStdErr;
      int retVal = 0;
      bool result = cmSystemTools::RunSingleCommand(
        command, &rccStdOut, &rccStdErr, &retVal, nullptr,
        cmSystemTools::OUTPUT_NONE, 0.0, cmProcessOutput::Auto);
      if (result && retVal == 0 &&
          rccStdOut.find("--list") != std::string::npos) {
        this->RccListOptions.push_back("--list");
      } else {
        this->RccListOptions.push_back("-list");
      }
    }
  }

408
  // Extract relevant source files
409
410
  std::vector<std::string> generatedSources;
  std::vector<std::string> generatedHeaders;
411
  {
412
    std::string const qrcExt = "qrc";
413
    std::vector<cmSourceFile*> srcFiles;
414
    this->Target->GetConfigCommonSourceFiles(srcFiles);
415
    for (cmSourceFile* sf : srcFiles) {
416
417
418
419
      if (sf->GetPropertyAsBool("SKIP_AUTOGEN")) {
        continue;
      }
      // sf->GetExtension() is only valid after sf->GetFullPath() ...
420
421
      std::string const& fPath = sf->GetFullPath();
      std::string const& ext = sf->GetExtension();
422
      // Register generated files that will be scanned by moc or uic
423
      if (this->MocEnabled || this->UicEnabled) {
424
        cmSystemTools::FileFormat const fileType =
425
426
427
          cmSystemTools::GetFileFormat(ext.c_str());
        if ((fileType == cmSystemTools::CXX_FILE_FORMAT) ||
            (fileType == cmSystemTools::HEADER_FILE_FORMAT)) {
428
          std::string const absPath = cmSystemTools::GetRealPath(fPath);
429
430
          if ((this->MocEnabled && !sf->GetPropertyAsBool("SKIP_AUTOMOC")) ||
              (this->UicEnabled && !sf->GetPropertyAsBool("SKIP_AUTOUIC"))) {
431
432
433
434
            // Register source
            const bool generated = sf->GetPropertyAsBool("GENERATED");
            if (fileType == cmSystemTools::HEADER_FILE_FORMAT) {
              if (generated) {
435
                generatedHeaders.push_back(absPath);
436
              } else {
437
                this->Headers.push_back(absPath);
438
439
440
              }
            } else {
              if (generated) {
441
                generatedSources.push_back(absPath);
442
              } else {
443
                this->Sources.push_back(absPath);
444
              }
445
446
447
            }
          }
        }
448
449
      }
      // Register rcc enabled files
450
      if (this->RccEnabled && (ext == qrcExt) &&
451
          !sf->GetPropertyAsBool("SKIP_AUTORCC")) {
452
453
        // Register qrc file
        {
454
455
456
457
458
          Qrc qrc;
          qrc.QrcFile = cmSystemTools::GetRealPath(fPath);
          qrc.QrcName =
            cmSystemTools::GetFilenameWithoutLastExtension(qrc.QrcFile);
          qrc.Generated = sf->GetPropertyAsBool("GENERATED");
459
460
          // RCC options
          {
461
            std::string const opts = GetSafeProperty(sf, "AUTORCC_OPTIONS");
462
            if (!opts.empty()) {
463
              cmSystemTools::ExpandListArgument(opts, qrc.Options);
464
465
            }
          }
466
          this->Qrcs.push_back(std::move(qrc));
467
        }
468
469
470
471
472
473
      }
    }
    // cmGeneratorTarget::GetConfigCommonSourceFiles computes the target's
    // sources meta data cache. Clear it so that OBJECT library targets that
    // are AUTOGEN initialized after this target get their added
    // mocs_compilation.cpp source acknowledged by this target.
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
    this->Target->ClearSourcesCache();
  }
  // Read skip files from makefile sources
  if (this->MocEnabled || this->UicEnabled) {
    const std::vector<cmSourceFile*>& allSources = makefile->GetSourceFiles();
    for (cmSourceFile* sf : allSources) {
      // sf->GetExtension() is only valid after sf->GetFullPath() ...
      std::string const& fPath = sf->GetFullPath();
      cmSystemTools::FileFormat const fileType =
        cmSystemTools::GetFileFormat(sf->GetExtension().c_str());
      if (!(fileType == cmSystemTools::CXX_FILE_FORMAT) &&
          !(fileType == cmSystemTools::HEADER_FILE_FORMAT)) {
        continue;
      }
      const bool skipAll = sf->GetPropertyAsBool("SKIP_AUTOGEN");
      const bool mocSkip =
        this->MocEnabled && (skipAll || sf->GetPropertyAsBool("SKIP_AUTOMOC"));
      const bool uicSkip =
        this->UicEnabled && (skipAll || sf->GetPropertyAsBool("SKIP_AUTOUIC"));
      if (mocSkip || uicSkip) {
        std::string const absFile = cmSystemTools::GetRealPath(fPath);
        if (mocSkip) {
          this->MocSkip.insert(absFile);
        }
        if (uicSkip) {
          this->UicSkip.insert(absFile);
        }
      }
    }
503
  }
504

505
  // Process GENERATED sources and headers
506
  if (!generatedSources.empty() || !generatedHeaders.empty()) {
507
508
509
    // Check status of policy CMP0071
    bool policyAccept = false;
    bool policyWarn = false;
510
    cmPolicies::PolicyStatus const CMP0071_status =
511
      makefile->GetPolicyStatus(cmPolicies::CMP0071);
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
    switch (CMP0071_status) {
      case cmPolicies::WARN:
        policyWarn = true;
        CM_FALLTHROUGH;
      case cmPolicies::OLD:
        // Ignore GENERATED file
        break;
      case cmPolicies::REQUIRED_IF_USED:
      case cmPolicies::REQUIRED_ALWAYS:
      case cmPolicies::NEW:
        // Process GENERATED file
        policyAccept = true;
        break;
    }

    if (policyAccept) {
      // Accept GENERATED sources
529
      for (std::string const& absFile : generatedHeaders) {
530
        this->Headers.push_back(absFile);
531
        autogenDependFiles.insert(absFile);
532
      }
533
      for (std::string const& absFile : generatedSources) {
534
        this->Sources.push_back(absFile);
535
        autogenDependFiles.insert(absFile);
536
      }
537
538
539
540
541
542
    } else {
      if (policyWarn) {
        std::string msg;
        msg += cmPolicies::GetPolicyWarning(cmPolicies::CMP0071);
        msg += "\n";
        std::string tools;
543
        std::string property;
544
        if (this->MocEnabled && this->UicEnabled) {
545
546
          tools = "AUTOMOC and AUTOUIC";
          property = "SKIP_AUTOGEN";
547
        } else if (this->MocEnabled) {
548
549
          tools = "AUTOMOC";
          property = "SKIP_AUTOMOC";
550
        } else if (this->UicEnabled) {
551
552
          tools = "AUTOUIC";
          property = "SKIP_AUTOUIC";
553
        }
554
555
556
557
        msg += "For compatibility, CMake is excluding the GENERATED source "
               "file(s):\n";
        for (const std::string& absFile : generatedHeaders) {
          msg.append("  ").append(cmQtAutoGen::Quoted(absFile)).append("\n");
558
        }
559
560
        for (const std::string& absFile : generatedSources) {
          msg.append("  ").append(cmQtAutoGen::Quoted(absFile)).append("\n");
561
        }
562
563
564
565
566
567
568
569
570
571
        msg += "from processing by ";
        msg += tools;
        msg +=
          ". If any of the files should be processed, set CMP0071 to NEW. "
          "If any of the files should not be processed, "
          "explicitly exclude them by setting the source file property ";
        msg += property;
        msg += ":\n  set_property(SOURCE file.h PROPERTY ";
        msg += property;
        msg += " ON)\n";
572
        makefile->IssueMessage(cmake::AUTHOR_WARNING, msg);
573
      }
574
    }
575
576
577
    // Clear lists
    generatedSources.clear();
    generatedHeaders.clear();
578
  }
579
  // Sort headers and sources
580
581
582
583
  if (this->MocEnabled || this->UicEnabled) {
    std::sort(this->Headers.begin(), this->Headers.end());
    std::sort(this->Sources.begin(), this->Sources.end());
  }
584

585
  // Process qrc files
586
587
  if (!this->Qrcs.empty()) {
    const bool QtV5 = (this->QtVersionMajor == "5");
588
589
590
    // Target rcc options
    std::vector<std::string> optionsTarget;
    cmSystemTools::ExpandListArgument(
591
      GetSafeProperty(this->Target, "AUTORCC_OPTIONS"), optionsTarget);
592

593
    // Check if file name is unique
594
595
596
597
598
    for (Qrc& qrc : this->Qrcs) {
      qrc.Unique = true;
      for (Qrc const& qrc2 : this->Qrcs) {
        if ((&qrc != &qrc2) && (qrc.QrcName == qrc2.QrcName)) {
          qrc.Unique = false;
599
600
          break;
        }
601
      }
602
    }
603
    // Path checksum and file names
604
    {
605
      cmFilePathChecksum const fpathCheckSum(makefile);
606
607
      for (Qrc& qrc : this->Qrcs) {
        qrc.PathChecksum = fpathCheckSum.getPart(qrc.QrcFile);
608
        // RCC output file name
609
        {
610
611
          std::string rccFile = this->DirBuild + "/";
          rccFile += qrc.PathChecksum;
612
          rccFile += "/qrc_";
613
          rccFile += qrc.QrcName;
614
          rccFile += ".cpp";
615
          qrc.RccFile = std::move(rccFile);
616
617
        }
        {
618
          std::string base = this->DirInfo;
619
          base += "/RCC";
620
621
622
          base += qrc.QrcName;
          if (!qrc.Unique) {
            base += qrc.PathChecksum;
623
          }
624
625
626
627
          qrc.InfoFile = base;
          qrc.InfoFile += "Info.cmake";
          qrc.SettingsFile = base;
          qrc.SettingsFile += "Settings.cmake";
628
        }
629
630
631
      }
    }
    // RCC options
632
    for (Qrc& qrc : this->Qrcs) {
633
634
635
      // Target options
      std::vector<std::string> opts = optionsTarget;
      // Merge computed "-name XYZ" option
636
      {
637
        std::string name = qrc.QrcName;
638
639
        // Replace '-' with '_'. The former is not valid for symbol names.
        std::replace(name.begin(), name.end(), '-', '_');
640
        if (!qrc.Unique) {
641
          name += "_";
642
          name += qrc.PathChecksum;
643
        }
644
645
646
647
        std::vector<std::string> nameOpts;
        nameOpts.emplace_back("-name");
        nameOpts.emplace_back(std::move(name));
        cmQtAutoGen::RccMergeOptions(opts, nameOpts, QtV5);
648
      }
649
      // Merge file option
650
651
      cmQtAutoGen::RccMergeOptions(opts, qrc.Options, QtV5);
      qrc.Options = std::move(opts);
652
    }
653
    for (Qrc& qrc : this->Qrcs) {
654
      // Register file at target
655
656
      std::vector<std::string> const ccOutput =
        this->AddGeneratedSource(qrc.RccFile, cmQtAutoGen::RCC);
657
658

      cmCustomCommandLines commandLines;
659
      {
660
661
662
663
        cmCustomCommandLine currentLine;
        currentLine.push_back(cmSystemTools::GetCMakeCommand());
        currentLine.push_back("-E");
        currentLine.push_back("cmake_autorcc");
664
        currentLine.push_back(qrc.InfoFile);
665
666
        currentLine.push_back("$<CONFIGURATION>");
        commandLines.push_back(std::move(currentLine));
667
      }
668
      std::string ccComment = "Automatic RCC for ";
669
      ccComment += FileProjectRelativePath(makefile, qrc.QrcFile);
670

671
      if (qrc.Generated) {
672
673
674
        // Create custom rcc target
        std::string ccName;
        {
675
          ccName = this->Target->GetName();
676
          ccName += "_arcc_";
677
678
          ccName += qrc.QrcName;
          if (!qrc.Unique) {
679
            ccName += "_";
680
            ccName += qrc.PathChecksum;
681
682
683
          }
          std::vector<std::string> ccDepends;
          // Add the .qrc file to the custom target dependencies
684
          ccDepends.push_back(qrc.QrcFile);
685
686

          cmTarget* autoRccTarget = makefile->AddUtilityCommand(
687
            ccName, true, this->DirWork.c_str(), ccOutput, ccDepends,
688
689
690
691
692
693
            commandLines, false, ccComment.c_str());
          // Create autogen generator target
          localGen->AddGeneratorTarget(
            new cmGeneratorTarget(autoRccTarget, localGen));

          // Set FOLDER property in autogen target
694
695
          if (!this->AutogenFolder.empty()) {
            autoRccTarget->SetProperty("FOLDER", this->AutogenFolder.c_str());
696
697
698
          }
        }
        // Add autogen target to the origin target dependencies
699
        this->Target->Target->AddUtility(ccName, makefile);
700
      } else {
701
        // Create custom rcc command
702
        {
703
704
705
          std::vector<std::string> ccByproducts;
          std::vector<std::string> ccDepends;
          // Add the .qrc file to the custom command dependencies
706
          ccDepends.push_back(qrc.QrcFile);
707
708
709
710

          // Add the resource files to the dependencies
          {
            std::string error;
711
712
713
            if (cmQtAutoGen::RccListInputs(this->RccExecutable,
                                           this->RccListOptions, qrc.QrcFile,
                                           qrc.Resources, &error)) {
714
              for (std::string const& fileName : qrc.Resources) {
715
716
717
718
719
                // Add resource file to the custom command dependencies
                ccDepends.push_back(fileName);
              }
            } else {
              cmSystemTools::Error(error.c_str());
720
            }
721
          }
722
723
724
          makefile->AddCustomCommandToOutput(ccOutput, ccByproducts, ccDepends,
                                             /*main_dependency*/ std::string(),
                                             commandLines, ccComment.c_str(),
725
                                             this->DirWork.c_str());
726
        }
727
        // Reconfigure when .qrc file changes
728
        makefile->AddCMakeDependFile(qrc.QrcFile);
729
730
731
732
      }
    }
  }

733
  // Create _autogen target
734
  if (this->MocEnabled || this->UicEnabled) {
735
736
737
    // Add user defined autogen target dependencies
    {
      std::string const deps =
738
        GetSafeProperty(this->Target, "AUTOGEN_TARGET_DEPENDS");
739
740
741
742
743
744
745
746
747
748
749
      if (!deps.empty()) {
        std::vector<std::string> extraDeps;
        cmSystemTools::ExpandListArgument(deps, extraDeps);
        for (std::string const& depName : extraDeps) {
          // Allow target and file dependencies
          auto* depTarget = makefile->FindTargetToUse(depName);
          if (depTarget != nullptr) {
            autogenDependTargets.insert(depTarget);
          } else {
            autogenDependFiles.insert(depName);
          }
750
        }
751
752
753
      }
    }

754
755
756
    // Compose target comment
    std::string autogenComment;
    {
757
758
759
      std::string tools;
      if (this->MocEnabled) {
        tools += "MOC";
760
      }
761
762
763
      if (this->UicEnabled) {
        if (!tools.empty()) {
          tools += " and ";
764
        }
765
        tools += "UIC";
766
      }
767
768
769
770
      autogenComment = "Automatic ";
      autogenComment += tools;
      autogenComment += " for target ";
      autogenComment += this->Target->GetName();
771
    }
772
773
774
775
776
777
778
779

    // Compose command lines
    cmCustomCommandLines commandLines;
    {
      cmCustomCommandLine currentLine;
      currentLine.push_back(cmSystemTools::GetCMakeCommand());
      currentLine.push_back("-E");
      currentLine.push_back("cmake_autogen");
780
      currentLine.push_back(this->AutogenInfoFile);
781
782
      currentLine.push_back("$<CONFIGURATION>");
      commandLines.push_back(std::move(currentLine));
783
784
    }

785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
    // Use PRE_BUILD on demand
    bool usePRE_BUILD = false;
    if (globalGen->GetName().find("Visual Studio") != std::string::npos) {
      // Under VS use a PRE_BUILD event instead of a separate target to
      // 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
      usePRE_BUILD = true;
    }
    // Disable PRE_BUILD in some cases
    if (usePRE_BUILD) {
      // Cannot use PRE_BUILD with file depends
      if (!autogenDependFiles.empty()) {
        usePRE_BUILD = false;
      }
    }
    // Create the autogen target/command
    if (usePRE_BUILD) {
      // Add additional autogen target dependencies to origin target
      for (cmTarget* depTarget : autogenDependTargets) {
805
        this->Target->Target->AddUtility(depTarget->GetName(), makefile);
806
      }
807

808
809
810
811
812
813
814
815
816
      // 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.
      //
      // PRE_BUILD does not support file dependencies!
      const std::vector<std::string> no_output;
      const std::vector<std::string> no_deps;
      cmCustomCommand cc(makefile, no_output, autogenProvides, no_deps,
                         commandLines, autogenComment.c_str(),
817
                         this->DirWork.c_str());
818
819
      cc.SetEscapeOldStyle(false);
      cc.SetEscapeAllowMakeVars(true);
820
      this->Target->Target->AddPreBuildCommand(cc);
821
    } else {
822

823
824
825
826
827
828
      // Convert file dependencies std::set to std::vector
      std::vector<std::string> autogenDepends(autogenDependFiles.begin(),
                                              autogenDependFiles.end());

      // Add link library target dependencies to the autogen target
      // dependencies
829
      for (std::string const& config : this->ConfigsList) {
830
        cmLinkImplementationLibraries const* libs =
831
          this->Target->GetLinkImplementationLibraries(config);
832
833
834
835
        if (libs != nullptr) {
          for (cmLinkItem const& item : libs->Libraries) {
            cmGeneratorTarget const* libTarget = item.Target;
            if ((libTarget != nullptr) &&
836
                !StaticLibraryCycle(this->Target, libTarget, config)) {
837
              std::string util;
838
              if (this->ConfigsList.size() > 1) {
839
840
841
842
843
                util += "$<$<CONFIG:";
                util += config;
                util += ">:";
              }
              util += libTarget->GetName();
844
              if (this->ConfigsList.size() > 1) {
845
846
847
                util += ">";
              }
              autogenDepends.push_back(util);
848
849
850
            }
          }
        }
851
852
      }

853
854
      // Create autogen target
      cmTarget* autogenTarget = makefile->AddUtilityCommand(
855
        this->AutogenTargetName, true, this->DirWork.c_str(),
856
857
858
859
860
861
862
        /*byproducts=*/autogenProvides, autogenDepends, commandLines, false,
        autogenComment.c_str());
      // Create autogen generator target
      localGen->AddGeneratorTarget(
        new cmGeneratorTarget(autogenTarget, localGen));

      // Forward origin utilities to autogen target
863
      for (std::string const& depName : this->Target->Target->GetUtilities()) {
864
        autogenTarget->AddUtility(depName, makefile);
865
      }
866
867
868
      // Add additional autogen target dependencies to autogen target
      for (cmTarget* depTarget : autogenDependTargets) {
        autogenTarget->AddUtility(depTarget->GetName(), makefile);
869
      }
870
871

      // Set FOLDER property in autogen target
872
873
      if (!this->AutogenFolder.empty()) {
        autogenTarget->SetProperty("FOLDER", this->AutogenFolder.c_str());
874
      }
875

876
      // Add autogen target to the origin target dependencies
877
      this->Target->Target->AddUtility(this->AutogenTargetName, makefile);
878
    }
879
  }
880
881
}

882
void cmQtAutoGeneratorInitializer::SetupCustomTargets()
883
{
884
  cmMakefile* makefile = this->Target->Target->GetMakefile();
885
886
887
888
889

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

890
  // Configuration suffixes
891
  std::map<std::string, std::string> configSuffixes;
892
893
894
895
  for (std::string const& cfg : this->ConfigsList) {
    std::string& suffix = configSuffixes[cfg];
    suffix = "_";
    suffix += cfg;
896
  }
897
898

  // Basic setup
899
  AddDefinitionEscaped(makefile, "_multi_config",
900
901
902
903
904
905
906
907
908
909
910
911
912
                       cmQtAutoGen::MultiConfigName(this->MultiConfig));
  AddDefinitionEscaped(makefile, "_build_dir", this->DirBuild);
  AddDefinitionEscaped(makefile, "_qt_version_major", this->QtVersionMajor);
  AddDefinitionEscaped(makefile, "_qt_version_minor", this->QtVersionMinor);

  if (this->MocEnabled || this->UicEnabled) {
    AddDefinitionEscaped(makefile, "_settings_file",
                         this->AutogenSettingsFile);
    AddDefinitionEscaped(makefile, "_sources", this->Sources);
    AddDefinitionEscaped(makefile, "_headers", this->Headers);

    if (this->MocEnabled) {
      this->SetupCustomTargetsMoc();
913
    }
914
915
    if (this->UicEnabled) {
      this->SetupCustomTargetsUic();
916
    }
917
  }
918
  if (this->RccEnabled) {
919
920
921
    AddDefinitionEscaped(makefile, "_qt_rcc_executable", this->RccExecutable);
    AddDefinitionEscaped(makefile, "_qt_rcc_list_options",
                         this->RccListOptions);
922
  }
923

924
  // Create info directory on demand
925
  if (!cmSystemTools::MakeDirectory(this->DirInfo)) {
926
    std::string emsg = ("Could not create directory: ");
927
    emsg += cmQtAutoGen::Quoted(this->DirInfo);
928
929
930
    cmSystemTools::Error(emsg.c_str());
  }

931
932
  auto ReOpenInfoFile = [](cmsys::ofstream& ofs,
                           std::string const& fileName) -> bool {
933
934
935
936
937
938
939
940
941
942
    // Ensure we have write permission
    mode_t perm = 0;
#if defined(_WIN32) && !defined(__CYGWIN__)
    mode_t mode_write = S_IWRITE;
#else
    mode_t mode_write = S_IWUSR;
#endif
    cmSystemTools::GetPermissions(fileName, perm);
    if (!(perm & mode_write)) {
      cmSystemTools::SetPermissions(fileName, perm | mode_write);
943
    }
944
945
946
947
948
949
950
951
952
953

    ofs.open(fileName.c_str(), std::ios::app);
    if (!ofs) {
      // File open error
      std::string error = "Internal CMake error when trying to open file: ";
      error += cmQtAutoGen::Quoted(fileName);
      error += " for writing.";
      cmSystemTools::Error(error.c_str());
    }
    return static_cast<bool>(ofs);
954
955
956
  };

  // Generate autogen target info file
957
  if (this->MocEnabled || this->UicEnabled) {
958
959
960
    {
      std::string infoFileIn = cmSystemTools::GetCMakeRoot();
      infoFileIn += "/Modules/AutogenInfo.cmake.in";
961
962
      makefile->ConfigureFile(
        infoFileIn.c_str(), this->AutogenInfoFile.c_str(), false, true, false);
963
    }
964

965
966
    // Append custom definitions to info file
    // --------------------------------------
967
968
    cmsys::ofstream ofs;
    if (ReOpenInfoFile(ofs, this->AutogenInfoFile)) {
969
      auto OfsWriteMap = [&ofs](
970
        const char* key, std::map<std::string, std::string> const& map) {
971
        for (auto const& item : map) {
972
973
974
975
          ofs << "set(" << key << "_" << item.first << " "
              << cmOutputConverter::EscapeForCMake(item.second) << ")\n";
        }
      };
976
977
      ofs << "# Configurations options\n";
      OfsWriteMap("AM_CONFIG_SUFFIX", configSuffixes);
978
979
980
981
982
983
984
985
986
987
988
989
      OfsWriteMap("AM_MOC_DEFINITIONS", this->ConfigMocDefines);
      OfsWriteMap("AM_MOC_INCLUDES", this->ConfigMocIncludes);
      OfsWriteMap("AM_UIC_TARGET_OPTIONS", this->ConfigUicOptions);
      // Settings files (only require for multi configuration generators)
      if (this->MultiConfig != cmQtAutoGen::SINGLE) {
        std::map<std::string, std::string> settingsFiles;
        for (std::string const& cfg : this->ConfigsList) {
          settingsFiles[cfg] = cmQtAutoGen::AppendFilenameSuffix(
            this->AutogenSettingsFile, "_" + cfg);
        }
        OfsWriteMap("AM_SETTINGS_FILE", settingsFiles);
      }
990
    }
991
  }
992
993

  // Generate auto RCC info files
994
  if (this->RccEnabled) {
995
996
    std::string infoFileIn = cmSystemTools::GetCMakeRoot();
    infoFileIn += "/Modules/AutoRccInfo.cmake.in";
997
    for (Qrc const& qrc : this->Qrcs) {
998
      // Configure info file
999
1000
      makefile->ConfigureFile(infoFileIn.c_str(), qrc.InfoFile.c_str(), false,
                              true, false);
1001
1002
1003

      // Append custom definitions to info file
      // --------------------------------------
1004
1005
1006
1007
1008
1009
1010
      cmsys::ofstream ofs;
      if (ReOpenInfoFile(ofs, qrc.InfoFile)) {
        {
          ofs << "# Job\n";
          auto OfsWrite = [&ofs](const char* key, std::string const& value) {
            ofs << "set(" << key << " "
                << cmOutputConverter::EscapeForCMake(value) << ")\n";
1011

1012
1013
1014
1015
1016
1017
1018
          };
          OfsWrite("ARCC_SETTINGS_FILE", qrc.SettingsFile);
          OfsWrite("ARCC_SOURCE", qrc.QrcFile);
          OfsWrite("ARCC_OUTPUT", qrc.RccFile);
          OfsWrite("ARCC_OPTIONS", cmJoin(qrc.Options, ";"));
          OfsWrite("ARCC_INPUTS", cmJoin(qrc.Resources, ";"));
        }
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
        {
          ofs << "# Configurations options\n";
          auto OfsWriteMap = [&ofs](
            const char* key, std::map<std::string, std::string> const& map) {
            for (auto const& item : map) {
              ofs << "set(" << key << "_" << item.first << " "
                  << cmOutputConverter::EscapeForCMake(item.second) << ")\n";
            }
          };
          OfsWriteMap("ARCC_CONFIG_SUFFIX", configSuffixes);
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038

          // Settings files (only require for multi configuration generators)
          if (this->MultiConfig != cmQtAutoGen::SINGLE) {
            std::map<std::string, std::string> settingsFiles;
            for (std::string const& cfg : this->ConfigsList) {
              settingsFiles[cfg] =
                cmQtAutoGen::AppendFilenameSuffix(qrc.SettingsFile, "_" + cfg);
            }
            OfsWriteMap("ARCC_SETTINGS_FILE", settingsFiles);
          }
1039
        }
1040
1041
1042
1043
1044
1045
      } else {
        break;
      }
    }
  }
}
1046

1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
void cmQtAutoGeneratorInitializer::SetupCustomTargetsMoc()
{
  cmLocalGenerator* localGen = this->Target->GetLocalGenerator();
  cmMakefile* makefile = this->Target->Target->GetMakefile();

  AddDefinitionEscaped(makefile, "_moc_skip", this->MocSkip);
  AddDefinitionEscaped(makefile, "_moc_options",
                       GetSafeProperty(this->Target, "AUTOMOC_MOC_OPTIONS"));
  AddDefinitionEscaped(makefile, "_moc_relaxed_mode",
                       makefile->IsOn("CMAKE_AUTOMOC_RELAXED_MODE") ? "TRUE"
                                                                    : "FALSE");