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

6
#include "cmAlgorithms.h"
7
#include "cmCustomCommand.h"
8
#include "cmCustomCommandLines.h"
9
#include "cmDuration.h"
10
#include "cmFilePathChecksum.h"
11
#include "cmGeneratedFileStream.h"
12
#include "cmGeneratorTarget.h"
13
#include "cmGlobalGenerator.h"
14
#include "cmLinkItem.h"
15 16
#include "cmLocalGenerator.h"
#include "cmMakefile.h"
17
#include "cmOutputConverter.h"
18
#include "cmPolicies.h"
19
#include "cmProcessOutput.h"
20
#include "cmSourceFile.h"
Daniel Pfeifer's avatar
Daniel Pfeifer committed
21
#include "cmSourceGroup.h"
22
#include "cmState.h"
23
#include "cmStateTypes.h"
24 25 26
#include "cmSystemTools.h"
#include "cmTarget.h"
#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 41 42 43 44 45 46 47 48 49 50 51 52 53
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;
}

54
static bool AddToSourceGroup(cmMakefile* makefile, std::string const& fileName,
55
                             cmQtAutoGen::GeneratorT genType)
56
{
Daniel Pfeifer's avatar
Daniel Pfeifer committed
57
  cmSourceGroup* sourceGroup = nullptr;
58 59
  // Acquire source group
  {
60 61 62 63 64 65
    std::string property;
    std::string groupName;
    {
      std::array<std::string, 2> props;
      // Use generator specific group name
      switch (genType) {
66
        case cmQtAutoGen::GeneratorT::MOC:
67 68
          props[0] = "AUTOMOC_SOURCE_GROUP";
          break;
69
        case cmQtAutoGen::GeneratorT::RCC:
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
          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;
        }
      }
85 86
    }
    // Generate a source group on demand
87
    if (!groupName.empty()) {
88
      sourceGroup = makefile->GetOrCreateSourceGroup(groupName);
Daniel Pfeifer's avatar
Daniel Pfeifer committed
89
      if (sourceGroup == nullptr) {
90 91 92 93 94 95
        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());
96 97 98 99
        return false;
      }
    }
  }
Daniel Pfeifer's avatar
Daniel Pfeifer committed
100
  if (sourceGroup != nullptr) {
101 102 103 104 105
    sourceGroup->AddGroupFile(fileName);
  }
  return true;
}

106
static void AddCleanFile(cmMakefile* makefile, std::string const& fileName)
107 108 109 110 111
{
  makefile->AppendProperty("ADDITIONAL_MAKE_CLEAN_FILES", fileName.c_str(),
                           false);
}

112 113 114 115 116 117
static std::string FileProjectRelativePath(cmMakefile* makefile,
                                           std::string const& fileName)
{
  std::string res;
  {
    std::string pSource = cmSystemTools::RelativePath(
118
      makefile->GetCurrentSourceDirectory(), fileName);
119
    std::string pBinary = cmSystemTools::RelativePath(
120
      makefile->GetCurrentBinaryDirectory(), fileName);
121 122 123 124 125 126 127 128 129 130 131
    if (pSource.size() < pBinary.size()) {
      res = std::move(pSource);
    } else if (pBinary.size() < fileName.size()) {
      res = std::move(pBinary);
    } else {
      res = fileName;
    }
  }
  return res;
}

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
/* @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;
}

176
cmQtAutoGenInitializer::cmQtAutoGenInitializer(
177 178 179
  cmGeneratorTarget* target, bool mocEnabled, bool uicEnabled, bool rccEnabled,
  std::string const& qtVersionMajor)
  : Target(target)
180
  , MultiConfig(false)
181
  , QtVersionMajor(qtVersionMajor)
182
{
183 184 185 186
  Moc.Enabled = mocEnabled;
  Uic.Enabled = uicEnabled;
  Rcc.Enabled = rccEnabled;

187 188
  this->QtVersionMinor =
    cmQtAutoGenInitializer::GetQtMinorVersion(target, this->QtVersionMajor);
189
}
190

191
bool cmQtAutoGenInitializer::InitCustomTargets()
192 193 194 195
{
  cmMakefile* makefile = this->Target->Target->GetMakefile();
  cmLocalGenerator* localGen = this->Target->GetLocalGenerator();
  cmGlobalGenerator* globalGen = localGen->GetGlobalGenerator();
196

197
  // Verbosity
198 199 200 201 202 203 204
  this->Verbosity = makefile->GetSafeDefinition("CMAKE_AUTOGEN_VERBOSE");
  if (!this->Verbosity.empty()) {
    unsigned long iVerb = 0;
    if (!cmSystemTools::StringToULong(this->Verbosity.c_str(), &iVerb)) {
      // Non numeric verbosity
      this->Verbosity =
        cmSystemTools::IsOn(this->Verbosity.c_str()) ? "1" : "0";
205 206 207
    }
  }

208
  // Configurations
209
  this->MultiConfig = globalGen->IsMultiConfig();
210 211 212
  this->ConfigDefault = makefile->GetConfigurations(this->ConfigsList);
  if (this->ConfigsList.empty()) {
    this->ConfigsList.push_back(this->ConfigDefault);
213
  }
214

215 216 217 218 219 220 221
  // Parallel processing
  this->Parallel = this->Target->GetSafeProperty("AUTOGEN_PARALLEL");
  if (this->Parallel.empty() || (this->Parallel == "AUTO")) {
    // Autodetect number of CPUs
    this->Parallel = std::to_string(GetParallelCPUCount());
  }

222 223 224 225 226 227 228 229 230 231 232 233 234
  // 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();
235
    this->DirInfo += '/';
236 237 238 239 240
    this->DirInfo += this->AutogenTargetName;
    this->DirInfo += ".dir";
    cmSystemTools::ConvertToUnixSlashes(this->DirInfo);

    // Autogen build dir
241
    this->DirBuild = this->Target->GetSafeProperty("AUTOGEN_BUILD_DIR");
242 243
    if (this->DirBuild.empty()) {
      this->DirBuild = cbd;
244
      this->DirBuild += '/';
245
      this->DirBuild += this->AutogenTargetName;
246
    }
247
    cmSystemTools::ConvertToUnixSlashes(this->DirBuild);
248 249
    // Remove build directories on cleanup
    AddCleanFile(makefile, this->DirBuild);
250 251 252 253

    // Working directory
    this->DirWork = cbd;
    cmSystemTools::ConvertToUnixSlashes(this->DirWork);
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268

    // Include directory
    this->DirInclude = this->DirBuild;
    this->DirInclude += "/include";
    if (this->MultiConfig) {
      this->DirInclude += "_$<CONFIG>";
    }
    if (this->MultiConfig) {
      for (std::string const& cfg : this->ConfigsList) {
        std::string& dir = this->DirConfigInclude[cfg];
        dir = this->DirBuild;
        dir += "/include_";
        dir += cfg;
      }
    }
269
  }
270

271
  // Autogen info and settings files
272
  {
273 274
    this->AutogenInfoFile = this->DirInfo;
    this->AutogenInfoFile += "/AutogenInfo.cmake";
275

276
    this->AutogenSettingsFile = this->DirInfo;
277
    this->AutogenSettingsFile += "/AutogenOldSettings.txt";
278 279 280 281 282 283 284 285 286 287

    if (this->MultiConfig) {
      for (std::string const& cfg : this->ConfigsList) {
        std::string& filename = this->AutogenConfigSettingsFile[cfg];
        filename = AppendFilenameSuffix(this->AutogenSettingsFile, "_" + cfg);
        AddCleanFile(makefile, filename);
      }
    } else {
      AddCleanFile(makefile, this->AutogenSettingsFile);
    }
288
  }
289

290 291 292 293 294 295 296 297 298 299
  // 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) {
300
      folder = this->Target->GetProperty("FOLDER");
301 302 303
    }
    if (folder != nullptr) {
      this->AutogenFolder = folder;
304 305
    }
  }
306

307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
  if (this->Moc.Enabled || this->Uic.Enabled) {
    // Init moc specific settings
    if (this->Moc.Enabled && !InitMoc()) {
      return false;
    }
    // Init uic specific settings
    if (this->Uic.Enabled && !InitUic()) {
      return false;
    }

    // Autogen target: Compute user defined dependencies
    {
      std::string const deps =
        this->Target->GetSafeProperty("AUTOGEN_TARGET_DEPENDS");
      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) {
            this->AutogenDependTargets.insert(depTarget);
          } else {
            this->AutogenDependFiles.insert(depName);
          }
        }
      }
    }
  }
  // Init rcc specific settings
  if (this->Rcc.Enabled && !InitRcc()) {
    return false;
  }

  // Add autogen include directory to the origin target INCLUDE_DIRECTORIES
  if (this->Moc.Enabled || this->Uic.Enabled ||
      (this->Rcc.Enabled && this->MultiConfig)) {
    this->Target->AddIncludeDirectory(this->DirInclude, true);
  }

  // Scan files
  if (!this->InitScanFiles()) {
    return false;
  }

  // Create autogen target
  if ((this->Moc.Enabled || this->Uic.Enabled) && !this->InitAutogenTarget()) {
    return false;
  }
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
  // Create rcc targets
  if (this->Rcc.Enabled && !this->InitRccTargets()) {
    return false;
  }

  return true;
}

bool cmQtAutoGenInitializer::InitMoc()
{
  cmMakefile* makefile = this->Target->Target->GetMakefile();
  cmLocalGenerator* localGen = this->Target->GetLocalGenerator();

  // Mocs compilation file
  this->Moc.MocsCompilation = this->DirBuild;
  this->Moc.MocsCompilation += "/mocs_compilation.cpp";

  // Moc predefs command
  if (this->Target->GetPropertyAsBool("AUTOMOC_COMPILER_PREDEFINES") &&
      this->QtVersionGreaterOrEqual(5, 8)) {
    this->Moc.PredefsCmd =
      makefile->GetSafeDefinition("CMAKE_CXX_COMPILER_PREDEFINES_COMMAND");
  }

  // Moc includes
382
  {
383 384 385
    bool const appendImplicit = (this->QtVersionMajor == "5");
    auto GetIncludeDirs =
      [this, localGen, appendImplicit](std::string const& cfg) -> std::string {
386 387 388 389
      // Get the include dirs for this target, without stripping the implicit
      // include dirs off, see
      // https://gitlab.kitware.com/cmake/cmake/issues/13667
      std::vector<std::string> dirs;
390 391
      localGen->GetIncludeDirectories(dirs, this->Target, "CXX", cfg, false,
                                      appendImplicit);
392 393 394 395 396 397
      return cmJoin(dirs, ";");
    };

    // Default configuration include directories
    this->Moc.Includes = GetIncludeDirs(this->ConfigDefault);
    // Other configuration settings
398
    if (this->MultiConfig) {
399
      for (std::string const& cfg : this->ConfigsList) {
400 401 402 403
        std::string dirs = GetIncludeDirs(cfg);
        if (dirs != this->Moc.Includes) {
          this->Moc.ConfigIncludes[cfg] = std::move(dirs);
        }
404
      }
405
    }
406 407
  }

408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
  // Moc compile definitions
  {
    auto GetCompileDefinitions =
      [this, localGen](std::string const& cfg) -> std::string {
      std::set<std::string> defines;
      localGen->AddCompileDefinitions(defines, this->Target, cfg, "CXX");
      return cmJoin(defines, ";");
    };

    // Default configuration defines
    this->Moc.Defines = GetCompileDefinitions(this->ConfigDefault);
    // Other configuration defines
    if (this->MultiConfig) {
      for (std::string const& cfg : this->ConfigsList) {
        std::string defines = GetCompileDefinitions(cfg);
        if (defines != this->Moc.Defines) {
          this->Moc.ConfigDefines[cfg] = std::move(defines);
        }
      }
    }
428
  }
429 430 431

  // Moc executable
  if (!GetMocExecutable()) {
432 433
    return false;
  }
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452

  return true;
}

bool cmQtAutoGenInitializer::InitUic()
{
  cmMakefile* makefile = this->Target->Target->GetMakefile();

  // Uic search paths
  {
    std::string const usp =
      this->Target->GetSafeProperty("AUTOUIC_SEARCH_PATHS");
    if (!usp.empty()) {
      cmSystemTools::ExpandListArgument(usp, this->Uic.SearchPaths);
      std::string const srcDir = makefile->GetCurrentSourceDirectory();
      for (std::string& path : this->Uic.SearchPaths) {
        path = cmSystemTools::CollapseFullPath(path, srcDir);
      }
    }
453
  }
454 455 456 457 458 459 460
  // Uic target options
  {
    auto UicGetOpts = [this](std::string const& cfg) -> std::string {
      std::vector<std::string> opts;
      this->Target->GetAutoUicOptions(opts, cfg);
      return cmJoin(opts, ";");
    };
461

462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
    // Default settings
    this->Uic.Options = UicGetOpts(this->ConfigDefault);

    // Configuration specific settings
    if (this->MultiConfig) {
      for (std::string const& cfg : this->ConfigsList) {
        std::string options = UicGetOpts(cfg);
        if (options != this->Uic.Options) {
          this->Uic.ConfigOptions[cfg] = std::move(options);
        }
      }
    }
  }
  // .ui files skip and options
  {
    std::string const uiExt = "ui";
    std::string pathError;
    for (cmSourceFile* sf : makefile->GetSourceFiles()) {
      // sf->GetExtension() is only valid after sf->GetFullPath() ...
      // 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;
      }
      if (sf->GetExtension() == uiExt) {
        std::string const absFile = cmSystemTools::GetRealPath(fPath);
        // Check if the .ui file should be skipped
        if (sf->GetPropertyAsBool("SKIP_AUTOUIC") ||
            sf->GetPropertyAsBool("SKIP_AUTOGEN")) {
          this->Uic.Skip.insert(absFile);
        }
        // Check if the .ui file has uic options
        std::string const uicOpts = sf->GetSafeProperty("AUTOUIC_OPTIONS");
        if (!uicOpts.empty()) {
          // Check if file isn't skipped
          if (this->Uic.Skip.count(absFile) == 0) {
            this->Uic.FileFiles.push_back(absFile);
            std::vector<std::string> optsVec;
            cmSystemTools::ExpandListArgument(uicOpts, optsVec);
            this->Uic.FileOptions.push_back(std::move(optsVec));
          }
        }
      }
507 508 509
    }
  }

510 511 512
  // Uic executable
  if (!GetUicExecutable()) {
    return false;
513 514
  }

515 516 517 518 519 520 521
  return true;
}

bool cmQtAutoGenInitializer::InitRcc()
{
  if (!GetRccExecutable()) {
    return false;
522
  }
523 524 525 526 527 528
  return true;
}

bool cmQtAutoGenInitializer::InitScanFiles()
{
  cmMakefile* makefile = this->Target->Target->GetMakefile();
529

530
  // Scan through target files
531
  {
532
    std::string const qrcExt = "qrc";
533
    std::vector<cmSourceFile*> srcFiles;
534
    this->Target->GetConfigCommonSourceFiles(srcFiles);
535
    for (cmSourceFile* sf : srcFiles) {
536 537 538 539
      if (sf->GetPropertyAsBool("SKIP_AUTOGEN")) {
        continue;
      }
      // sf->GetExtension() is only valid after sf->GetFullPath() ...
540 541
      std::string const& fPath = sf->GetFullPath();
      std::string const& ext = sf->GetExtension();
542
      // Register generated files that will be scanned by moc or uic
543
      if (this->Moc.Enabled || this->Uic.Enabled) {
544
        cmSystemTools::FileFormat const fileType =
545 546 547
          cmSystemTools::GetFileFormat(ext.c_str());
        if ((fileType == cmSystemTools::CXX_FILE_FORMAT) ||
            (fileType == cmSystemTools::HEADER_FILE_FORMAT)) {
548
          std::string const absPath = cmSystemTools::GetRealPath(fPath);
549 550
          if ((this->Moc.Enabled && !sf->GetPropertyAsBool("SKIP_AUTOMOC")) ||
              (this->Uic.Enabled && !sf->GetPropertyAsBool("SKIP_AUTOUIC"))) {
551 552 553 554
            // Register source
            const bool generated = sf->GetPropertyAsBool("GENERATED");
            if (fileType == cmSystemTools::HEADER_FILE_FORMAT) {
              if (generated) {
555
                this->MocUic.HeadersGenerated.push_back(absPath);
556
              } else {
557
                this->MocUic.Headers.push_back(absPath);
558 559 560
              }
            } else {
              if (generated) {
561
                this->MocUic.SourcesGenerated.push_back(absPath);
562
              } else {
563
                this->MocUic.Sources.push_back(absPath);
564
              }
565 566 567
            }
          }
        }
568 569
      }
      // Register rcc enabled files
570
      if (this->Rcc.Enabled && (ext == qrcExt) &&
571
          !sf->GetPropertyAsBool("SKIP_AUTORCC")) {
572 573
        // Register qrc file
        {
574 575 576 577 578
          Qrc qrc;
          qrc.QrcFile = cmSystemTools::GetRealPath(fPath);
          qrc.QrcName =
            cmSystemTools::GetFilenameWithoutLastExtension(qrc.QrcFile);
          qrc.Generated = sf->GetPropertyAsBool("GENERATED");
579 580
          // RCC options
          {
581
            std::string const opts = sf->GetSafeProperty("AUTORCC_OPTIONS");
582
            if (!opts.empty()) {
583
              cmSystemTools::ExpandListArgument(opts, qrc.Options);
584 585
            }
          }
586
          this->Rcc.Qrcs.push_back(std::move(qrc));
587
        }
588 589
      }
    }
590
  }
591 592 593 594 595 596
  // 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.
  this->Target->ClearSourcesCache();

597
  if (this->Moc.Enabled || this->Uic.Enabled) {
598 599 600 601 602 603 604 605 606 607 608
    // Read skip files from makefile sources
    {
      std::string pathError;
      for (cmSourceFile* sf : makefile->GetSourceFiles()) {
        // sf->GetExtension() is only valid after sf->GetFullPath() ...
        // 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;
609
        }
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
        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->Moc.Enabled &&
          (skipAll || sf->GetPropertyAsBool("SKIP_AUTOMOC"));
        const bool uicSkip = this->Uic.Enabled &&
          (skipAll || sf->GetPropertyAsBool("SKIP_AUTOUIC"));
        if (mocSkip || uicSkip) {
          std::string const absFile = cmSystemTools::GetRealPath(fPath);
          if (mocSkip) {
            this->Moc.Skip.insert(absFile);
          }
          if (uicSkip) {
            this->Uic.Skip.insert(absFile);
          }
629 630 631
        }
      }
    }
632

633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
    // Process GENERATED sources and headers
    if (!this->MocUic.SourcesGenerated.empty() ||
        !this->MocUic.HeadersGenerated.empty()) {
      // Check status of policy CMP0071
      bool policyAccept = false;
      bool policyWarn = false;
      cmPolicies::PolicyStatus const CMP0071_status =
        makefile->GetPolicyStatus(cmPolicies::CMP0071);
      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;
654
      }
655 656 657 658 659 660

      if (policyAccept) {
        // Accept GENERATED sources
        for (std::string const& absFile : this->MocUic.HeadersGenerated) {
          this->MocUic.Headers.push_back(absFile);
          this->AutogenDependFiles.insert(absFile);
661
        }
662 663 664
        for (std::string const& absFile : this->MocUic.SourcesGenerated) {
          this->MocUic.Sources.push_back(absFile);
          this->AutogenDependFiles.insert(absFile);
665
        }
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
      } else {
        if (policyWarn) {
          std::string msg;
          msg += cmPolicies::GetPolicyWarning(cmPolicies::CMP0071);
          msg += "\n";
          std::string tools;
          std::string property;
          if (this->Moc.Enabled && this->Uic.Enabled) {
            tools = "AUTOMOC and AUTOUIC";
            property = "SKIP_AUTOGEN";
          } else if (this->Moc.Enabled) {
            tools = "AUTOMOC";
            property = "SKIP_AUTOMOC";
          } else if (this->Uic.Enabled) {
            tools = "AUTOUIC";
            property = "SKIP_AUTOUIC";
          }
          msg += "For compatibility, CMake is excluding the GENERATED source "
                 "file(s):\n";
          for (const std::string& absFile : this->MocUic.HeadersGenerated) {
            msg.append("  ").append(Quoted(absFile)).append("\n");
          }
          for (const std::string& absFile : this->MocUic.SourcesGenerated) {
            msg.append("  ").append(Quoted(absFile)).append("\n");
          }
          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";
          makefile->IssueMessage(cmake::AUTHOR_WARNING, msg);
702
        }
703
      }
704
    }
705 706 707 708 709
    // Sort headers and sources
    if (this->Moc.Enabled || this->Uic.Enabled) {
      std::sort(this->MocUic.Headers.begin(), this->MocUic.Headers.end());
      std::sort(this->MocUic.Sources.begin(), this->MocUic.Sources.end());
    }
710
  }
711

712
  // Process qrc files
713
  if (!this->Rcc.Qrcs.empty()) {
714
    const bool QtV5 = (this->QtVersionMajor == "5");
715 716 717
    // Target rcc options
    std::vector<std::string> optionsTarget;
    cmSystemTools::ExpandListArgument(
718
      this->Target->GetSafeProperty("AUTORCC_OPTIONS"), optionsTarget);
719

720
    // Check if file name is unique
721
    for (Qrc& qrc : this->Rcc.Qrcs) {
722
      qrc.Unique = true;
723
      for (Qrc const& qrc2 : this->Rcc.Qrcs) {
724 725
        if ((&qrc != &qrc2) && (qrc.QrcName == qrc2.QrcName)) {
          qrc.Unique = false;
726 727
          break;
        }
728
      }
729
    }
730
    // Path checksum and file names
731
    {
732
      cmFilePathChecksum const fpathCheckSum(makefile);
733
      for (Qrc& qrc : this->Rcc.Qrcs) {
734
        qrc.PathChecksum = fpathCheckSum.getPart(qrc.QrcFile);
735
        // RCC output file name
736
        {
737 738
          std::string rccFile = this->DirBuild + "/";
          rccFile += qrc.PathChecksum;
739
          rccFile += "/qrc_";
740
          rccFile += qrc.QrcName;
741
          rccFile += ".cpp";
742
          qrc.RccFile = std::move(rccFile);
743 744
        }
        {
745
          std::string base = this->DirInfo;
746
          base += "/RCC";
747 748 749
          base += qrc.QrcName;
          if (!qrc.Unique) {
            base += qrc.PathChecksum;
750
          }
751 752 753 754

          qrc.LockFile = base;
          qrc.LockFile += ".lock";

755 756
          qrc.InfoFile = base;
          qrc.InfoFile += "Info.cmake";
757

758
          qrc.SettingsFile = base;
759
          qrc.SettingsFile += "Settings.txt";
760 761 762 763 764 765 766

          if (this->MultiConfig) {
            for (std::string const& cfg : this->ConfigsList) {
              qrc.ConfigSettingsFile[cfg] =
                AppendFilenameSuffix(qrc.SettingsFile, "_" + cfg);
            }
          }
767
        }
768 769 770
      }
    }
    // RCC options
771
    for (Qrc& qrc : this->Rcc.Qrcs) {
772 773 774
      // Target options
      std::vector<std::string> opts = optionsTarget;
      // Merge computed "-name XYZ" option
775
      {
776
        std::string name = qrc.QrcName;
777 778
        // Replace '-' with '_'. The former is not valid for symbol names.
        std::replace(name.begin(), name.end(), '-', '_');
779
        if (!qrc.Unique) {
780
          name += "_";
781
          name += qrc.PathChecksum;
782
        }
783 784 785
        std::vector<std::string> nameOpts;
        nameOpts.emplace_back("-name");
        nameOpts.emplace_back(std::move(name));
786
        RccMergeOptions(opts, nameOpts, QtV5);
787
      }
788
      // Merge file option
789
      RccMergeOptions(opts, qrc.Options, QtV5);
790
      qrc.Options = std::move(opts);
791
    }
792
    // RCC resources
793
    for (Qrc& qrc : this->Rcc.Qrcs) {
794 795 796 797 798
      if (!qrc.Generated) {
        std::string error;
        if (!RccListInputs(qrc.QrcFile, qrc.Resources, error)) {
          cmSystemTools::Error(error.c_str());
          return false;
799
        }
800
      }
801 802
    }
  }
803

804 805
  return true;
}
806

807 808 809 810 811 812 813 814 815 816 817 818 819 820
bool cmQtAutoGenInitializer::InitAutogenTarget()
{
  cmMakefile* makefile = this->Target->Target->GetMakefile();
  cmLocalGenerator* localGen = this->Target->GetLocalGenerator();
  cmGlobalGenerator* globalGen = localGen->GetGlobalGenerator();

  // Register info file as generated by CMake
  makefile->AddCMakeOutputFile(this->AutogenInfoFile);

  // Files provided by the autogen target
  std::vector<std::string> autogenProvides;
  if (this->Moc.Enabled) {
    this->AddGeneratedSource(this->Moc.MocsCompilation, GeneratorT::MOC);
    autogenProvides.push_back(this->Moc.MocsCompilation);
821 822
  }

823 824 825 826 827 828
  // Compose target comment
  std::string autogenComment;
  {
    std::string tools;
    if (this->Moc.Enabled) {
      tools += "MOC";
829
    }
830 831 832
    if (this->Uic.Enabled) {
      if (!tools.empty()) {
        tools += " and ";
833
      }
834
      tools += "UIC";
835
    }
836 837 838 839 840
    autogenComment = "Automatic ";
    autogenComment += tools;
    autogenComment += " for target ";
    autogenComment += this->Target->GetName();
  }
841

842 843 844 845 846 847 848 849 850 851 852
  // Compose command lines
  cmCustomCommandLines commandLines;
  {
    cmCustomCommandLine currentLine;
    currentLine.push_back(cmSystemTools::GetCMakeCommand());
    currentLine.push_back("-E");
    currentLine.push_back("cmake_autogen");
    currentLine.push_back(this->AutogenInfoFile);
    currentLine.push_back("$<CONFIGURATION>");
    commandLines.push_back(std::move(currentLine));
  }
853

854 855 856 857 858 859 860 861 862 863 864 865 866 867
  // 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 (!this->AutogenDependFiles.empty()) {
      usePRE_BUILD = false;
868
    }
869 870 871 872 873 874
  }
  // Create the autogen target/command
  if (usePRE_BUILD) {
    // Add additional autogen target dependencies to origin target
    for (cmTarget* depTarget : this->AutogenDependTargets) {
      this->Target->Target->AddUtility(depTarget->GetName(), makefile);
875
    }
876

877 878 879 880 881 882 883 884 885 886 887 888 889 890
    // 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(),
                       this->DirWork.c_str());
    cc.SetEscapeOldStyle(false);
    cc.SetEscapeAllowMakeVars(true);
    this->Target->Target->AddPreBuildCommand(cc);
  } else {
891

892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
    // Add link library target dependencies to the autogen target
    // dependencies
    {
      // 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]++;
908 909 910
            }
          }
        }
911
      }
912 913 914 915
      for (auto const& item : commonTargets) {
        if (item.second == this->ConfigsList.size()) {
          this->AutogenDependTargets.insert(item.first->Target);
        }
916
      }
917
    }
918

919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
    // Create autogen target
    cmTarget* autogenTarget = makefile->AddUtilityCommand(
      this->AutogenTargetName, cmMakefile::TargetOrigin::Generator, true,
      this->DirWork.c_str(), /*byproducts=*/autogenProvides,
      std::vector<std::string>(this->AutogenDependFiles.begin(),
                               this->AutogenDependFiles.end()),
      commandLines, false, autogenComment.c_str());
    // Create autogen generator target
    localGen->AddGeneratorTarget(
      new cmGeneratorTarget(autogenTarget, localGen));

    // Forward origin utilities to autogen target
    for (std::string const& depName : this->Target->Target->GetUtilities()) {
      autogenTarget->AddUtility(depName, makefile);
    }
    // Add additional autogen target dependencies to autogen target
    for (cmTarget* depTarget : this->AutogenDependTargets) {
      autogenTarget->AddUtility(depTarget->GetName(), makefile);
937 938
    }

939 940 941
    // Set FOLDER property in autogen target
    if (!this->AutogenFolder.empty()) {
      autogenTarget->SetProperty("FOLDER", this->AutogenFolder.c_str());
942 943
    }

944 945
    // Add autogen target to the origin target dependencies
    this->Target->Target->AddUtility(this->AutogenTargetName, makefile);
946 947 948 949 950
  }

  return true;
}

951
bool cmQtAutoGenInitializer::InitRccTargets()
952 953
{
  cmMakefile* makefile = this->Target->Target->GetMakefile();
954
  cmLocalGenerator* localGen = this->Target->GetLocalGenerator();
955

956 957 958 959 960
  for (Qrc const& qrc : this->Rcc.Qrcs) {
    // Register info file as generated by CMake
    makefile->AddCMakeOutputFile(qrc.InfoFile);
    // Register file at target
    this->AddGeneratedSource(qrc.RccFile, GeneratorT::RCC);
961

962 963
    std::vector<std::string> ccOutput;
    ccOutput.push_back(qrc.RccFile);
964

965 966 967 968 969 970 971 972 973 974 975
    cmCustomCommandLines commandLines;
    if (this->MultiConfig) {
      // Build for all configurations
      for (std::string const& config : this->ConfigsList) {
        cmCustomCommandLine currentLine;
        currentLine.push_back(cmSystemTools::GetCMakeCommand());
        currentLine.push_back("-E");
        currentLine.push_back("cmake_autorcc");
        currentLine.push_back(qrc.InfoFile);
        currentLine.push_back(config);
        commandLines.push_back(std::move(currentLine));
976
      }
977 978 979 980 981 982 983 984
    } else {
      cmCustomCommandLine currentLine;
      currentLine.push_back(cmSystemTools::GetCMakeCommand());
      currentLine.push_back("-E");
      currentLine.push_back("cmake_autorcc");
      currentLine.push_back(qrc.InfoFile);
      currentLine.push_back("$<CONFIG>");
      commandLines.push_back(std::move(currentLine));
985
    }
986 987 988 989 990 991 992 993 994 995 996 997 998
    std::string ccComment = "Automatic RCC for ";
    ccComment += FileProjectRelativePath(makefile, qrc.QrcFile);

    if (qrc.Generated) {
      // Create custom rcc target
      std::string ccName;
      {
        ccName = this->Target->GetName();
        ccName += "_arcc_";
        ccName += qrc.QrcName;
        if (!qrc.Unique) {
          ccName += "_";
          ccName += qrc.PathChecksum;
999
        }
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
        std::vector<std::string> ccDepends;
        // Add the .qrc and info file to the custom target dependencies
        ccDepends.push_back(qrc.QrcFile);
        ccDepends.push_back(qrc.InfoFile);

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

        // Set FOLDER property in autogen target
        if (!this->AutogenFolder.empty()) {
          autoRccTarget->SetProperty("FOLDER", this->AutogenFolder.c_str());
1016 1017
        }
      }
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
      // Add autogen target to the origin target dependencies
      this->Target->Target->AddUtility(ccName, makefile);
    } else {
      // Create custom rcc command
      {
        std::vector<std::string> ccByproducts;
        std::vector<std::string> ccDepends;
        // Add the .qrc and info file to the custom command dependencies
        ccDepends.push_back(qrc.QrcFile);
        ccDepends.push_back(qrc.InfoFile);

        // Add the resource files to the dependencies
        for (std::string const& fileName : qrc.Resources) {
          // Add resource file to the custom command dependencies
          ccDepends.push_back(fileName);
        }
        makefile->AddCustomCommandToOutput(ccOutput, ccByproducts, ccDepends,
                                           /*main_dependency*/ std::string(),
                                           commandLines, ccComment.c_str(),
                                           this->DirWork.c_str());
      }
      // Reconfigure when .qrc file changes
      makefile->AddCMakeDependFile(qrc.QrcFile);
1041 1042 1043 1044 1045 1046
    }
  }

  return true;
}

1047
bool cmQtAutoGenInitializer::SetupCustomTargets()