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 "cmDuration.h"
10
#include "cmFilePathChecksum.h"
11
#include "cmGeneratorTarget.h"
12
#include "cmGlobalGenerator.h"
13
#include "cmLinkItem.h"
14 15
#include "cmLocalGenerator.h"
#include "cmMakefile.h"
16
#include "cmOutputConverter.h"
17
#include "cmPolicies.h"
18
#include "cmProcessOutput.h"
19
#include "cmSourceFile.h"
Daniel Pfeifer's avatar
Daniel Pfeifer committed
20
#include "cmSourceGroup.h"
21
#include "cmState.h"
22
#include "cmStateTypes.h"
23 24
#include "cmSystemTools.h"
#include "cmTarget.h"
25
#include "cm_sys_stat.h"
26
#include "cmake.h"
27
#include "cmsys/FStream.hxx"
28
#include "cmsys/SystemInformation.hxx"
29

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

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

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

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

57 58 59 60 61 62 63 64 65 66 67 68 69 70
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;
}

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

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

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

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

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

166 167 168 169 170 171
static std::string FileProjectRelativePath(cmMakefile* makefile,
                                           std::string const& fileName)
{
  std::string res;
  {
    std::string pSource = cmSystemTools::RelativePath(
172
      makefile->GetCurrentSourceDirectory(), fileName);
173
    std::string pBinary = cmSystemTools::RelativePath(
174
      makefile->GetCurrentBinaryDirectory(), fileName);
175 176 177 178 179 180 181 182 183 184 185
    if (pSource.size() < pBinary.size()) {
      res = std::move(pSource);
    } else if (pBinary.size() < fileName.size()) {
      res = std::move(pBinary);
    } else {
      res = fileName;
    }
  }
  return res;
}

186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
/* @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;
}

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

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

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

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

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

    // FIXME: Visual Studio does not support per-config sources, yet.
    //        (EXCLUDED_SOURCE_FILE_NAMES)
    // if (globalGen->GetName().find("Visual Studio") != std::string::npos) {
271
    //  return MultiConfigT::MULTI;
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
    //}
  }

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

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

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

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

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

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

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

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

365
  // Add autogen includes directory to the origin target INCLUDE_DIRECTORIES
366 367
  if (this->MocEnabled || this->UicEnabled) {
    std::string includeDir = this->DirBuild + "/include";
368
    if (this->MultiConfig != MultiConfigT::SINGLE) {
369
      includeDir += "_$<CONFIG>";
370
    }
371
    this->Target->AddIncludeDirectory(includeDir, true);
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
  // 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,
414
        cmSystemTools::OUTPUT_NONE, cmDuration::zero(), cmProcessOutput::Auto);
415 416 417 418 419 420 421 422 423
      if (result && retVal == 0 &&
          rccStdOut.find("--list") != std::string::npos) {
        this->RccListOptions.push_back("--list");
      } else {
        this->RccListOptions.push_back("-list");
      }
    }
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

846 847
      // Add link library target dependencies to the autogen target
      // dependencies
848 849 850 851 852 853 854 855 856 857 858 859 860 861
      {
        // 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]++;
862
              }
863 864 865
            }
          }
        }
866 867 868 869 870
        for (auto const& item : commonTargets) {
          if (item.second == this->ConfigsList.size()) {
            autogenDependTargets.insert(item.first->Target);
          }
        }
871 872
      }

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

      // Forward origin utilities to autogen target
885
      for (std::string const& depName : this->Target->Target->GetUtilities()) {
886
        autogenTarget->AddUtility(depName, makefile);