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

7
#include "cmCustomCommand.h"
8
#include "cmCustomCommandLines.h"
9
#include "cmFilePathChecksum.h"
10
#include "cmGeneratorExpression.h"
11
#include "cmGeneratorTarget.h"
12
#include "cmGlobalGenerator.h"
13
#include "cmLinkItem.h"
14
#include "cmListFileCache.h"
15 16
#include "cmLocalGenerator.h"
#include "cmMakefile.h"
17
#include "cmMessageType.h"
18
#include "cmOutputConverter.h"
19
#include "cmPolicies.h"
20
#include "cmSourceFile.h"
21
#include "cmSourceFileLocationKind.h"
Daniel Pfeifer's avatar
Daniel Pfeifer committed
22
#include "cmSourceGroup.h"
23
#include "cmState.h"
24
#include "cmStateTypes.h"
25
#include "cmStringAlgorithms.h"
26 27
#include "cmSystemTools.h"
#include "cmTarget.h"
28
#include "cmake.h"
29
#include "cmsys/SystemInformation.hxx"
30

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

41 42
#include "cm_memory.hxx"

43 44 45 46 47 48 49 50 51 52 53 54 55 56
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;
}

57 58 59 60 61 62
static std::string FileProjectRelativePath(cmMakefile* makefile,
                                           std::string const& fileName)
{
  std::string res;
  {
    std::string pSource = cmSystemTools::RelativePath(
63
      makefile->GetCurrentSourceDirectory(), fileName);
64
    std::string pBinary = cmSystemTools::RelativePath(
65
      makefile->GetCurrentBinaryDirectory(), fileName);
66 67 68 69 70 71 72 73 74 75 76
    if (pSource.size() < pBinary.size()) {
      res = std::move(pSource);
    } else if (pBinary.size() < fileName.size()) {
      res = std::move(pBinary);
    } else {
      res = fileName;
    }
  }
  return res;
}

77 78
/**
 * Tests if targetDepend is a STATIC_LIBRARY and if any of its
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
 * 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;
}

122 123 124 125 126 127 128 129 130 131 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
cmQtAutoGenInitializer::InfoWriter::InfoWriter(std::string const& filename)
{
  Ofs_.SetCopyIfDifferent(true);
  Ofs_.Open(filename, false, true);
}

template <class IT>
std::string cmQtAutoGenInitializer::InfoWriter::ListJoin(IT it_begin,
                                                         IT it_end)
{
  std::string res;
  for (IT it = it_begin; it != it_end; ++it) {
    if (it != it_begin) {
      res += ';';
    }
    for (const char* c = it->c_str(); *c; ++c) {
      if (*c == '"') {
        // Escape the double quote to avoid ending the argument.
        res += "\\\"";
      } else if (*c == '$') {
        // Escape the dollar to avoid expanding variables.
        res += "\\$";
      } else if (*c == '\\') {
        // Escape the backslash to avoid other escapes.
        res += "\\\\";
      } else if (*c == ';') {
        // Escape the semicolon to avoid list expansion.
        res += "\\;";
      } else {
        // Other characters will be parsed correctly.
        res += *c;
      }
    }
  }
  return res;
}

159 160
inline std::string cmQtAutoGenInitializer::InfoWriter::ConfigKey(
  cm::string_view key, std::string const& config)
161
{
162
  return cmStrCat(key, "_", config);
163 164
}

165
void cmQtAutoGenInitializer::InfoWriter::Write(cm::string_view key,
166 167 168 169 170 171
                                               std::string const& value)
{
  Ofs_ << "set(" << key << " " << cmOutputConverter::EscapeForCMake(value)
       << ")\n";
};

172
void cmQtAutoGenInitializer::InfoWriter::WriteUInt(cm::string_view key,
173 174 175 176 177 178
                                                   unsigned int value)
{
  Ofs_ << "set(" << key << " " << value << ")\n";
};

template <class C>
179
void cmQtAutoGenInitializer::InfoWriter::WriteStrings(cm::string_view key,
180 181 182 183 184 185 186
                                                      C const& container)
{
  Ofs_ << "set(" << key << " \""
       << ListJoin(container.begin(), container.end()) << "\")\n";
}

void cmQtAutoGenInitializer::InfoWriter::WriteConfig(
187
  cm::string_view key, std::map<std::string, std::string> const& map)
188 189
{
  for (auto const& item : map) {
190
    Write(ConfigKey(key, item.first), item.second);
191 192 193 194 195
  }
};

template <class C>
void cmQtAutoGenInitializer::InfoWriter::WriteConfigStrings(
196
  cm::string_view key, std::map<std::string, C> const& map)
197 198
{
  for (auto const& item : map) {
199
    WriteStrings(ConfigKey(key, item.first), item.second);
200 201 202 203
  }
}

void cmQtAutoGenInitializer::InfoWriter::WriteNestedLists(
204
  cm::string_view key, std::vector<std::vector<std::string>> const& lists)
205 206
{
  std::vector<std::string> seplist;
207 208 209
  seplist.reserve(lists.size());
  for (std::vector<std::string> const& list : lists) {
    seplist.push_back(cmStrCat("{", ListJoin(list.begin(), list.end()), "}"));
210 211 212 213
  }
  Write(key, cmJoin(seplist, cmQtAutoGen::ListSep));
};

214 215 216 217 218 219
cmQtAutoGenInitializer::cmQtAutoGenInitializer(
  cmQtAutoGenGlobalInitializer* globalInitializer, cmGeneratorTarget* target,
  IntegerVersion const& qtVersion, bool mocEnabled, bool uicEnabled,
  bool rccEnabled, bool globalAutogenTarget, bool globalAutoRccTarget)
  : GlobalInitializer(globalInitializer)
  , Target(target)
220
  , QtVersion(qtVersion)
221
{
222
  AutogenTarget.GlobalTarget = globalAutogenTarget;
223 224 225
  Moc.Enabled = mocEnabled;
  Uic.Enabled = uicEnabled;
  Rcc.Enabled = rccEnabled;
226
  Rcc.GlobalTarget = globalAutoRccTarget;
227
}
228

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

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

242
  // Verbosity
243 244 245 246 247
  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
248
      this->Verbosity = cmSystemTools::IsOn(this->Verbosity) ? "1" : "0";
249 250 251
    }
  }

252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
  // Targets FOLDER
  {
    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 = this->Target->GetProperty("FOLDER");
    }
    if (folder != nullptr) {
      this->TargetsFolder = folder;
    }
267 268
  }

269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
  // Check status of policy CMP0071
  {
    cmPolicies::PolicyStatus const CMP0071_status =
      makefile->GetPolicyStatus(cmPolicies::CMP0071);
    switch (CMP0071_status) {
      case cmPolicies::WARN:
        this->CMP0071Warn = 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
        this->CMP0071Accept = true;
        break;
    }
  }

289
  // Common directories
290 291 292
  {
    // Collapsed current binary directory
    std::string const cbd = cmSystemTools::CollapseFullPath(
293
      std::string(), makefile->GetCurrentBinaryDirectory());
294

295 296
    // Info directory
    this->Dir.Info = cbd;
297
    this->Dir.Info += "/CMakeFiles";
298 299 300 301 302 303 304 305 306 307 308 309 310
    this->Dir.Info += '/';
    this->Dir.Info += this->Target->GetName();
    this->Dir.Info += "_autogen";
    this->Dir.Info += ".dir";
    cmSystemTools::ConvertToUnixSlashes(this->Dir.Info);

    // Build directory
    this->Dir.Build = this->Target->GetSafeProperty("AUTOGEN_BUILD_DIR");
    if (this->Dir.Build.empty()) {
      this->Dir.Build = cbd;
      this->Dir.Build += '/';
      this->Dir.Build += this->Target->GetName();
      this->Dir.Build += "_autogen";
311
    }
312 313
    cmSystemTools::ConvertToUnixSlashes(this->Dir.Build);
    // Cleanup build directory
314
    this->AddCleanFile(this->Dir.Build);
315 316

    // Working directory
317 318
    this->Dir.Work = cbd;
    cmSystemTools::ConvertToUnixSlashes(this->Dir.Work);
319 320

    // Include directory
321 322
    this->Dir.Include = this->Dir.Build;
    this->Dir.Include += "/include";
323
    if (this->MultiConfig) {
324
      this->Dir.Include += "_$<CONFIG>";
325
    }
326
    // Per config include directories
327 328
    if (this->MultiConfig) {
      for (std::string const& cfg : this->ConfigsList) {
329 330
        std::string& dir = this->Dir.ConfigInclude[cfg];
        dir = this->Dir.Build;
331 332 333 334
        dir += "/include_";
        dir += cfg;
      }
    }
335
  }
336

337
  // Moc, Uic and _autogen target settings
338
  if (this->MocOrUicEnabled()) {
339 340 341 342
    // Init moc specific settings
    if (this->Moc.Enabled && !InitMoc()) {
      return false;
    }
343

344
    // Init uic specific settings
345 346
    if (this->Uic.Enabled && !InitUic()) {
      return false;
347 348
    }

349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
    // Autogen target name
    this->AutogenTarget.Name = this->Target->GetName();
    this->AutogenTarget.Name += "_autogen";

    // Autogen target parallel processing
    this->AutogenTarget.Parallel =
      this->Target->GetSafeProperty("AUTOGEN_PARALLEL");
    if (this->AutogenTarget.Parallel.empty() ||
        (this->AutogenTarget.Parallel == "AUTO")) {
      // Autodetect number of CPUs
      this->AutogenTarget.Parallel = std::to_string(GetParallelCPUCount());
    }

    // Autogen target info and settings files
    {
      this->AutogenTarget.InfoFile = this->Dir.Info;
      this->AutogenTarget.InfoFile += "/AutogenInfo.cmake";

      this->AutogenTarget.SettingsFile = this->Dir.Info;
      this->AutogenTarget.SettingsFile += "/AutogenOldSettings.txt";

      if (this->MultiConfig) {
        for (std::string const& cfg : this->ConfigsList) {
          std::string& filename = this->AutogenTarget.ConfigSettingsFile[cfg];
          filename =
            AppendFilenameSuffix(this->AutogenTarget.SettingsFile, "_" + cfg);
375
          this->AddCleanFile(filename);
376 377
        }
      } else {
378
        this->AddCleanFile(this->AutogenTarget.SettingsFile);
379
      }
380 381 382

      this->AutogenTarget.ParseCacheFile = this->Dir.Info;
      this->AutogenTarget.ParseCacheFile += "/ParseCache.txt";
383
      this->AddCleanFile(this->AutogenTarget.ParseCacheFile);
384 385
    }

386 387
    // Autogen target: Compute user defined dependencies
    {
388 389 390
      this->AutogenTarget.DependOrigin =
        this->Target->GetPropertyAsBool("AUTOGEN_ORIGIN_DEPENDS");

391 392 393 394 395 396 397 398 399
      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) {
400
            this->AutogenTarget.DependTargets.insert(depTarget);
401
          } else {
402
            this->AutogenTarget.DependFiles.insert(depName);
403 404 405 406
          }
        }
      }
    }
407 408 409 410 411 412 413 414 415 416 417 418 419

    // CMAKE_AUTOMOC_RELAXED_MODE deprecation warning
    if (this->Moc.Enabled) {
      if (cmSystemTools::IsOn(
            makefile->GetDefinition("CMAKE_AUTOMOC_RELAXED_MODE"))) {
        std::string msg = "AUTOMOC: CMAKE_AUTOMOC_RELAXED_MODE is "
                          "deprecated an will be removed in the future.  ";
        msg += "Consider disabling it and converting the target ";
        msg += this->Target->GetName();
        msg += " to regular mode.";
        makefile->IssueMessage(MessageType::AUTHOR_WARNING, msg);
      }
    }
420
  }
421

422 423 424 425 426 427
  // Init rcc specific settings
  if (this->Rcc.Enabled && !InitRcc()) {
    return false;
  }

  // Add autogen include directory to the origin target INCLUDE_DIRECTORIES
428
  if (this->MocOrUicEnabled() || (this->Rcc.Enabled && this->MultiConfig)) {
429
    this->Target->AddIncludeDirectory(this->Dir.Include, true);
430 431 432 433 434 435 436 437
  }

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

  // Create autogen target
438
  if (this->MocOrUicEnabled() && !this->InitAutogenTarget()) {
439 440
    return false;
  }
441

442 443 444 445 446 447 448 449 450 451 452 453 454 455
  // 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
456
  this->Moc.MocsCompilation = this->Dir.Build;
457 458 459 460
  this->Moc.MocsCompilation += "/mocs_compilation.cpp";

  // Moc predefs command
  if (this->Target->GetPropertyAsBool("AUTOMOC_COMPILER_PREDEFINES") &&
461
      (this->QtVersion >= IntegerVersion(5, 8))) {
462 463 464 465 466
    this->Moc.PredefsCmd =
      makefile->GetSafeDefinition("CMAKE_CXX_COMPILER_PREDEFINES_COMMAND");
  }

  // Moc includes
467
  {
468
    bool const appendImplicit = (this->QtVersion.Major >= 5);
469
    auto GetIncludeDirs =
470 471
      [this, localGen,
       appendImplicit](std::string const& cfg) -> std::vector<std::string> {
472 473 474 475
      // 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;
476 477
      localGen->GetIncludeDirectoriesImplicit(dirs, this->Target, "CXX", cfg,
                                              false, appendImplicit);
478
      return dirs;
479 480 481 482 483
    };

    // Default configuration include directories
    this->Moc.Includes = GetIncludeDirs(this->ConfigDefault);
    // Other configuration settings
484
    if (this->MultiConfig) {
485
      for (std::string const& cfg : this->ConfigsList) {
486
        std::vector<std::string> dirs = GetIncludeDirs(cfg);
487 488 489
        if (dirs != this->Moc.Includes) {
          this->Moc.ConfigIncludes[cfg] = std::move(dirs);
        }
490
      }
491
    }
492 493
  }

494 495 496
  // Moc compile definitions
  {
    auto GetCompileDefinitions =
497
      [this, localGen](std::string const& cfg) -> std::set<std::string> {
498
      std::set<std::string> defines;
499
      localGen->GetTargetDefines(this->Target, cfg, "CXX", defines);
500 501 502 503 504 505
#ifdef _WIN32
      if (this->Moc.PredefsCmd.empty()) {
        // Add WIN32 definition if we don't have a moc_predefs.h
        defines.insert("WIN32");
      }
#endif
506
      return defines;
507 508 509 510 511 512 513
    };

    // Default configuration defines
    this->Moc.Defines = GetCompileDefinitions(this->ConfigDefault);
    // Other configuration defines
    if (this->MultiConfig) {
      for (std::string const& cfg : this->ConfigsList) {
514
        std::set<std::string> defines = GetCompileDefinitions(cfg);
515 516 517 518 519
        if (defines != this->Moc.Defines) {
          this->Moc.ConfigDefines[cfg] = std::move(defines);
        }
      }
    }
520
  }
521 522

  // Moc executable
523
  {
524
    if (!this->GetQtExecutable(this->Moc, "moc", false)) {
525 526 527 528 529 530 531 532 533 534
      return false;
    }
    // Let the _autogen target depend on the moc executable
    if (this->Moc.ExecutableTarget != nullptr) {
      this->AutogenTarget.DependTargets.insert(
        this->Moc.ExecutableTarget->Target);
    }
  }

  return true;
535 536 537 538 539 540 541 542 543 544 545 546
}

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);
547
      std::string const& srcDir = makefile->GetCurrentSourceDirectory();
548 549 550 551
      for (std::string& path : this->Uic.SearchPaths) {
        path = cmSystemTools::CollapseFullPath(path, srcDir);
      }
    }
552
  }
553 554
  // Uic target options
  {
555 556
    auto UicGetOpts =
      [this](std::string const& cfg) -> std::vector<std::string> {
557 558
      std::vector<std::string> opts;
      this->Target->GetAutoUicOptions(opts, cfg);
559
      return opts;
560
    };
561

562 563 564 565 566 567
    // Default settings
    this->Uic.Options = UicGetOpts(this->ConfigDefault);

    // Configuration specific settings
    if (this->MultiConfig) {
      for (std::string const& cfg : this->ConfigsList) {
568
        std::vector<std::string> options = UicGetOpts(cfg);
569 570 571 572 573 574
        if (options != this->Uic.Options) {
          this->Uic.ConfigOptions[cfg] = std::move(options);
        }
      }
    }
  }
575

576
  // Uic executable
577
  {
578
    if (!this->GetQtExecutable(this->Uic, "uic", true)) {
579 580 581 582 583 584 585 586 587 588
      return false;
    }
    // Let the _autogen target depend on the uic executable
    if (this->Uic.ExecutableTarget != nullptr) {
      this->AutogenTarget.DependTargets.insert(
        this->Uic.ExecutableTarget->Target);
    }
  }

  return true;
589 590 591 592
}

bool cmQtAutoGenInitializer::InitRcc()
{
593 594
  // Rcc executable
  {
595
    if (!this->GetQtExecutable(this->Rcc, "rcc", false)) {
596 597
      return false;
    }
598 599 600 601 602 603 604 605 606 607
    // Evaluate test output on demand
    CompilerFeatures& features = *this->Rcc.ExecutableFeatures;
    if (!features.Evaluated) {
      // Look for list options
      if (this->QtVersion.Major == 5 || this->QtVersion.Major == 6) {
        if (features.HelpOutput.find("--list") != std::string::npos) {
          features.ListOptions.emplace_back("--list");
        } else if (features.HelpOutput.find("-list") != std::string::npos) {
          features.ListOptions.emplace_back("-list");
        }
608
      }
609 610
      // Evaluation finished
      features.Evaluated = true;
611 612 613 614
    }
  }

  return true;
615 616 617 618 619
}

bool cmQtAutoGenInitializer::InitScanFiles()
{
  cmMakefile* makefile = this->Target->Target->GetMakefile();
620
  cmake const* cm = makefile->GetCMakeInstance();
621
  auto const& kw = this->GlobalInitializer->kw();
622

623 624
  auto makeMUFile = [this, &kw](cmSourceFile* sf, std::string const& fullPath,
                                bool muIt) -> MUFileHandle {
625 626 627 628
    MUFileHandle muf = cm::make_unique<MUFile>();
    muf->RealPath = cmSystemTools::GetRealPath(fullPath);
    muf->SF = sf;
    muf->Generated = sf->GetIsGenerated();
629
    bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
630
    muf->SkipMoc = this->Moc.Enabled &&
631
      (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOMOC));
632
    muf->SkipUic = this->Uic.Enabled &&
633
      (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
    if (muIt) {
      muf->MocIt = this->Moc.Enabled && !muf->SkipMoc;
      muf->UicIt = this->Uic.Enabled && !muf->SkipUic;
    }
    return muf;
  };

  auto addMUFile = [&](MUFileHandle&& muf, bool isHeader) {
    if ((muf->MocIt || muf->UicIt) && muf->Generated) {
      this->AutogenTarget.FilesGenerated.emplace_back(muf.get());
    }
    if (isHeader) {
      this->AutogenTarget.Headers.emplace(muf->SF, std::move(muf));
    } else {
      this->AutogenTarget.Sources.emplace(muf->SF, std::move(muf));
    }
  };
651

652
  // Scan through target files
653
  {
654
    // Scan through target files
655
    std::vector<cmSourceFile*> srcFiles;
656
    this->Target->GetConfigCommonSourceFiles(srcFiles);
657
    for (cmSourceFile* sf : srcFiles) {
658 659 660 661 662 663
      // 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 pathError;
      std::string const& fullPath = sf->GetFullPath(&pathError);
      if (!pathError.empty() || fullPath.empty()) {
664 665
        continue;
      }
666 667
      std::string const& extLower =
        cmSystemTools::LowerCase(sf->GetExtension());
668

669 670
      // Register files that will be scanned by moc or uic
      if (this->MocOrUicEnabled()) {
671 672 673 674
        if (cm->IsHeaderExtension(extLower)) {
          addMUFile(makeMUFile(sf, fullPath, true), true);
        } else if (cm->IsSourceExtension(extLower)) {
          addMUFile(makeMUFile(sf, fullPath, true), false);
675
        }
676
      }
677

678
      // Register rcc enabled files
679
      if (this->Rcc.Enabled) {
680
        if ((extLower == kw.qrc) && !sf->GetPropertyAsBool(kw.SKIP_AUTOGEN) &&
681
            !sf->GetPropertyAsBool(kw.SKIP_AUTORCC)) {
682
          // Register qrc file
683
          Qrc qrc;
684
          qrc.QrcFile = cmSystemTools::GetRealPath(fullPath);
685 686
          qrc.QrcName =
            cmSystemTools::GetFilenameWithoutLastExtension(qrc.QrcFile);
687
          qrc.Generated = sf->GetIsGenerated();
688 689
          // RCC options
          {
690
            std::string const opts = sf->GetSafeProperty(kw.AUTORCC_OPTIONS);
691
            if (!opts.empty()) {
692
              cmSystemTools::ExpandListArgument(opts, qrc.Options);
693 694
            }
          }
695
          this->Rcc.Qrcs.push_back(std::move(qrc));
696
        }
697 698
      }
    }
699
  }
700 701 702 703 704 705
  // 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();

706 707 708 709 710 711
  // For source files find additional headers and private headers
  if (this->MocOrUicEnabled()) {
    std::vector<MUFileHandle> extraHeaders;
    extraHeaders.reserve(this->AutogenTarget.Sources.size() * 2);
    // Header search suffixes and extensions
    std::array<std::string, 2> const suffixes{ { "", "_p" } };
712
    auto const& exts = cm->GetHeaderExtensions();
713 714 715 716 717
    // Scan through sources
    for (auto const& pair : this->AutogenTarget.Sources) {
      MUFile const& muf = *pair.second;
      if (muf.MocIt || muf.UicIt) {
        // Search for the default header file and a private header
718 719 720
        std::string const& srcPath = muf.SF->GetFullPath();
        std::string basePath = cmQtAutoGen::SubDirPrefix(srcPath);
        basePath += cmSystemTools::GetFilenameWithoutLastExtension(srcPath);
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
        for (auto const& suffix : suffixes) {
          std::string const suffixedPath = basePath + suffix;
          for (auto const& ext : exts) {
            std::string fullPath = suffixedPath;
            fullPath += '.';
            fullPath += ext;

            auto constexpr locationKind = cmSourceFileLocationKind::Known;
            cmSourceFile* sf = makefile->GetSource(fullPath, locationKind);
            if (sf != nullptr) {
              // Check if we know about this header already
              if (this->AutogenTarget.Headers.find(sf) !=
                  this->AutogenTarget.Headers.end()) {
                continue;
              }
              // We only accept not-GENERATED files that do exist.
              if (!sf->GetIsGenerated() &&
                  !cmSystemTools::FileExists(fullPath)) {
                continue;
              }
            } else if (cmSystemTools::FileExists(fullPath)) {
              // Create a new source file for the existing file
              sf = makefile->CreateSource(fullPath, false, locationKind);
            }

            if (sf != nullptr) {
              auto eMuf = makeMUFile(sf, fullPath, true);
              // Ony process moc/uic when the parent is processed as well
              if (!muf.MocIt) {
                eMuf->MocIt = false;
              }
              if (!muf.UicIt) {
                eMuf->UicIt = false;
              }
              extraHeaders.emplace_back(std::move(eMuf));
            }
          }
        }
      }
    }
    // Move generated files to main headers list
    for (auto& eMuf : extraHeaders) {
      addMUFile(std::move(eMuf), true);
    }
  }

767 768 769 770
  // Scan through all source files in the makefile to extract moc and uic
  // parameters.  Historically we support non target source file parameters.
  // The reason is that their file names might be discovered from source files
  // at generation time.
771
  if (this->MocOrUicEnabled()) {
772 773 774 775
    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).
776
      std::string pathError;
777 778 779 780
      std::string const& fullPath = sf->GetFullPath(&pathError);
      if (!pathError.empty() || fullPath.empty()) {
        continue;
      }
781 782
      std::string const& extLower =
        cmSystemTools::LowerCase(sf->GetExtension());
783

784
      if (cm->IsHeaderExtension(extLower)) {
785 786 787 788 789 790
        if (this->AutogenTarget.Headers.find(sf) ==
            this->AutogenTarget.Headers.end()) {
          auto muf = makeMUFile(sf, fullPath, false);
          if (muf->SkipMoc || muf->SkipUic) {
            this->AutogenTarget.Headers.emplace(sf, std::move(muf));
          }
791
        }
792
      } else if (cm->IsSourceExtension(extLower)) {
793 794 795 796 797 798
        if (this->AutogenTarget.Sources.find(sf) ==
            this->AutogenTarget.Sources.end()) {
          auto muf = makeMUFile(sf, fullPath, false);
          if (muf->SkipMoc || muf->SkipUic) {
            this->AutogenTarget.Sources.emplace(sf, std::move(muf));
          }
799
        }
800
      } else if (this->Uic.Enabled && (extLower == kw.ui)) {
801 802
        // .ui file
        std::string realPath = cmSystemTools::GetRealPath(fullPath);
803
        bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
804
        bool const skipUic =
805
          (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
806 807
        if (!skipUic) {
          // Check if the .ui file has uic options
808
          std::string const uicOpts = sf->GetSafeProperty(kw.AUTOUIC_OPTIONS);
809
          if (!uicOpts.empty()) {
810
            this->Uic.FileFiles.push_back(std::move(realPath));
811 812 813
            std::vector<std::string> optsVec;
            cmSystemTools::ExpandListArgument(uicOpts, optsVec);
            this->Uic.FileOptions.push_back(std::move(optsVec));
814
          }
815 816 817
        } else {
          // Register skipped .ui file
          this->Uic.SkipUi.insert(std::move(realPath));
818 819 820
        }
      }
    }
821
  }
822

823
  // Process GENERATED sources and headers
824 825 826 827 828
  if (this->MocOrUicEnabled() && !this->AutogenTarget.FilesGenerated.empty()) {
    if (this->CMP0071Accept) {
      // Let the autogen target depend on the GENERATED files
      for (MUFile* muf : this->AutogenTarget.FilesGenerated) {
        this->AutogenTarget.DependFiles.insert(muf->RealPath);
829
      }
830 831 832 833 834 835
    } else if (this->CMP0071Warn) {
      std::string msg;
      msg += cmPolicies::GetPolicyWarning(cmPolicies::CMP0071);
      msg += '\n';
      std::string property;
      if (this->Moc.Enabled && this->Uic.Enabled) {
836
        property = kw.SKIP_AUTOGEN;
837
      } else if (this->Moc.Enabled) {
838
        property = kw.SKIP_AUTOMOC;
839
      } else if (this->Uic.Enabled) {
840
        property = kw.SKIP_AUTOUIC;
841
      }
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
      msg += "For compatibility, CMake is excluding the GENERATED source "
             "file(s):\n";
      for (MUFile* muf : this->AutogenTarget.FilesGenerated) {
        msg += "  ";
        msg += Quoted(muf->RealPath);
        msg += '\n';
      }
      msg += "from processing by ";
      msg += cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false);
      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(MessageType::AUTHOR_WARNING, msg);
859
    }
860 861
  }

862
  // Process qrc files
863
  if (!this->Rcc.Qrcs.empty()) {
Tobias Hunger's avatar
Tobias Hunger committed
864
    const bool modernQt = (this->QtVersion.Major >= 5);
865 866 867
    // Target rcc options
    std::vector<std::string> optionsTarget;
    cmSystemTools::ExpandListArgument(
868
      this->Target->GetSafeProperty(kw.AUTORCC_OPTIONS), optionsTarget);
869

870
    // Check if file name is unique
871
    for (Qrc& qrc : this->Rcc.Qrcs) {
872
      qrc.Unique = true;
873
      for (Qrc const& qrc2 : this->Rcc.Qrcs) {
874 875
        if ((&qrc != &qrc2) && (qrc.QrcName == qrc2.QrcName)) {
          qrc.Unique = false;
876 877
          break;
        }
878
      }
879
    }
880
    // Path checksum and file names
881
    {
882
      cmFilePathChecksum const fpathCheckSum(makefile);
883
      for (Qrc& qrc : this->Rcc.Qrcs) {
884
        qrc.PathChecksum = fpathCheckSum.getPart(qrc.QrcFile);
885
        // RCC output file name
886
        {
887
          std::string rccFile = this->Dir.Build + "/";
888
          rccFile += qrc.PathChecksum;
889
          rccFile += "/qrc_";
890
          rccFile += qrc.QrcName;
891
          rccFile += ".cpp";
892
          qrc.RccFile = std::move(rccFile);
893 894
        }
        {
895
          std::string base = this->Dir.Info;
896
          base += "/RCC";
897 898 899
          base += qrc.QrcName;
          if (!qrc.Unique) {
            base += qrc.PathChecksum;
900
          }
901 902 903 904

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

905 906
          qrc.InfoFile = base;
          qrc.InfoFile += "Info.cmake";
907

908
          qrc.SettingsFile = base;
909
          qrc.SettingsFile += "Settings.txt";
910 911 912 913 914 915 916

          if (this->MultiConfig) {
            for (std::string const& cfg : this->ConfigsList) {
              qrc.ConfigSettingsFile[cfg] =
                AppendFilenameSuffix(qrc.SettingsFile, "_" + cfg);
            }
          }
917
        }
918 919 920
      }
    }
    // RCC options
921
    for (Qrc& qrc : this->Rcc.Qrcs) {
922 923 924
      // Target options
      std::vector<std::string> opts = optionsTarget;
      // Merge computed "-name XYZ" option
925
      {
926
        std::string name = qrc.QrcName;
927 928
        // Replace '-' with '_'. The former is not valid for symbol names.
        std::replace(name.begin(), name.end(), '-', '_');
929
        if (!qrc.Unique) {
930
          name += "_";
931
          name += qrc.PathChecksum;
932
        }
933 934 93