cmQtAutoGenInitializer.cxx 49.5 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
#include "cmQtAutoGenInitializer.h"
5

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
#include "cmsys/SystemInformation.hxx"
28

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

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

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

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

56
57
58
59
60
61
62
63
64
65
66
67
68
69
static std::size_t GetParallelCPUCount()
{
  static std::size_t count = 0;
  // Detect only on the first call
  if (count == 0) {
    cmsys::SystemInformation info;
    info.RunCPUCheck();
    count = info.GetNumberOfPhysicalCPU();
    count = std::max<std::size_t>(count, 1);
    count = std::min<std::size_t>(count, cmQtAutoGen::ParallelMax);
  }
  return count;
}

70
static void AddDefinitionEscaped(cmMakefile* makefile, const char* key,
71
                                 std::string const& value)
72
73
74
75
76
77
78
79
80
81
82
83
{
  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());
}

84
85
86
87
88
89
90
static void AddDefinitionEscaped(cmMakefile* makefile, const char* key,
                                 const std::set<std::string>& values)
{
  makefile->AddDefinition(
    key, cmOutputConverter::EscapeForCMake(cmJoin(values, ";")).c_str());
}

91
92
93
94
95
96
97
98
99
100
101
102
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(
103
                                 cmJoin(seplist, cmQtAutoGen::ListSep))
104
105
106
                                 .c_str());
}

107
static bool AddToSourceGroup(cmMakefile* makefile, std::string const& fileName,
108
                             cmQtAutoGen::GeneratorT genType)
109
{
Daniel Pfeifer's avatar
Daniel Pfeifer committed
110
  cmSourceGroup* sourceGroup = nullptr;
111
112
  // Acquire source group
  {
113
114
115
116
117
118
    std::string property;
    std::string groupName;
    {
      std::array<std::string, 2> props;
      // Use generator specific group name
      switch (genType) {
119
        case cmQtAutoGen::GeneratorT::MOC:
120
121
          props[0] = "AUTOMOC_SOURCE_GROUP";
          break;
122
        case cmQtAutoGen::GeneratorT::RCC:
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
          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;
        }
      }
138
139
    }
    // Generate a source group on demand
140
    if (!groupName.empty()) {
141
      sourceGroup = makefile->GetOrCreateSourceGroup(groupName);
Daniel Pfeifer's avatar
Daniel Pfeifer committed
142
      if (sourceGroup == nullptr) {
143
144
145
146
147
148
        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());
149
150
151
152
        return false;
      }
    }
  }
Daniel Pfeifer's avatar
Daniel Pfeifer committed
153
  if (sourceGroup != nullptr) {
154
155
156
157
158
    sourceGroup->AddGroupFile(fileName);
  }
  return true;
}

159
static void AddCleanFile(cmMakefile* makefile, std::string const& fileName)
160
161
162
163
164
{
  makefile->AppendProperty("ADDITIONAL_MAKE_CLEAN_FILES", fileName.c_str(),
                           false);
}

165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
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;
}

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
/* @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;
}

229
cmQtAutoGenInitializer::cmQtAutoGenInitializer(
230
231
232
233
234
235
236
  cmGeneratorTarget* target, bool mocEnabled, bool uicEnabled, bool rccEnabled,
  std::string const& qtVersionMajor)
  : Target(target)
  , MocEnabled(mocEnabled)
  , UicEnabled(uicEnabled)
  , RccEnabled(rccEnabled)
  , QtVersionMajor(qtVersionMajor)
237
  , MultiConfig(MultiConfigT::WRAPPER)
238
{
239
240
  this->QtVersionMinor =
    cmQtAutoGenInitializer::GetQtMinorVersion(target, this->QtVersionMajor);
241
}
242

243
void cmQtAutoGenInitializer::InitCustomTargets()
244
245
246
247
{
  cmMakefile* makefile = this->Target->Target->GetMakefile();
  cmLocalGenerator* localGen = this->Target->GetLocalGenerator();
  cmGlobalGenerator* globalGen = localGen->GetGlobalGenerator();
248

249
250
251
252
  // Configurations
  this->ConfigDefault = makefile->GetConfigurations(this->ConfigsList);
  if (this->ConfigsList.empty()) {
    this->ConfigsList.push_back(this->ConfigDefault);
253
  }
254
255

  // Multi configuration
256
  {
257
    if (!globalGen->IsMultiConfig()) {
258
      this->MultiConfig = MultiConfigT::SINGLE;
259
    }
260

261
262
263
    // FIXME: Xcode does not support per-config sources, yet.
    //        (EXCLUDED_SOURCE_FILE_NAMES)
    // if (globalGen->GetName().find("Xcode") != std::string::npos) {
264
    //  return MultiConfigT::MULTI;
265
266
267
268
269
    //}

    // FIXME: Visual Studio does not support per-config sources, yet.
    //        (EXCLUDED_SOURCE_FILE_NAMES)
    // if (globalGen->GetName().find("Visual Studio") != std::string::npos) {
270
    //  return MultiConfigT::MULTI;
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
    //}
  }

  // 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;
298
    }
299
300
301
302
303
    cmSystemTools::ConvertToUnixSlashes(this->DirBuild);

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

306
  // Autogen files
307
  {
308
309
    this->AutogenInfoFile = this->DirInfo;
    this->AutogenInfoFile += "/AutogenInfo.cmake";
310

311
    this->AutogenSettingsFile = this->DirInfo;
312
    this->AutogenSettingsFile += "/AutogenOldSettings.txt";
313
  }
314

315
316
317
318
319
320
321
322
323
324
325
326
327
328
  // 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;
329
330
    }
  }
331

332
333
334
  std::set<std::string> autogenDependFiles;
  std::set<cmTarget*> autogenDependTargets;
  std::vector<std::string> autogenProvides;
335

336
337
338
  // Remove build directories on cleanup
  AddCleanFile(makefile, this->DirBuild);
  // Remove old settings on cleanup
339
  {
340
341
    std::string base = this->DirInfo;
    base += "/AutogenOldSettings";
342
    if (this->MultiConfig == MultiConfigT::SINGLE) {
343
344
345
346
347
348
349
350
      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);
351
      }
352
    }
353
354
  }

355
  // Add moc compilation to generated files list
356
357
  if (this->MocEnabled) {
    std::string const mocsComp = this->DirBuild + "/mocs_compilation.cpp";
358
    auto files = this->AddGeneratedSource(mocsComp, GeneratorT::MOC);
359
360
361
    for (std::string& file : files) {
      autogenProvides.push_back(std::move(file));
    }
362
  }
363

364
  // Add autogen includes directory to the origin target INCLUDE_DIRECTORIES
365
366
  if (this->MocEnabled || this->UicEnabled) {
    std::string includeDir = this->DirBuild + "/include";
367
    if (this->MultiConfig != MultiConfigT::SINGLE) {
368
      includeDir += "_$<CONFIG>";
369
    }
370
    this->Target->AddIncludeDirectory(includeDir, true);
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
  // 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");
      }
    }
  }

423
  // Extract relevant source files
424
425
  std::vector<std::string> generatedSources;
  std::vector<std::string> generatedHeaders;
426
  {
427
    std::string const qrcExt = "qrc";
428
    std::vector<cmSourceFile*> srcFiles;
429
    this->Target->GetConfigCommonSourceFiles(srcFiles);
430
    for (cmSourceFile* sf : srcFiles) {
431
432
433
434
      if (sf->GetPropertyAsBool("SKIP_AUTOGEN")) {
        continue;
      }
      // sf->GetExtension() is only valid after sf->GetFullPath() ...
435
436
      std::string const& fPath = sf->GetFullPath();
      std::string const& ext = sf->GetExtension();
437
      // Register generated files that will be scanned by moc or uic
438
      if (this->MocEnabled || this->UicEnabled) {
439
        cmSystemTools::FileFormat const fileType =
440
441
442
          cmSystemTools::GetFileFormat(ext.c_str());
        if ((fileType == cmSystemTools::CXX_FILE_FORMAT) ||
            (fileType == cmSystemTools::HEADER_FILE_FORMAT)) {
443
          std::string const absPath = cmSystemTools::GetRealPath(fPath);
444
445
          if ((this->MocEnabled && !sf->GetPropertyAsBool("SKIP_AUTOMOC")) ||
              (this->UicEnabled && !sf->GetPropertyAsBool("SKIP_AUTOUIC"))) {
446
447
448
449
            // Register source
            const bool generated = sf->GetPropertyAsBool("GENERATED");
            if (fileType == cmSystemTools::HEADER_FILE_FORMAT) {
              if (generated) {
450
                generatedHeaders.push_back(absPath);
451
              } else {
452
                this->Headers.push_back(absPath);
453
454
455
              }
            } else {
              if (generated) {
456
                generatedSources.push_back(absPath);
457
              } else {
458
                this->Sources.push_back(absPath);
459
              }
460
461
462
            }
          }
        }
463
464
      }
      // Register rcc enabled files
465
      if (this->RccEnabled && (ext == qrcExt) &&
466
          !sf->GetPropertyAsBool("SKIP_AUTORCC")) {
467
468
        // Register qrc file
        {
469
470
471
472
473
          Qrc qrc;
          qrc.QrcFile = cmSystemTools::GetRealPath(fPath);
          qrc.QrcName =
            cmSystemTools::GetFilenameWithoutLastExtension(qrc.QrcFile);
          qrc.Generated = sf->GetPropertyAsBool("GENERATED");
474
475
          // RCC options
          {
476
            std::string const opts = GetSafeProperty(sf, "AUTORCC_OPTIONS");
477
            if (!opts.empty()) {
478
              cmSystemTools::ExpandListArgument(opts, qrc.Options);
479
480
            }
          }
481
          this->Qrcs.push_back(std::move(qrc));
482
        }
483
484
485
486
487
488
      }
    }
    // 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.
489
490
491
492
    this->Target->ClearSourcesCache();
  }
  // Read skip files from makefile sources
  if (this->MocEnabled || this->UicEnabled) {
493
494
    std::string pathError;
    for (cmSourceFile* sf : makefile->GetSourceFiles()) {
495
      // sf->GetExtension() is only valid after sf->GetFullPath() ...
496
497
498
499
500
501
502
      // Since we're iterating over source files that might be not in the
      // target we need to check for path errors (not existing files).
      std::string const& fPath = sf->GetFullPath(&pathError);
      if (!pathError.empty()) {
        pathError.clear();
        continue;
      }
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
      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);
        }
      }
    }
524
  }
525

526
  // Process GENERATED sources and headers
527
  if (!generatedSources.empty() || !generatedHeaders.empty()) {
528
529
530
    // Check status of policy CMP0071
    bool policyAccept = false;
    bool policyWarn = false;
531
    cmPolicies::PolicyStatus const CMP0071_status =
532
      makefile->GetPolicyStatus(cmPolicies::CMP0071);
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
    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
550
      for (std::string const& absFile : generatedHeaders) {
551
        this->Headers.push_back(absFile);
552
        autogenDependFiles.insert(absFile);
553
      }
554
      for (std::string const& absFile : generatedSources) {
555
        this->Sources.push_back(absFile);
556
        autogenDependFiles.insert(absFile);
557
      }
558
559
560
561
562
563
    } else {
      if (policyWarn) {
        std::string msg;
        msg += cmPolicies::GetPolicyWarning(cmPolicies::CMP0071);
        msg += "\n";
        std::string tools;
564
        std::string property;
565
        if (this->MocEnabled && this->UicEnabled) {
566
567
          tools = "AUTOMOC and AUTOUIC";
          property = "SKIP_AUTOGEN";
568
        } else if (this->MocEnabled) {
569
570
          tools = "AUTOMOC";
          property = "SKIP_AUTOMOC";
571
        } else if (this->UicEnabled) {
572
573
          tools = "AUTOUIC";
          property = "SKIP_AUTOUIC";
574
        }
575
576
577
        msg += "For compatibility, CMake is excluding the GENERATED source "
               "file(s):\n";
        for (const std::string& absFile : generatedHeaders) {
578
          msg.append("  ").append(Quoted(absFile)).append("\n");
579
        }
580
        for (const std::string& absFile : generatedSources) {
581
          msg.append("  ").append(Quoted(absFile)).append("\n");
582
        }
583
584
585
586
587
588
589
590
591
592
        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";
593
        makefile->IssueMessage(cmake::AUTHOR_WARNING, msg);
594
      }
595
    }
596
597
598
    // Clear lists
    generatedSources.clear();
    generatedHeaders.clear();
599
  }
600
  // Sort headers and sources
601
602
603
604
  if (this->MocEnabled || this->UicEnabled) {
    std::sort(this->Headers.begin(), this->Headers.end());
    std::sort(this->Sources.begin(), this->Sources.end());
  }
605

606
  // Process qrc files
607
608
  if (!this->Qrcs.empty()) {
    const bool QtV5 = (this->QtVersionMajor == "5");
609
610
611
    // Target rcc options
    std::vector<std::string> optionsTarget;
    cmSystemTools::ExpandListArgument(
612
      GetSafeProperty(this->Target, "AUTORCC_OPTIONS"), optionsTarget);
613

614
    // Check if file name is unique
615
616
617
618
619
    for (Qrc& qrc : this->Qrcs) {
      qrc.Unique = true;
      for (Qrc const& qrc2 : this->Qrcs) {
        if ((&qrc != &qrc2) && (qrc.QrcName == qrc2.QrcName)) {
          qrc.Unique = false;
620
621
          break;
        }
622
      }
623
    }
624
    // Path checksum and file names
625
    {
626
      cmFilePathChecksum const fpathCheckSum(makefile);
627
628
      for (Qrc& qrc : this->Qrcs) {
        qrc.PathChecksum = fpathCheckSum.getPart(qrc.QrcFile);
629
        // RCC output file name
630
        {
631
632
          std::string rccFile = this->DirBuild + "/";
          rccFile += qrc.PathChecksum;
633
          rccFile += "/qrc_";
634
          rccFile += qrc.QrcName;
635
          rccFile += ".cpp";
636
          qrc.RccFile = std::move(rccFile);
637
638
        }
        {
639
          std::string base = this->DirInfo;
640
          base += "/RCC";
641
642
643
          base += qrc.QrcName;
          if (!qrc.Unique) {
            base += qrc.PathChecksum;
644
          }
645
646
647
          qrc.InfoFile = base;
          qrc.InfoFile += "Info.cmake";
          qrc.SettingsFile = base;
648
          qrc.SettingsFile += "Settings.txt";
649
        }
650
651
652
      }
    }
    // RCC options
653
    for (Qrc& qrc : this->Qrcs) {
654
655
656
      // Target options
      std::vector<std::string> opts = optionsTarget;
      // Merge computed "-name XYZ" option
657
      {
658
        std::string name = qrc.QrcName;
659
660
        // Replace '-' with '_'. The former is not valid for symbol names.
        std::replace(name.begin(), name.end(), '-', '_');
661
        if (!qrc.Unique) {
662
          name += "_";
663
          name += qrc.PathChecksum;
664
        }
665
666
667
        std::vector<std::string> nameOpts;
        nameOpts.emplace_back("-name");
        nameOpts.emplace_back(std::move(name));
668
        RccMergeOptions(opts, nameOpts, QtV5);
669
      }
670
      // Merge file option
671
      RccMergeOptions(opts, qrc.Options, QtV5);
672
      qrc.Options = std::move(opts);
673
    }
674
    for (Qrc& qrc : this->Qrcs) {
675
      // Register file at target
676
      std::vector<std::string> const ccOutput =
677
        this->AddGeneratedSource(qrc.RccFile, GeneratorT::RCC);
678
679

      cmCustomCommandLines commandLines;
680
      {
681
682
683
684
        cmCustomCommandLine currentLine;
        currentLine.push_back(cmSystemTools::GetCMakeCommand());
        currentLine.push_back("-E");
        currentLine.push_back("cmake_autorcc");
685
        currentLine.push_back(qrc.InfoFile);
686
687
        currentLine.push_back("$<CONFIGURATION>");
        commandLines.push_back(std::move(currentLine));
688
      }
689
      std::string ccComment = "Automatic RCC for ";
690
      ccComment += FileProjectRelativePath(makefile, qrc.QrcFile);
691

692
      if (qrc.Generated) {
693
694
695
        // Create custom rcc target
        std::string ccName;
        {
696
          ccName = this->Target->GetName();
697
          ccName += "_arcc_";
698
699
          ccName += qrc.QrcName;
          if (!qrc.Unique) {
700
            ccName += "_";
701
            ccName += qrc.PathChecksum;
702
703
          }
          std::vector<std::string> ccDepends;
704
          // Add the .qrc and info file to the custom target dependencies
705
          ccDepends.push_back(qrc.QrcFile);
706
          ccDepends.push_back(qrc.InfoFile);
707
708

          cmTarget* autoRccTarget = makefile->AddUtilityCommand(
709
710
711
            ccName, cmMakefile::TargetOrigin::Generator, true,
            this->DirWork.c_str(), ccOutput, ccDepends, commandLines, false,
            ccComment.c_str());
712
713
714
715
716
          // Create autogen generator target
          localGen->AddGeneratorTarget(
            new cmGeneratorTarget(autoRccTarget, localGen));

          // Set FOLDER property in autogen target
717
718
          if (!this->AutogenFolder.empty()) {
            autoRccTarget->SetProperty("FOLDER", this->AutogenFolder.c_str());
719
720
721
          }
        }
        // Add autogen target to the origin target dependencies
722
        this->Target->Target->AddUtility(ccName, makefile);
723
      } else {
724
        // Create custom rcc command
725
        {
726
727
          std::vector<std::string> ccByproducts;
          std::vector<std::string> ccDepends;
728
          // Add the .qrc and info file to the custom command dependencies
729
          ccDepends.push_back(qrc.QrcFile);
730
          ccDepends.push_back(qrc.InfoFile);
731
732
733
734

          // Add the resource files to the dependencies
          {
            std::string error;
735
            if (RccListInputs(qrc.QrcFile, qrc.Resources, error)) {
736
              for (std::string const& fileName : qrc.Resources) {
737
738
739
740
741
                // Add resource file to the custom command dependencies
                ccDepends.push_back(fileName);
              }
            } else {
              cmSystemTools::Error(error.c_str());
742
            }
743
          }
744
745
746
          makefile->AddCustomCommandToOutput(ccOutput, ccByproducts, ccDepends,
                                             /*main_dependency*/ std::string(),
                                             commandLines, ccComment.c_str(),
747
                                             this->DirWork.c_str());
748
        }
749
        // Reconfigure when .qrc file changes
750
        makefile->AddCMakeDependFile(qrc.QrcFile);
751
752
753
754
      }
    }
  }

755
  // Create _autogen target
756
  if (this->MocEnabled || this->UicEnabled) {
757
758
759
    // Add user defined autogen target dependencies
    {
      std::string const deps =
760
        GetSafeProperty(this->Target, "AUTOGEN_TARGET_DEPENDS");
761
762
763
764
765
766
767
768
769
770
771
      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);
          }
772
        }
773
774
775
      }
    }

776
777
778
    // Compose target comment
    std::string autogenComment;
    {
779
780
781
      std::string tools;
      if (this->MocEnabled) {
        tools += "MOC";
782
      }
783
784
785
      if (this->UicEnabled) {
        if (!tools.empty()) {
          tools += " and ";
786
        }
787
        tools += "UIC";
788
      }
789
790
791
792
      autogenComment = "Automatic ";
      autogenComment += tools;
      autogenComment += " for target ";
      autogenComment += this->Target->GetName();
793
    }
794
795
796
797
798
799
800
801

    // Compose command lines
    cmCustomCommandLines commandLines;
    {
      cmCustomCommandLine currentLine;
      currentLine.push_back(cmSystemTools::GetCMakeCommand());
      currentLine.push_back("-E");
      currentLine.push_back("cmake_autogen");
802
      currentLine.push_back(this->AutogenInfoFile);
803
804
      currentLine.push_back("$<CONFIGURATION>");
      commandLines.push_back(std::move(currentLine));
805
806
    }

807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
    // 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) {
827
        this->Target->Target->AddUtility(depTarget->GetName(), makefile);
828
      }
829

830
831
832
833
834
835
836
837
838
      // 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(),
839
                         this->DirWork.c_str());
840
841
      cc.SetEscapeOldStyle(false);
      cc.SetEscapeAllowMakeVars(true);
842
      this->Target->Target->AddPreBuildCommand(cc);
843
    } else {
844

845
846
      // Add link library target dependencies to the autogen target
      // dependencies
847
848
849
850
851
852
853
854
855
856
857
858
859
860
      {
        // add_dependencies/addUtility do not support generator expressions.
        // We depend only on the libraries found in all configs therefore.
        std::map<cmGeneratorTarget const*, std::size_t> commonTargets;
        for (std::string const& config : this->ConfigsList) {
          cmLinkImplementationLibraries const* libs =
            this->Target->GetLinkImplementationLibraries(config);
          if (libs != nullptr) {
            for (cmLinkItem const& item : libs->Libraries) {
              cmGeneratorTarget const* libTarget = item.Target;
              if ((libTarget != nullptr) &&
                  !StaticLibraryCycle(this->Target, libTarget, config)) {
                // Increment target config count
                commonTargets[libTarget]++;
861
              }
862
863
864
            }
          }
        }
865
866
867
868
869
        for (auto const& item : commonTargets) {
          if (item.second == this->ConfigsList.size()) {
            autogenDependTargets.insert(item.first->Target);
          }
        }
870
871
      }

872
873
      // Create autogen target
      cmTarget* autogenTarget = makefile->AddUtilityCommand(
874
        this->AutogenTargetName, cmMakefile::TargetOrigin::Generator, true,
875
876
877
        this->DirWork.c_str(), /*byproducts=*/autogenProvides,
        std::vector<std::string>(autogenDependFiles.begin(),
                                 autogenDependFiles.end()),
878
        commandLines, false, autogenComment.c_str());
879
880
881
882
883
      // Create autogen generator target
      localGen->AddGeneratorTarget(
        new cmGeneratorTarget(autogenTarget, localGen));

      // Forward origin utilities to autogen target
884
      for (std::string const& depName : this->Target->Target->GetUtilities()) {
885
        autogenTarget->AddUtility(depName, makefile);
886
      }
887
888
889
      // Add additional autogen target dependencies to autogen target
      for (cmTarget* depTarget : autogenDependTargets) {
        autogenTarget->AddUtility(depTarget->GetName(), makefile);
890
      }
891
892

      // Set FOLDER property in autogen target
893
894
      if (!this->AutogenFolder.empty()) {
        autogenTarget->SetProperty("FOLDER", this->AutogenFolder.c_str());
895
      }
896

897
      // Add autogen target to the origin target dependencies
898
      this->Target->Target->AddUtility(this->AutogenTargetName, makefile);
899
    }
900
  }
901
902
}

903
void cmQtAutoGenInitializer::SetupCustomTargets()
904
{
905
  cmMakefile* makefile = this->Target->Target->GetMakefile();
906
907
908
909
910

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

911
  // Configuration suffixes
912
  std::map<std::string, std::string> configSuffixes;
913
914
915
916
  for (std::string const& cfg : this->ConfigsList) {
    std::string& suffix = configSuffixes[cfg];
    suffix = "_";
    suffix += cfg;
917
  }
918
919

  // Basic setup
920
  AddDefinitionEscaped(makefile, "_multi_config",
921
                       MultiConfigName(this->MultiConfig));
922
  AddDefinitionEscaped(makefile, "_build_dir", this->DirBuild);
923
924
925
926
927
928
929
930
  {
    std::string parallel = GetSafeProperty(this->Target, "AUTOGEN_PARALLEL");
    // Autodetect number of CPUs
    if (parallel.empty() || (parallel == "AUTO")) {
      parallel = std::to_string(GetParallelCPUCount());
    }
    AddDefinitionEscaped(makefile, "_parallel", parallel);
  }
931
932

  if (this->MocEnabled || this->UicEnabled) {
933
    AddDefinitionEscaped(makefile, "_qt_version_major", this->QtVersionMajor);
934
935
936
937
938
939
940
    AddDefinitionEscaped(makefile, "_settings_file",
                         this->AutogenSettingsFile);
    AddDefinitionEscaped(makefile, "_sources", this->Sources);
    AddDefinitionEscaped(makefile, "_headers", this->Headers);

    if (this->MocEnabled) {
      this->SetupCustomTargetsMoc();
941
    }
942
943
    if (this->UicEnabled) {
      this->SetupCustomTargetsUic();
944
    }
945
  }
946
  if (this->RccEnabled) {
947
948
949
    AddDefinitionEscaped(makefile, "_qt_rcc_executable", this->RccExecutable);
    AddDefinitionEscaped(makefile, "_qt_rcc_list_options",
                         this->RccListOptions);
950
  }
951

952
  // Create info directory on demand
953
  if (!cmSystemTools::MakeDirectory(this->DirInfo)) {