40f3ab58d1bb8866a77296476a8d5d3e87ada3df
[platform/upstream/cmake.git] / Source / cmQtAutoGenInitializer.cxx
1 /* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
2    file Copyright.txt or https://cmake.org/licensing for details.  */
3 #include "cmQtAutoGenInitializer.h"
4
5 #include <cstddef>
6 #include <deque>
7 #include <initializer_list>
8 #include <map>
9 #include <set>
10 #include <sstream> // for basic_ios, istringstream
11 #include <string>
12 #include <unordered_set>
13 #include <utility>
14 #include <vector>
15
16 #include <cm/algorithm>
17 #include <cm/iterator>
18 #include <cm/memory>
19 #include <cmext/algorithm>
20 #include <cmext/string_view>
21
22 #include <cm3p/json/value.h>
23 #include <cm3p/json/writer.h>
24
25 #include "cmsys/SystemInformation.hxx"
26
27 #include "cmAlgorithms.h"
28 #include "cmCustomCommand.h"
29 #include "cmCustomCommandLines.h"
30 #include "cmGeneratedFileStream.h"
31 #include "cmGeneratorExpression.h"
32 #include "cmGeneratorTarget.h"
33 #include "cmGlobalGenerator.h"
34 #include "cmLinkItem.h"
35 #include "cmListFileCache.h"
36 #include "cmLocalGenerator.h"
37 #include "cmMakefile.h"
38 #include "cmMessageType.h"
39 #include "cmPolicies.h"
40 #include "cmQtAutoGen.h"
41 #include "cmQtAutoGenGlobalInitializer.h"
42 #include "cmSourceFile.h"
43 #include "cmSourceFileLocationKind.h"
44 #include "cmSourceGroup.h"
45 #include "cmState.h"
46 #include "cmStateTypes.h"
47 #include "cmStringAlgorithms.h"
48 #include "cmSystemTools.h"
49 #include "cmTarget.h"
50 #include "cmValue.h"
51 #include "cmake.h"
52
53 namespace {
54
55 unsigned int GetParallelCPUCount()
56 {
57   static unsigned int count = 0;
58   // Detect only on the first call
59   if (count == 0) {
60     cmsys::SystemInformation info;
61     info.RunCPUCheck();
62     count =
63       cm::clamp(info.GetNumberOfPhysicalCPU(), 1u, cmQtAutoGen::ParallelMax);
64   }
65   return count;
66 }
67
68 std::string FileProjectRelativePath(cmMakefile* makefile,
69                                     std::string const& fileName)
70 {
71   std::string res;
72   {
73     std::string pSource = cmSystemTools::RelativePath(
74       makefile->GetCurrentSourceDirectory(), fileName);
75     std::string pBinary = cmSystemTools::RelativePath(
76       makefile->GetCurrentBinaryDirectory(), fileName);
77     if (pSource.size() < pBinary.size()) {
78       res = std::move(pSource);
79     } else if (pBinary.size() < fileName.size()) {
80       res = std::move(pBinary);
81     } else {
82       res = fileName;
83     }
84   }
85   return res;
86 }
87
88 /**
89  * Tests if targetDepend is a STATIC_LIBRARY and if any of its
90  * recursive STATIC_LIBRARY dependencies depends on targetOrigin
91  * (STATIC_LIBRARY cycle).
92  */
93 bool StaticLibraryCycle(cmGeneratorTarget const* targetOrigin,
94                         cmGeneratorTarget const* targetDepend,
95                         std::string const& config)
96 {
97   bool cycle = false;
98   if ((targetOrigin->GetType() == cmStateEnums::STATIC_LIBRARY) &&
99       (targetDepend->GetType() == cmStateEnums::STATIC_LIBRARY)) {
100     std::set<cmGeneratorTarget const*> knownLibs;
101     std::deque<cmGeneratorTarget const*> testLibs;
102
103     // Insert initial static_library dependency
104     knownLibs.insert(targetDepend);
105     testLibs.push_back(targetDepend);
106
107     while (!testLibs.empty()) {
108       cmGeneratorTarget const* testTarget = testLibs.front();
109       testLibs.pop_front();
110       // Check if the test target is the origin target (cycle)
111       if (testTarget == targetOrigin) {
112         cycle = true;
113         break;
114       }
115       // Collect all static_library dependencies from the test target
116       cmLinkImplementationLibraries const* libs =
117         testTarget->GetLinkImplementationLibraries(
118           config, cmGeneratorTarget::LinkInterfaceFor::Link);
119       if (libs) {
120         for (cmLinkItem const& item : libs->Libraries) {
121           cmGeneratorTarget const* depTarget = item.Target;
122           if (depTarget &&
123               (depTarget->GetType() == cmStateEnums::STATIC_LIBRARY) &&
124               knownLibs.insert(depTarget).second) {
125             testLibs.push_back(depTarget);
126           }
127         }
128       }
129     }
130   }
131   return cycle;
132 }
133
134 /** Sanitizes file search paths.  */
135 class SearchPathSanitizer
136 {
137 public:
138   SearchPathSanitizer(cmMakefile* makefile)
139     : SourcePath_(makefile->GetCurrentSourceDirectory())
140   {
141   }
142   std::vector<std::string> operator()(
143     std::vector<std::string> const& paths) const;
144
145 private:
146   std::string SourcePath_;
147 };
148
149 std::vector<std::string> SearchPathSanitizer::operator()(
150   std::vector<std::string> const& paths) const
151 {
152   std::vector<std::string> res;
153   res.reserve(paths.size());
154   for (std::string const& srcPath : paths) {
155     // Collapse relative paths
156     std::string path =
157       cmSystemTools::CollapseFullPath(srcPath, this->SourcePath_);
158     // Remove suffix slashes
159     while (cmHasSuffix(path, '/')) {
160       path.pop_back();
161     }
162     // Accept only non empty paths
163     if (!path.empty()) {
164       res.emplace_back(std::move(path));
165     }
166   }
167   return res;
168 }
169
170 /** @brief Writes a CMake info file.  */
171 class InfoWriter
172 {
173 public:
174   // -- Single value
175   void Set(std::string const& key, std::string const& value)
176   {
177     this->Value_[key] = value;
178   }
179   void SetConfig(std::string const& key,
180                  cmQtAutoGenInitializer::ConfigString const& cfgStr);
181   void SetBool(std::string const& key, bool value)
182   {
183     this->Value_[key] = value;
184   }
185   void SetUInt(std::string const& key, unsigned int value)
186   {
187     this->Value_[key] = value;
188   }
189
190   // -- Array utility
191   template <typename CONT>
192   static bool MakeArray(Json::Value& jval, CONT const& container);
193
194   template <typename CONT>
195   static void MakeStringArray(Json::Value& jval, CONT const& container);
196
197   // -- Array value
198   template <typename CONT>
199   void SetArray(std::string const& key, CONT const& container);
200   template <typename CONT>
201   void SetConfigArray(
202     std::string const& key,
203     cmQtAutoGenInitializer::ConfigStrings<CONT> const& cfgStr);
204
205   // -- Array of arrays
206   template <typename CONT, typename FUNC>
207   void SetArrayArray(std::string const& key, CONT const& container, FUNC func);
208
209   // -- Save to json file
210   bool Save(std::string const& filename);
211
212 private:
213   Json::Value Value_;
214 };
215
216 void InfoWriter::SetConfig(std::string const& key,
217                            cmQtAutoGenInitializer::ConfigString const& cfgStr)
218 {
219   this->Set(key, cfgStr.Default);
220   for (auto const& item : cfgStr.Config) {
221     this->Set(cmStrCat(key, '_', item.first), item.second);
222   }
223 }
224
225 template <typename CONT>
226 bool InfoWriter::MakeArray(Json::Value& jval, CONT const& container)
227 {
228   jval = Json::arrayValue;
229   std::size_t const listSize = cm::size(container);
230   if (listSize == 0) {
231     return false;
232   }
233   jval.resize(static_cast<unsigned int>(listSize));
234   return true;
235 }
236
237 template <typename CONT>
238 void InfoWriter::MakeStringArray(Json::Value& jval, CONT const& container)
239 {
240   if (MakeArray(jval, container)) {
241     Json::ArrayIndex ii = 0;
242     for (std::string const& item : container) {
243       jval[ii++] = item;
244     }
245   }
246 }
247
248 template <typename CONT>
249 void InfoWriter::SetArray(std::string const& key, CONT const& container)
250 {
251   MakeStringArray(this->Value_[key], container);
252 }
253
254 template <typename CONT, typename FUNC>
255 void InfoWriter::SetArrayArray(std::string const& key, CONT const& container,
256                                FUNC func)
257 {
258   Json::Value& jval = this->Value_[key];
259   if (MakeArray(jval, container)) {
260     Json::ArrayIndex ii = 0;
261     for (auto const& citem : container) {
262       Json::Value& aval = jval[ii++];
263       aval = Json::arrayValue;
264       func(aval, citem);
265     }
266   }
267 }
268
269 template <typename CONT>
270 void InfoWriter::SetConfigArray(
271   std::string const& key,
272   cmQtAutoGenInitializer::ConfigStrings<CONT> const& cfgStr)
273 {
274   this->SetArray(key, cfgStr.Default);
275   for (auto const& item : cfgStr.Config) {
276     this->SetArray(cmStrCat(key, '_', item.first), item.second);
277   }
278 }
279
280 bool InfoWriter::Save(std::string const& filename)
281 {
282   cmGeneratedFileStream fileStream;
283   fileStream.SetCopyIfDifferent(true);
284   fileStream.Open(filename, false, true);
285   if (!fileStream) {
286     return false;
287   }
288
289   Json::StyledStreamWriter jsonWriter;
290   try {
291     jsonWriter.write(fileStream, this->Value_);
292   } catch (...) {
293     return false;
294   }
295
296   return fileStream.Close();
297 }
298
299 void AddAutogenExecutableToDependencies(
300   cmQtAutoGenInitializer::GenVarsT const& genVars,
301   std::vector<std::string>& dependencies)
302 {
303   if (genVars.ExecutableTarget != nullptr) {
304     dependencies.push_back(genVars.ExecutableTarget->Target->GetName());
305   } else if (!genVars.Executable.empty()) {
306     dependencies.push_back(genVars.Executable);
307   }
308 }
309
310 } // End of unnamed namespace
311
312 cmQtAutoGenInitializer::cmQtAutoGenInitializer(
313   cmQtAutoGenGlobalInitializer* globalInitializer,
314   cmGeneratorTarget* genTarget, IntegerVersion const& qtVersion,
315   bool mocEnabled, bool uicEnabled, bool rccEnabled, bool globalAutogenTarget,
316   bool globalAutoRccTarget)
317   : GlobalInitializer(globalInitializer)
318   , GenTarget(genTarget)
319   , GlobalGen(genTarget->GetGlobalGenerator())
320   , LocalGen(genTarget->GetLocalGenerator())
321   , Makefile(genTarget->Makefile)
322   , PathCheckSum(genTarget->Makefile)
323   , QtVersion(qtVersion)
324 {
325   this->AutogenTarget.GlobalTarget = globalAutogenTarget;
326   this->Moc.Enabled = mocEnabled;
327   this->Uic.Enabled = uicEnabled;
328   this->Rcc.Enabled = rccEnabled;
329   this->Rcc.GlobalTarget = globalAutoRccTarget;
330 }
331
332 bool cmQtAutoGenInitializer::InitCustomTargets()
333 {
334   // Configurations
335   this->MultiConfig = this->GlobalGen->IsMultiConfig();
336   this->ConfigDefault = this->Makefile->GetDefaultConfiguration();
337   this->ConfigsList =
338     this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
339
340   // Verbosity
341   {
342     std::string def =
343       this->Makefile->GetSafeDefinition("CMAKE_AUTOGEN_VERBOSE");
344     if (!def.empty()) {
345       unsigned long iVerb = 0;
346       if (cmStrToULong(def, &iVerb)) {
347         // Numeric verbosity
348         this->Verbosity = static_cast<unsigned int>(iVerb);
349       } else {
350         // Non numeric verbosity
351         if (cmIsOn(def)) {
352           this->Verbosity = 1;
353         }
354       }
355     }
356   }
357
358   // Targets FOLDER
359   {
360     cmValue folder =
361       this->Makefile->GetState()->GetGlobalProperty("AUTOMOC_TARGETS_FOLDER");
362     if (!folder) {
363       folder = this->Makefile->GetState()->GetGlobalProperty(
364         "AUTOGEN_TARGETS_FOLDER");
365     }
366     // Inherit FOLDER property from target (#13688)
367     if (!folder) {
368       folder = this->GenTarget->GetProperty("FOLDER");
369     }
370     if (folder) {
371       this->TargetsFolder = *folder;
372     }
373   }
374
375   // Check status of policy CMP0071 regarding handling of GENERATED files
376   switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0071)) {
377     case cmPolicies::WARN:
378       // Ignore GENERATED files but warn
379       this->CMP0071Warn = true;
380       CM_FALLTHROUGH;
381     case cmPolicies::OLD:
382       // Ignore GENERATED files
383       break;
384     case cmPolicies::REQUIRED_IF_USED:
385     case cmPolicies::REQUIRED_ALWAYS:
386     case cmPolicies::NEW:
387       // Process GENERATED files
388       this->CMP0071Accept = true;
389       break;
390   }
391
392   // Check status of policy CMP0100 regarding handling of .hh headers
393   switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0100)) {
394     case cmPolicies::WARN:
395       // Ignore but .hh files but warn
396       this->CMP0100Warn = true;
397       CM_FALLTHROUGH;
398     case cmPolicies::OLD:
399       // Ignore .hh files
400       break;
401     case cmPolicies::REQUIRED_IF_USED:
402     case cmPolicies::REQUIRED_ALWAYS:
403     case cmPolicies::NEW:
404       // Process .hh file
405       this->CMP0100Accept = true;
406       break;
407   }
408
409   // Common directories
410   std::string relativeBuildDir;
411   {
412     // Collapsed current binary directory
413     std::string const cbd = cmSystemTools::CollapseFullPath(
414       std::string(), this->Makefile->GetCurrentBinaryDirectory());
415
416     // Info directory
417     this->Dir.Info = cmStrCat(cbd, "/CMakeFiles/", this->GenTarget->GetName(),
418                               "_autogen.dir");
419     cmSystemTools::ConvertToUnixSlashes(this->Dir.Info);
420
421     // Build directory
422     this->Dir.Build = this->GenTarget->GetSafeProperty("AUTOGEN_BUILD_DIR");
423     if (this->Dir.Build.empty()) {
424       this->Dir.Build =
425         cmStrCat(cbd, '/', this->GenTarget->GetName(), "_autogen");
426     }
427     cmSystemTools::ConvertToUnixSlashes(this->Dir.Build);
428     this->Dir.RelativeBuild =
429       cmSystemTools::RelativePath(cbd, this->Dir.Build);
430     // Cleanup build directory
431     this->AddCleanFile(this->Dir.Build);
432
433     // Working directory
434     this->Dir.Work = cbd;
435     cmSystemTools::ConvertToUnixSlashes(this->Dir.Work);
436
437     // Include directory
438     this->ConfigFileNamesAndGenex(this->Dir.Include, this->Dir.IncludeGenExp,
439                                   cmStrCat(this->Dir.Build, "/include"), "");
440   }
441
442   // Moc, Uic and _autogen target settings
443   if (this->MocOrUicEnabled()) {
444     // Init moc specific settings
445     if (this->Moc.Enabled && !this->InitMoc()) {
446       return false;
447     }
448
449     // Init uic specific settings
450     if (this->Uic.Enabled && !this->InitUic()) {
451       return false;
452     }
453
454     // Autogen target name
455     this->AutogenTarget.Name =
456       cmStrCat(this->GenTarget->GetName(), "_autogen");
457
458     // Autogen target parallel processing
459     {
460       std::string const& prop =
461         this->GenTarget->GetSafeProperty("AUTOGEN_PARALLEL");
462       if (prop.empty() || (prop == "AUTO")) {
463         // Autodetect number of CPUs
464         this->AutogenTarget.Parallel = GetParallelCPUCount();
465       } else {
466         this->AutogenTarget.Parallel = 1;
467       }
468     }
469
470     // Autogen target info and settings files
471     {
472       // Info file
473       this->AutogenTarget.InfoFile =
474         cmStrCat(this->Dir.Info, "/AutogenInfo.json");
475
476       // Used settings file
477       this->ConfigFileNames(this->AutogenTarget.SettingsFile,
478                             cmStrCat(this->Dir.Info, "/AutogenUsed"), ".txt");
479       this->ConfigFileClean(this->AutogenTarget.SettingsFile);
480
481       // Parse cache file
482       this->ConfigFileNames(this->AutogenTarget.ParseCacheFile,
483                             cmStrCat(this->Dir.Info, "/ParseCache"), ".txt");
484       this->ConfigFileClean(this->AutogenTarget.ParseCacheFile);
485     }
486
487     // Autogen target: Compute user defined dependencies
488     {
489       this->AutogenTarget.DependOrigin =
490         this->GenTarget->GetPropertyAsBool("AUTOGEN_ORIGIN_DEPENDS");
491
492       std::string const& deps =
493         this->GenTarget->GetSafeProperty("AUTOGEN_TARGET_DEPENDS");
494       if (!deps.empty()) {
495         for (std::string const& depName : cmExpandedList(deps)) {
496           // Allow target and file dependencies
497           auto* depTarget = this->Makefile->FindTargetToUse(depName);
498           if (depTarget) {
499             this->AutogenTarget.DependTargets.insert(depTarget);
500           } else {
501             this->AutogenTarget.DependFiles.insert(depName);
502           }
503         }
504       }
505     }
506
507     if (this->Moc.Enabled) {
508       // Path prefix
509       if (cmIsOn(this->GenTarget->GetProperty("AUTOMOC_PATH_PREFIX"))) {
510         this->Moc.PathPrefix = true;
511       }
512
513       // CMAKE_AUTOMOC_RELAXED_MODE
514       if (this->Makefile->IsOn("CMAKE_AUTOMOC_RELAXED_MODE")) {
515         this->Moc.RelaxedMode = true;
516         this->Makefile->IssueMessage(
517           MessageType::AUTHOR_WARNING,
518           cmStrCat("AUTOMOC: CMAKE_AUTOMOC_RELAXED_MODE is "
519                    "deprecated an will be removed in the future.  Consider "
520                    "disabling it and converting the target ",
521                    this->GenTarget->GetName(), " to regular mode."));
522       }
523
524       // Options
525       cmExpandList(this->GenTarget->GetSafeProperty("AUTOMOC_MOC_OPTIONS"),
526                    this->Moc.Options);
527       // Filters
528       cmExpandList(this->GenTarget->GetSafeProperty("AUTOMOC_MACRO_NAMES"),
529                    this->Moc.MacroNames);
530       this->Moc.MacroNames.erase(cmRemoveDuplicates(this->Moc.MacroNames),
531                                  this->Moc.MacroNames.end());
532       {
533         auto filterList = cmExpandedList(
534           this->GenTarget->GetSafeProperty("AUTOMOC_DEPEND_FILTERS"));
535         if ((filterList.size() % 2) != 0) {
536           cmSystemTools::Error(
537             cmStrCat("AutoMoc: AUTOMOC_DEPEND_FILTERS predefs size ",
538                      filterList.size(), " is not a multiple of 2."));
539           return false;
540         }
541         this->Moc.DependFilters.reserve(1 + (filterList.size() / 2));
542         this->Moc.DependFilters.emplace_back(
543           "Q_PLUGIN_METADATA",
544           "[\n][ \t]*Q_PLUGIN_METADATA[ \t]*\\("
545           "[^\\)]*FILE[ \t]*\"([^\"]+)\"");
546         for (std::size_t ii = 0; ii != filterList.size(); ii += 2) {
547           this->Moc.DependFilters.emplace_back(filterList[ii],
548                                                filterList[ii + 1]);
549         }
550       }
551     }
552   }
553
554   // Init rcc specific settings
555   if (this->Rcc.Enabled && !this->InitRcc()) {
556     return false;
557   }
558
559   // Add autogen include directory to the origin target INCLUDE_DIRECTORIES
560   if (this->MocOrUicEnabled() || (this->Rcc.Enabled && this->MultiConfig)) {
561     this->GenTarget->AddIncludeDirectory(this->Dir.IncludeGenExp, true);
562   }
563
564   // Scan files
565   if (!this->InitScanFiles()) {
566     return false;
567   }
568
569   // Create autogen target
570   if (this->MocOrUicEnabled() && !this->InitAutogenTarget()) {
571     return false;
572   }
573
574   // Create rcc targets
575   if (this->Rcc.Enabled && !this->InitRccTargets()) {
576     return false;
577   }
578
579   return true;
580 }
581
582 bool cmQtAutoGenInitializer::InitMoc()
583 {
584   // Mocs compilation file
585   if (this->GlobalGen->IsXcode()) {
586     // XXX(xcode-per-cfg-src): Drop this Xcode-specific code path
587     // when the Xcode generator supports per-config sources.
588     this->Moc.CompilationFile.Default =
589       cmStrCat(this->Dir.Build, "/mocs_compilation.cpp");
590     this->Moc.CompilationFileGenex = this->Moc.CompilationFile.Default;
591   } else {
592     this->ConfigFileNamesAndGenex(
593       this->Moc.CompilationFile, this->Moc.CompilationFileGenex,
594       cmStrCat(this->Dir.Build, "/mocs_compilation"_s), ".cpp"_s);
595   }
596
597   // Moc predefs
598   if (this->GenTarget->GetPropertyAsBool("AUTOMOC_COMPILER_PREDEFINES") &&
599       (this->QtVersion >= IntegerVersion(5, 8))) {
600     // Command
601     this->Makefile->GetDefExpandList("CMAKE_CXX_COMPILER_PREDEFINES_COMMAND",
602                                      this->Moc.PredefsCmd);
603     // Header
604     if (!this->Moc.PredefsCmd.empty()) {
605       this->ConfigFileNames(this->Moc.PredefsFile,
606                             cmStrCat(this->Dir.Build, "/moc_predefs"), ".h");
607     }
608   }
609
610   // Moc includes
611   {
612     SearchPathSanitizer sanitizer(this->Makefile);
613     auto getDirs =
614       [this, &sanitizer](std::string const& cfg) -> std::vector<std::string> {
615       // Get the include dirs for this target, without stripping the implicit
616       // include dirs off, see issue #13667.
617       std::vector<std::string> dirs;
618       bool const appendImplicit = (this->QtVersion.Major >= 5);
619       this->LocalGen->GetIncludeDirectoriesImplicit(
620         dirs, this->GenTarget, "CXX", cfg, false, appendImplicit);
621       return sanitizer(dirs);
622     };
623
624     // Default configuration include directories
625     this->Moc.Includes.Default = getDirs(this->ConfigDefault);
626     // Other configuration settings
627     if (this->MultiConfig) {
628       for (std::string const& cfg : this->ConfigsList) {
629         std::vector<std::string> dirs = getDirs(cfg);
630         if (dirs == this->Moc.Includes.Default) {
631           continue;
632         }
633         this->Moc.Includes.Config[cfg] = std::move(dirs);
634       }
635     }
636   }
637
638   // Moc compile definitions
639   {
640     auto getDefs = [this](std::string const& cfg) -> std::set<std::string> {
641       std::set<std::string> defines;
642       this->LocalGen->GetTargetDefines(this->GenTarget, cfg, "CXX", defines);
643       if (this->Moc.PredefsCmd.empty() &&
644           this->Makefile->GetSafeDefinition("CMAKE_SYSTEM_NAME") ==
645             "Windows") {
646         // Add WIN32 definition if we don't have a moc_predefs.h
647         defines.insert("WIN32");
648       }
649       return defines;
650     };
651
652     // Default configuration defines
653     this->Moc.Defines.Default = getDefs(this->ConfigDefault);
654     // Other configuration defines
655     if (this->MultiConfig) {
656       for (std::string const& cfg : this->ConfigsList) {
657         std::set<std::string> defines = getDefs(cfg);
658         if (defines == this->Moc.Defines.Default) {
659           continue;
660         }
661         this->Moc.Defines.Config[cfg] = std::move(defines);
662       }
663     }
664   }
665
666   // Moc executable
667   {
668     if (!this->GetQtExecutable(this->Moc, "moc", false)) {
669       return false;
670     }
671     // Let the _autogen target depend on the moc executable
672     if (this->Moc.ExecutableTarget) {
673       this->AutogenTarget.DependTargets.insert(
674         this->Moc.ExecutableTarget->Target);
675     }
676   }
677
678   return true;
679 }
680
681 bool cmQtAutoGenInitializer::InitUic()
682 {
683   // Uic search paths
684   {
685     std::string const& usp =
686       this->GenTarget->GetSafeProperty("AUTOUIC_SEARCH_PATHS");
687     if (!usp.empty()) {
688       this->Uic.SearchPaths =
689         SearchPathSanitizer(this->Makefile)(cmExpandedList(usp));
690     }
691   }
692   // Uic target options
693   {
694     auto getOpts = [this](std::string const& cfg) -> std::vector<std::string> {
695       std::vector<std::string> opts;
696       this->GenTarget->GetAutoUicOptions(opts, cfg);
697       return opts;
698     };
699
700     // Default options
701     this->Uic.Options.Default = getOpts(this->ConfigDefault);
702     // Configuration specific options
703     if (this->MultiConfig) {
704       for (std::string const& cfg : this->ConfigsList) {
705         std::vector<std::string> options = getOpts(cfg);
706         if (options == this->Uic.Options.Default) {
707           continue;
708         }
709         this->Uic.Options.Config[cfg] = std::move(options);
710       }
711     }
712   }
713
714   // Uic executable
715   {
716     if (!this->GetQtExecutable(this->Uic, "uic", true)) {
717       return false;
718     }
719     // Let the _autogen target depend on the uic executable
720     if (this->Uic.ExecutableTarget) {
721       this->AutogenTarget.DependTargets.insert(
722         this->Uic.ExecutableTarget->Target);
723     }
724   }
725
726   return true;
727 }
728
729 bool cmQtAutoGenInitializer::InitRcc()
730 {
731   // Rcc executable
732   {
733     if (!this->GetQtExecutable(this->Rcc, "rcc", false)) {
734       return false;
735     }
736     // Evaluate test output on demand
737     CompilerFeatures& features = *this->Rcc.ExecutableFeatures;
738     if (!features.Evaluated) {
739       // Look for list options
740       if (this->QtVersion.Major == 5 || this->QtVersion.Major == 6) {
741         if (features.HelpOutput.find("--list") != std::string::npos) {
742           features.ListOptions.emplace_back("--list");
743         } else if (features.HelpOutput.find("-list") != std::string::npos) {
744           features.ListOptions.emplace_back("-list");
745         }
746       }
747       // Evaluation finished
748       features.Evaluated = true;
749     }
750   }
751
752   return true;
753 }
754
755 bool cmQtAutoGenInitializer::InitScanFiles()
756 {
757   cmake const* cm = this->Makefile->GetCMakeInstance();
758   auto const& kw = this->GlobalInitializer->kw();
759
760   auto makeMUFile = [this, &kw](cmSourceFile* sf, std::string const& fullPath,
761                                 std::vector<size_t> const& configs,
762                                 bool muIt) -> MUFileHandle {
763     MUFileHandle muf = cm::make_unique<MUFile>();
764     muf->FullPath = fullPath;
765     muf->SF = sf;
766     if (!configs.empty() && configs.size() != this->ConfigsList.size()) {
767       muf->Configs = configs;
768     }
769     muf->Generated = sf->GetIsGenerated();
770     bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
771     muf->SkipMoc = this->Moc.Enabled &&
772       (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOMOC));
773     muf->SkipUic = this->Uic.Enabled &&
774       (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
775     if (muIt) {
776       muf->MocIt = this->Moc.Enabled && !muf->SkipMoc;
777       muf->UicIt = this->Uic.Enabled && !muf->SkipUic;
778     }
779     return muf;
780   };
781
782   auto addMUHeader = [this](MUFileHandle&& muf, cm::string_view extension) {
783     cmSourceFile* sf = muf->SF;
784     const bool muIt = (muf->MocIt || muf->UicIt);
785     if (this->CMP0100Accept || (extension != "hh")) {
786       // Accept
787       if (muIt && muf->Generated) {
788         this->AutogenTarget.FilesGenerated.emplace_back(muf.get());
789       }
790       this->AutogenTarget.Headers.emplace(sf, std::move(muf));
791     } else if (muIt && this->CMP0100Warn) {
792       // Store file for warning message
793       this->AutogenTarget.CMP0100HeadersWarn.push_back(sf);
794     }
795   };
796
797   auto addMUSource = [this](MUFileHandle&& muf) {
798     if ((muf->MocIt || muf->UicIt) && muf->Generated) {
799       this->AutogenTarget.FilesGenerated.emplace_back(muf.get());
800     }
801     this->AutogenTarget.Sources.emplace(muf->SF, std::move(muf));
802   };
803
804   // Scan through target files
805   {
806     // Scan through target files
807     for (cmGeneratorTarget::AllConfigSource const& acs :
808          this->GenTarget->GetAllConfigSources()) {
809       std::string const& fullPath = acs.Source->GetFullPath();
810       std::string const& extLower =
811         cmSystemTools::LowerCase(acs.Source->GetExtension());
812
813       // Register files that will be scanned by moc or uic
814       if (this->MocOrUicEnabled()) {
815         if (cm->IsAHeaderExtension(extLower)) {
816           addMUHeader(makeMUFile(acs.Source, fullPath, acs.Configs, true),
817                       extLower);
818         } else if (cm->IsACLikeSourceExtension(extLower)) {
819           addMUSource(makeMUFile(acs.Source, fullPath, acs.Configs, true));
820         }
821       }
822
823       // Register rcc enabled files
824       if (this->Rcc.Enabled) {
825         if ((extLower == kw.qrc) &&
826             !acs.Source->GetPropertyAsBool(kw.SKIP_AUTOGEN) &&
827             !acs.Source->GetPropertyAsBool(kw.SKIP_AUTORCC)) {
828           // Register qrc file
829           Qrc qrc;
830           qrc.QrcFile = fullPath;
831           qrc.QrcName =
832             cmSystemTools::GetFilenameWithoutLastExtension(qrc.QrcFile);
833           qrc.Generated = acs.Source->GetIsGenerated();
834           // RCC options
835           {
836             std::string const& opts =
837               acs.Source->GetSafeProperty(kw.AUTORCC_OPTIONS);
838             if (!opts.empty()) {
839               cmExpandList(opts, qrc.Options);
840             }
841           }
842           this->Rcc.Qrcs.push_back(std::move(qrc));
843         }
844       }
845     }
846   }
847   // cmGeneratorTarget::GetAllConfigSources computes the target's
848   // sources meta data cache. Clear it so that OBJECT library targets that
849   // are AUTOGEN initialized after this target get their added
850   // mocs_compilation.cpp source acknowledged by this target.
851   this->GenTarget->ClearSourcesCache();
852
853   // For source files find additional headers and private headers
854   if (this->MocOrUicEnabled()) {
855     // Header search suffixes and extensions
856     static std::initializer_list<cm::string_view> const suffixes{ "", "_p" };
857     auto const& exts = cm->GetHeaderExtensions();
858     // Scan through sources
859     for (auto const& pair : this->AutogenTarget.Sources) {
860       MUFile const& muf = *pair.second;
861       if (muf.MocIt || muf.UicIt) {
862         // Search for the default header file and a private header
863         std::string const& srcFullPath = muf.SF->ResolveFullPath();
864         std::string basePath = cmStrCat(
865           cmQtAutoGen::SubDirPrefix(srcFullPath),
866           cmSystemTools::GetFilenameWithoutLastExtension(srcFullPath));
867         for (auto const& suffix : suffixes) {
868           std::string const suffixedPath = cmStrCat(basePath, suffix);
869           for (auto const& ext : exts) {
870             std::string fullPath = cmStrCat(suffixedPath, '.', ext);
871
872             auto constexpr locationKind = cmSourceFileLocationKind::Known;
873             cmSourceFile* sf =
874               this->Makefile->GetSource(fullPath, locationKind);
875             if (sf) {
876               // Check if we know about this header already
877               if (cm::contains(this->AutogenTarget.Headers, sf)) {
878                 continue;
879               }
880               // We only accept not-GENERATED files that do exist.
881               if (!sf->GetIsGenerated() &&
882                   !cmSystemTools::FileExists(fullPath)) {
883                 continue;
884               }
885             } else if (cmSystemTools::FileExists(fullPath)) {
886               // Create a new source file for the existing file
887               sf = this->Makefile->CreateSource(fullPath, false, locationKind);
888             }
889
890             if (sf) {
891               auto eMuf = makeMUFile(sf, fullPath, muf.Configs, true);
892               // Only process moc/uic when the parent is processed as well
893               if (!muf.MocIt) {
894                 eMuf->MocIt = false;
895               }
896               if (!muf.UicIt) {
897                 eMuf->UicIt = false;
898               }
899               addMUHeader(std::move(eMuf), ext);
900             }
901           }
902         }
903       }
904     }
905   }
906
907   // Scan through all source files in the makefile to extract moc and uic
908   // parameters.  Historically we support non target source file parameters.
909   // The reason is that their file names might be discovered from source files
910   // at generation time.
911   if (this->MocOrUicEnabled()) {
912     for (const auto& sf : this->Makefile->GetSourceFiles()) {
913       // sf->GetExtension() is only valid after sf->ResolveFullPath() ...
914       // Since we're iterating over source files that might be not in the
915       // target we need to check for path errors (not existing files).
916       std::string pathError;
917       std::string const& fullPath = sf->ResolveFullPath(&pathError);
918       if (!pathError.empty() || fullPath.empty()) {
919         continue;
920       }
921       std::string const& extLower =
922         cmSystemTools::LowerCase(sf->GetExtension());
923
924       if (cm->IsAHeaderExtension(extLower)) {
925         if (!cm::contains(this->AutogenTarget.Headers, sf.get())) {
926           auto muf = makeMUFile(sf.get(), fullPath, {}, false);
927           if (muf->SkipMoc || muf->SkipUic) {
928             addMUHeader(std::move(muf), extLower);
929           }
930         }
931       } else if (cm->IsACLikeSourceExtension(extLower)) {
932         if (!cm::contains(this->AutogenTarget.Sources, sf.get())) {
933           auto muf = makeMUFile(sf.get(), fullPath, {}, false);
934           if (muf->SkipMoc || muf->SkipUic) {
935             addMUSource(std::move(muf));
936           }
937         }
938       } else if (this->Uic.Enabled && (extLower == kw.ui)) {
939         // .ui file
940         bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
941         bool const skipUic =
942           (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
943         if (!skipUic) {
944           // Check if the .ui file has uic options
945           std::string const uicOpts = sf->GetSafeProperty(kw.AUTOUIC_OPTIONS);
946           if (uicOpts.empty()) {
947             this->Uic.UiFilesNoOptions.emplace_back(fullPath);
948           } else {
949             this->Uic.UiFilesWithOptions.emplace_back(fullPath,
950                                                       cmExpandedList(uicOpts));
951           }
952
953           auto uiHeaderRelativePath = cmSystemTools::RelativePath(
954             this->LocalGen->GetCurrentSourceDirectory(),
955             cmSystemTools::GetFilenamePath(fullPath));
956
957           // Avoid creating a path containing adjacent slashes
958           if (!uiHeaderRelativePath.empty() &&
959               uiHeaderRelativePath.back() != '/') {
960             uiHeaderRelativePath += '/';
961           }
962
963           auto uiHeaderFilePath = cmStrCat(
964             '/', uiHeaderRelativePath, "ui_"_s,
965             cmSystemTools::GetFilenameWithoutLastExtension(fullPath), ".h"_s);
966
967           ConfigString uiHeader;
968           std::string uiHeaderGenex;
969           this->ConfigFileNamesAndGenex(
970             uiHeader, uiHeaderGenex, cmStrCat(this->Dir.Build, "/include"_s),
971             uiHeaderFilePath);
972
973           this->Uic.UiHeaders.emplace_back(
974             std::make_pair(uiHeader, uiHeaderGenex));
975         } else {
976           // Register skipped .ui file
977           this->Uic.SkipUi.insert(fullPath);
978         }
979       }
980     }
981   }
982
983   // Process GENERATED sources and headers
984   if (this->MocOrUicEnabled() && !this->AutogenTarget.FilesGenerated.empty()) {
985     if (this->CMP0071Accept) {
986       // Let the autogen target depend on the GENERATED files
987       for (MUFile* muf : this->AutogenTarget.FilesGenerated) {
988         this->AutogenTarget.DependFiles.insert(muf->FullPath);
989       }
990     } else if (this->CMP0071Warn) {
991       cm::string_view property;
992       if (this->Moc.Enabled && this->Uic.Enabled) {
993         property = "SKIP_AUTOGEN";
994       } else if (this->Moc.Enabled) {
995         property = "SKIP_AUTOMOC";
996       } else if (this->Uic.Enabled) {
997         property = "SKIP_AUTOUIC";
998       }
999       std::string files;
1000       for (MUFile* muf : this->AutogenTarget.FilesGenerated) {
1001         files += cmStrCat("  ", Quoted(muf->FullPath), '\n');
1002       }
1003       this->Makefile->IssueMessage(
1004         MessageType::AUTHOR_WARNING,
1005         cmStrCat(
1006           cmPolicies::GetPolicyWarning(cmPolicies::CMP0071), '\n',
1007           "For compatibility, CMake is excluding the GENERATED source "
1008           "file(s):\n",
1009           files, "from processing by ",
1010           cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
1011           ".  If any of the files should be processed, set CMP0071 to NEW.  "
1012           "If any of the files should not be processed, "
1013           "explicitly exclude them by setting the source file property ",
1014           property, ":\n  set_property(SOURCE file.h PROPERTY ", property,
1015           " ON)\n"));
1016     }
1017   }
1018
1019   // Generate CMP0100 warning
1020   if (this->MocOrUicEnabled() &&
1021       !this->AutogenTarget.CMP0100HeadersWarn.empty()) {
1022     cm::string_view property;
1023     if (this->Moc.Enabled && this->Uic.Enabled) {
1024       property = "SKIP_AUTOGEN";
1025     } else if (this->Moc.Enabled) {
1026       property = "SKIP_AUTOMOC";
1027     } else if (this->Uic.Enabled) {
1028       property = "SKIP_AUTOUIC";
1029     }
1030     std::string files;
1031     for (cmSourceFile* sf : this->AutogenTarget.CMP0100HeadersWarn) {
1032       files += cmStrCat("  ", Quoted(sf->GetFullPath()), '\n');
1033     }
1034     this->Makefile->IssueMessage(
1035       MessageType::AUTHOR_WARNING,
1036       cmStrCat(
1037         cmPolicies::GetPolicyWarning(cmPolicies::CMP0100), '\n',
1038         "For compatibility, CMake is excluding the header file(s):\n", files,
1039         "from processing by ",
1040         cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
1041         ".  If any of the files should be processed, set CMP0100 to NEW.  "
1042         "If any of the files should not be processed, "
1043         "explicitly exclude them by setting the source file property ",
1044         property, ":\n  set_property(SOURCE file.hh PROPERTY ", property,
1045         " ON)\n"));
1046   }
1047
1048   // Process qrc files
1049   if (!this->Rcc.Qrcs.empty()) {
1050     const bool modernQt = (this->QtVersion.Major >= 5);
1051     // Target rcc options
1052     std::vector<std::string> optionsTarget =
1053       cmExpandedList(this->GenTarget->GetSafeProperty(kw.AUTORCC_OPTIONS));
1054
1055     // Check if file name is unique
1056     for (Qrc& qrc : this->Rcc.Qrcs) {
1057       qrc.Unique = true;
1058       for (Qrc const& qrc2 : this->Rcc.Qrcs) {
1059         if ((&qrc != &qrc2) && (qrc.QrcName == qrc2.QrcName)) {
1060           qrc.Unique = false;
1061           break;
1062         }
1063       }
1064     }
1065     // Path checksum and file names
1066     for (Qrc& qrc : this->Rcc.Qrcs) {
1067       // Path checksum
1068       qrc.QrcPathChecksum = this->PathCheckSum.getPart(qrc.QrcFile);
1069       // Output file name
1070       qrc.OutputFile = cmStrCat(this->Dir.Build, '/', qrc.QrcPathChecksum,
1071                                 "/qrc_", qrc.QrcName, ".cpp");
1072       std::string const base = cmStrCat(this->Dir.Info, "/AutoRcc_",
1073                                         qrc.QrcName, '_', qrc.QrcPathChecksum);
1074       qrc.LockFile = cmStrCat(base, "_Lock.lock");
1075       qrc.InfoFile = cmStrCat(base, "_Info.json");
1076       this->ConfigFileNames(qrc.SettingsFile, cmStrCat(base, "_Used"), ".txt");
1077     }
1078     // rcc options
1079     for (Qrc& qrc : this->Rcc.Qrcs) {
1080       // Target options
1081       std::vector<std::string> opts = optionsTarget;
1082       // Merge computed "-name XYZ" option
1083       {
1084         std::string name = qrc.QrcName;
1085         // Replace '-' with '_'. The former is not valid for symbol names.
1086         std::replace(name.begin(), name.end(), '-', '_');
1087         if (!qrc.Unique) {
1088           name += cmStrCat('_', qrc.QrcPathChecksum);
1089         }
1090         std::vector<std::string> nameOpts;
1091         nameOpts.emplace_back("-name");
1092         nameOpts.emplace_back(std::move(name));
1093         RccMergeOptions(opts, nameOpts, modernQt);
1094       }
1095       // Merge file option
1096       RccMergeOptions(opts, qrc.Options, modernQt);
1097       qrc.Options = std::move(opts);
1098     }
1099     // rcc resources
1100     for (Qrc& qrc : this->Rcc.Qrcs) {
1101       if (!qrc.Generated) {
1102         std::string error;
1103         RccLister const lister(this->Rcc.Executable,
1104                                this->Rcc.ExecutableFeatures->ListOptions);
1105         if (!lister.list(qrc.QrcFile, qrc.Resources, error)) {
1106           cmSystemTools::Error(error);
1107           return false;
1108         }
1109       }
1110     }
1111   }
1112
1113   return true;
1114 }
1115
1116 bool cmQtAutoGenInitializer::InitAutogenTarget()
1117 {
1118   // Register info file as generated by CMake
1119   this->Makefile->AddCMakeOutputFile(this->AutogenTarget.InfoFile);
1120
1121   // Determine whether to use a depfile for the AUTOGEN target.
1122   const bool useNinjaDepfile = this->QtVersion >= IntegerVersion(5, 15) &&
1123     this->GlobalGen->GetName().find("Ninja") != std::string::npos;
1124
1125   // Files provided by the autogen target
1126   std::vector<std::string> autogenByproducts;
1127   std::vector<std::string> timestampByproducts;
1128   if (this->Moc.Enabled) {
1129     this->AddGeneratedSource(this->Moc.CompilationFile, this->Moc, true);
1130     if (useNinjaDepfile) {
1131       if (this->MultiConfig) {
1132         // Make all mocs_compilation_<CONFIG>.cpp files byproducts of the
1133         // ${target}_autogen/timestamp custom command.
1134         // We cannot just use Moc.CompilationFileGenex here, because that
1135         // custom command runs cmake_autogen for each configuration.
1136         for (const auto& p : this->Moc.CompilationFile.Config) {
1137           timestampByproducts.push_back(p.second);
1138         }
1139       } else {
1140         timestampByproducts.push_back(this->Moc.CompilationFileGenex);
1141       }
1142     } else {
1143       autogenByproducts.push_back(this->Moc.CompilationFileGenex);
1144     }
1145   }
1146
1147   if (this->Uic.Enabled) {
1148     for (const auto& file : this->Uic.UiHeaders) {
1149       this->AddGeneratedSource(file.first, this->Uic);
1150       autogenByproducts.push_back(file.second);
1151     }
1152   }
1153
1154   // Compose target comment
1155   std::string autogenComment;
1156   {
1157     std::string tools;
1158     if (this->Moc.Enabled) {
1159       tools += "MOC";
1160     }
1161     if (this->Uic.Enabled) {
1162       if (!tools.empty()) {
1163         tools += " and ";
1164       }
1165       tools += "UIC";
1166     }
1167     autogenComment = cmStrCat("Automatic ", tools, " for target ",
1168                               this->GenTarget->GetName());
1169   }
1170
1171   // Compose command lines
1172   // FIXME: Take advantage of our per-config mocs_compilation_$<CONFIG>.cpp
1173   // instead of fiddling with the include directories
1174   std::vector<std::string> configs;
1175   this->GlobalGen->GetQtAutoGenConfigs(configs);
1176   bool stdPipesUTF8 = true;
1177   cmCustomCommandLines commandLines;
1178   for (auto const& config : configs) {
1179     commandLines.push_back(cmMakeCommandLine(
1180       { cmSystemTools::GetCMakeCommand(), "-E", "cmake_autogen",
1181         this->AutogenTarget.InfoFile, config }));
1182   }
1183
1184   // Use PRE_BUILD on demand
1185   bool usePRE_BUILD = false;
1186   if (this->GlobalGen->GetName().find("Visual Studio") != std::string::npos) {
1187     // Under VS use a PRE_BUILD event instead of a separate target to
1188     // reduce the number of targets loaded into the IDE.
1189     // This also works around a VS 11 bug that may skip updating the target:
1190     //  https://connect.microsoft.com/VisualStudio/feedback/details/769495
1191     usePRE_BUILD = true;
1192   }
1193   // Disable PRE_BUILD in some cases
1194   if (usePRE_BUILD) {
1195     // Cannot use PRE_BUILD with file depends
1196     if (!this->AutogenTarget.DependFiles.empty()) {
1197       usePRE_BUILD = false;
1198     }
1199     // Cannot use PRE_BUILD when a global autogen target is in place
1200     if (this->AutogenTarget.GlobalTarget) {
1201       usePRE_BUILD = false;
1202     }
1203   }
1204   // Create the autogen target/command
1205   if (usePRE_BUILD) {
1206     // Add additional autogen target dependencies to origin target
1207     for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
1208       this->GenTarget->Target->AddUtility(depTarget->GetName(), false,
1209                                           this->Makefile);
1210     }
1211
1212     if (!this->Uic.UiFilesNoOptions.empty() ||
1213         !this->Uic.UiFilesWithOptions.empty()) {
1214       // Add a generated timestamp file
1215       ConfigString timestampFile;
1216       std::string timestampFileGenex;
1217       ConfigFileNamesAndGenex(timestampFile, timestampFileGenex,
1218                               cmStrCat(this->Dir.Build, "/autouic"_s),
1219                               ".stamp"_s);
1220       this->AddGeneratedSource(timestampFile, this->Uic);
1221
1222       // Add a step in the pre-build command to touch the timestamp file
1223       commandLines.push_back(
1224         cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E", "touch",
1225                             timestampFileGenex }));
1226
1227       // UIC needs to be re-run if any of the known UI files change or the
1228       // executable itself has been updated
1229       auto uicDependencies = this->Uic.UiFilesNoOptions;
1230       for (auto const& uiFile : this->Uic.UiFilesWithOptions) {
1231         uicDependencies.push_back(uiFile.first);
1232       }
1233       AddAutogenExecutableToDependencies(this->Uic, uicDependencies);
1234
1235       // Add a rule file to cause the target to build if a dependency has
1236       // changed, which will trigger the pre-build command to run autogen
1237       auto cc = cm::make_unique<cmCustomCommand>();
1238       cc->SetOutputs(timestampFileGenex);
1239       cc->SetDepends(uicDependencies);
1240       cc->SetComment("");
1241       cc->SetWorkingDirectory(this->Dir.Work.c_str());
1242       cc->SetCMP0116Status(cmPolicies::NEW);
1243       cc->SetEscapeOldStyle(false);
1244       cc->SetStdPipesUTF8(stdPipesUTF8);
1245       this->LocalGen->AddCustomCommandToOutput(std::move(cc));
1246     }
1247
1248     // Add the pre-build command directly to bypass the OBJECT_LIBRARY
1249     // rejection in cmMakefile::AddCustomCommandToTarget because we know
1250     // PRE_BUILD will work for an OBJECT_LIBRARY in this specific case.
1251     //
1252     // PRE_BUILD does not support file dependencies!
1253     cmCustomCommand cc;
1254     cc.SetByproducts(autogenByproducts);
1255     cc.SetCommandLines(commandLines);
1256     cc.SetComment(autogenComment.c_str());
1257     cc.SetBacktrace(this->Makefile->GetBacktrace());
1258     cc.SetWorkingDirectory(this->Dir.Work.c_str());
1259     cc.SetStdPipesUTF8(stdPipesUTF8);
1260     cc.SetEscapeOldStyle(false);
1261     cc.SetEscapeAllowMakeVars(true);
1262     this->GenTarget->Target->AddPreBuildCommand(std::move(cc));
1263   } else {
1264
1265     // Add link library target dependencies to the autogen target
1266     // dependencies
1267     if (this->AutogenTarget.DependOrigin) {
1268       // add_dependencies/addUtility do not support generator expressions.
1269       // We depend only on the libraries found in all configs therefore.
1270       std::map<cmGeneratorTarget const*, std::size_t> commonTargets;
1271       for (std::string const& config : this->ConfigsList) {
1272         cmLinkImplementationLibraries const* libs =
1273           this->GenTarget->GetLinkImplementationLibraries(
1274             config, cmGeneratorTarget::LinkInterfaceFor::Link);
1275         if (libs) {
1276           for (cmLinkItem const& item : libs->Libraries) {
1277             cmGeneratorTarget const* libTarget = item.Target;
1278             if (libTarget &&
1279                 !StaticLibraryCycle(this->GenTarget, libTarget, config)) {
1280               // Increment target config count
1281               commonTargets[libTarget]++;
1282             }
1283           }
1284         }
1285       }
1286       for (auto const& item : commonTargets) {
1287         if (item.second == this->ConfigsList.size()) {
1288           this->AutogenTarget.DependTargets.insert(item.first->Target);
1289         }
1290       }
1291     }
1292
1293     std::vector<std::string> dependencies(
1294       this->AutogenTarget.DependFiles.begin(),
1295       this->AutogenTarget.DependFiles.end());
1296
1297     if (useNinjaDepfile) {
1298       // Create a custom command that generates a timestamp file and
1299       // has a depfile assigned. The depfile is created by JobDepFilesMergeT.
1300       //
1301       // Also create an additional '_autogen_timestamp_deps' that the custom
1302       // command will depend on. It will have no sources or commands to
1303       // execute, but it will have dependencies that would originally be
1304       // assigned to the pre-Qt 5.15 'autogen' target. These dependencies will
1305       // serve as a list of order-only dependencies for the custom command,
1306       // without forcing the custom command to re-execute.
1307       //
1308       // The dependency tree would then look like
1309       // '_autogen_timestamp_deps (order-only)' <- '/timestamp' file <-
1310       // '_autogen' target.
1311       const auto timestampTargetName =
1312         cmStrCat(this->GenTarget->GetName(), "_autogen_timestamp_deps");
1313       std::vector<std::string> timestampTargetProvides;
1314       cmCustomCommandLines timestampTargetCommandLines;
1315
1316       // Add additional autogen target dependencies to
1317       // '_autogen_timestamp_deps'.
1318       for (const cmTarget* t : this->AutogenTarget.DependTargets) {
1319         std::string depname = t->GetName();
1320         if (t->IsImported()) {
1321           auto ttype = t->GetType();
1322           if (ttype == cmStateEnums::TargetType::STATIC_LIBRARY ||
1323               ttype == cmStateEnums::TargetType::SHARED_LIBRARY ||
1324               ttype == cmStateEnums::TargetType::UNKNOWN_LIBRARY) {
1325             depname = cmStrCat("$<TARGET_LINKER_FILE:", t->GetName(), ">");
1326           }
1327         }
1328         dependencies.push_back(depname);
1329       }
1330
1331       auto cc = cm::make_unique<cmCustomCommand>();
1332       cc->SetWorkingDirectory(this->Dir.Work.c_str());
1333       cc->SetByproducts(timestampTargetProvides);
1334       cc->SetDepends(dependencies);
1335       cc->SetCommandLines(timestampTargetCommandLines);
1336       cc->SetCMP0116Status(cmPolicies::NEW);
1337       cc->SetEscapeOldStyle(false);
1338       cmTarget* timestampTarget = this->LocalGen->AddUtilityCommand(
1339         timestampTargetName, true, std::move(cc));
1340       this->LocalGen->AddGeneratorTarget(
1341         cm::make_unique<cmGeneratorTarget>(timestampTarget, this->LocalGen));
1342
1343       // Set FOLDER property on the timestamp target, so it appears in the
1344       // appropriate folder in an IDE or in the file api.
1345       if (!this->TargetsFolder.empty()) {
1346         timestampTarget->SetProperty("FOLDER", this->TargetsFolder);
1347       }
1348
1349       // Make '/timestamp' file depend on '_autogen_timestamp_deps' and on the
1350       // moc and uic executables (whichever are enabled).
1351       dependencies.clear();
1352       dependencies.push_back(timestampTargetName);
1353
1354       AddAutogenExecutableToDependencies(this->Moc, dependencies);
1355       AddAutogenExecutableToDependencies(this->Uic, dependencies);
1356
1357       // Create the custom command that outputs the timestamp file.
1358       const char timestampFileName[] = "timestamp";
1359       const std::string outputFile =
1360         cmStrCat(this->Dir.Build, "/", timestampFileName);
1361       this->AutogenTarget.DepFile = cmStrCat(this->Dir.Build, "/deps");
1362       this->AutogenTarget.DepFileRuleName =
1363         cmStrCat(this->Dir.RelativeBuild, "/", timestampFileName);
1364       commandLines.push_back(cmMakeCommandLine(
1365         { cmSystemTools::GetCMakeCommand(), "-E", "touch", outputFile }));
1366
1367       this->AddGeneratedSource(outputFile, this->Moc);
1368       cc = cm::make_unique<cmCustomCommand>();
1369       cc->SetOutputs(outputFile);
1370       cc->SetByproducts(timestampByproducts);
1371       cc->SetDepends(dependencies);
1372       cc->SetCommandLines(commandLines);
1373       cc->SetComment(autogenComment.c_str());
1374       cc->SetWorkingDirectory(this->Dir.Work.c_str());
1375       cc->SetCMP0116Status(cmPolicies::NEW);
1376       cc->SetEscapeOldStyle(false);
1377       cc->SetDepfile(this->AutogenTarget.DepFile);
1378       cc->SetStdPipesUTF8(stdPipesUTF8);
1379       this->LocalGen->AddCustomCommandToOutput(std::move(cc));
1380
1381       // Alter variables for the autogen target which now merely wraps the
1382       // custom command
1383       dependencies.clear();
1384       dependencies.push_back(outputFile);
1385       commandLines.clear();
1386       autogenComment.clear();
1387     }
1388
1389     // Create autogen target
1390     auto cc = cm::make_unique<cmCustomCommand>();
1391     cc->SetWorkingDirectory(this->Dir.Work.c_str());
1392     cc->SetByproducts(autogenByproducts);
1393     cc->SetDepends(dependencies);
1394     cc->SetCommandLines(commandLines);
1395     cc->SetCMP0116Status(cmPolicies::NEW);
1396     cc->SetEscapeOldStyle(false);
1397     cc->SetComment(autogenComment.c_str());
1398     cmTarget* autogenTarget = this->LocalGen->AddUtilityCommand(
1399       this->AutogenTarget.Name, true, std::move(cc));
1400     // Create autogen generator target
1401     this->LocalGen->AddGeneratorTarget(
1402       cm::make_unique<cmGeneratorTarget>(autogenTarget, this->LocalGen));
1403
1404     // Forward origin utilities to autogen target
1405     if (this->AutogenTarget.DependOrigin) {
1406       for (BT<std::pair<std::string, bool>> const& depName :
1407            this->GenTarget->GetUtilities()) {
1408         autogenTarget->AddUtility(depName.Value.first, false, this->Makefile);
1409       }
1410     }
1411     if (!useNinjaDepfile) {
1412       // Add additional autogen target dependencies to autogen target
1413       for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
1414         autogenTarget->AddUtility(depTarget->GetName(), false, this->Makefile);
1415       }
1416     }
1417
1418     // Set FOLDER property in autogen target
1419     if (!this->TargetsFolder.empty()) {
1420       autogenTarget->SetProperty("FOLDER", this->TargetsFolder);
1421     }
1422
1423     // Add autogen target to the origin target dependencies
1424     this->GenTarget->Target->AddUtility(this->AutogenTarget.Name, false,
1425                                         this->Makefile);
1426
1427     // Add autogen target to the global autogen target dependencies
1428     if (this->AutogenTarget.GlobalTarget) {
1429       this->GlobalInitializer->AddToGlobalAutoGen(this->LocalGen,
1430                                                   this->AutogenTarget.Name);
1431     }
1432   }
1433
1434   return true;
1435 }
1436
1437 bool cmQtAutoGenInitializer::InitRccTargets()
1438 {
1439   for (Qrc const& qrc : this->Rcc.Qrcs) {
1440     // Register info file as generated by CMake
1441     this->Makefile->AddCMakeOutputFile(qrc.InfoFile);
1442     // Register file at target
1443     {
1444       cmSourceFile* sf = this->AddGeneratedSource(qrc.OutputFile, this->Rcc);
1445       sf->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "On");
1446     }
1447
1448     std::vector<std::string> ccOutput;
1449     ccOutput.push_back(qrc.OutputFile);
1450
1451     std::vector<std::string> ccDepends;
1452     // Add the .qrc and info file to the custom command dependencies
1453     ccDepends.push_back(qrc.QrcFile);
1454     ccDepends.push_back(qrc.InfoFile);
1455
1456     cmCustomCommandLines commandLines;
1457     if (this->MultiConfig) {
1458       // Build for all configurations
1459       for (std::string const& config : this->ConfigsList) {
1460         commandLines.push_back(
1461           cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
1462                               "cmake_autorcc", qrc.InfoFile, config }));
1463       }
1464     } else {
1465       commandLines.push_back(
1466         cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
1467                             "cmake_autorcc", qrc.InfoFile, "$<CONFIG>" }));
1468     }
1469     std::string ccComment =
1470       cmStrCat("Automatic RCC for ",
1471                FileProjectRelativePath(this->Makefile, qrc.QrcFile));
1472
1473     auto cc = cm::make_unique<cmCustomCommand>();
1474     cc->SetWorkingDirectory(this->Dir.Work.c_str());
1475     cc->SetCommandLines(commandLines);
1476     cc->SetCMP0116Status(cmPolicies::NEW);
1477     cc->SetComment(ccComment.c_str());
1478     cc->SetStdPipesUTF8(true);
1479
1480     if (qrc.Generated || this->Rcc.GlobalTarget) {
1481       // Create custom rcc target
1482       std::string ccName;
1483       {
1484         ccName = cmStrCat(this->GenTarget->GetName(), "_arcc_", qrc.QrcName);
1485         if (!qrc.Unique) {
1486           ccName += cmStrCat('_', qrc.QrcPathChecksum);
1487         }
1488
1489         cc->SetByproducts(ccOutput);
1490         cc->SetDepends(ccDepends);
1491         cc->SetEscapeOldStyle(false);
1492         cmTarget* autoRccTarget =
1493           this->LocalGen->AddUtilityCommand(ccName, true, std::move(cc));
1494
1495         // Create autogen generator target
1496         this->LocalGen->AddGeneratorTarget(
1497           cm::make_unique<cmGeneratorTarget>(autoRccTarget, this->LocalGen));
1498
1499         // Set FOLDER property in autogen target
1500         if (!this->TargetsFolder.empty()) {
1501           autoRccTarget->SetProperty("FOLDER", this->TargetsFolder);
1502         }
1503         if (!this->Rcc.ExecutableTargetName.empty()) {
1504           autoRccTarget->AddUtility(this->Rcc.ExecutableTargetName, false,
1505                                     this->Makefile);
1506         }
1507       }
1508       // Add autogen target to the origin target dependencies
1509       this->GenTarget->Target->AddUtility(ccName, false, this->Makefile);
1510
1511       // Add autogen target to the global autogen target dependencies
1512       if (this->Rcc.GlobalTarget) {
1513         this->GlobalInitializer->AddToGlobalAutoRcc(this->LocalGen, ccName);
1514       }
1515     } else {
1516       // Create custom rcc command
1517       {
1518         std::vector<std::string> ccByproducts;
1519
1520         // Add the resource files to the dependencies
1521         for (std::string const& fileName : qrc.Resources) {
1522           // Add resource file to the custom command dependencies
1523           ccDepends.push_back(fileName);
1524         }
1525         if (!this->Rcc.ExecutableTargetName.empty()) {
1526           ccDepends.push_back(this->Rcc.ExecutableTargetName);
1527         }
1528         cc->SetOutputs(ccOutput);
1529         cc->SetByproducts(ccByproducts);
1530         cc->SetDepends(ccDepends);
1531         this->LocalGen->AddCustomCommandToOutput(std::move(cc));
1532       }
1533       // Reconfigure when .qrc file changes
1534       this->Makefile->AddCMakeDependFile(qrc.QrcFile);
1535     }
1536   }
1537
1538   return true;
1539 }
1540
1541 bool cmQtAutoGenInitializer::SetupCustomTargets()
1542 {
1543   // Create info directory on demand
1544   if (!cmSystemTools::MakeDirectory(this->Dir.Info)) {
1545     cmSystemTools::Error(cmStrCat("AutoGen: Could not create directory: ",
1546                                   Quoted(this->Dir.Info)));
1547     return false;
1548   }
1549
1550   // Generate autogen target info file
1551   if (this->MocOrUicEnabled()) {
1552     // Write autogen target info files
1553     if (!this->SetupWriteAutogenInfo()) {
1554       return false;
1555     }
1556   }
1557
1558   // Write AUTORCC info files
1559   return !this->Rcc.Enabled || this->SetupWriteRccInfo();
1560 }
1561
1562 bool cmQtAutoGenInitializer::SetupWriteAutogenInfo()
1563 {
1564   // Utility lambdas
1565   auto MfDef = [this](std::string const& key) {
1566     return this->Makefile->GetSafeDefinition(key);
1567   };
1568
1569   // Filtered headers and sources
1570   std::set<std::string> moc_skip;
1571   std::set<std::string> uic_skip;
1572   std::vector<MUFile const*> headers;
1573   std::vector<MUFile const*> sources;
1574
1575   // Filter headers
1576   {
1577     headers.reserve(this->AutogenTarget.Headers.size());
1578     for (auto const& pair : this->AutogenTarget.Headers) {
1579       MUFile const* const muf = pair.second.get();
1580       if (muf->SkipMoc) {
1581         moc_skip.insert(muf->FullPath);
1582       }
1583       if (muf->SkipUic) {
1584         uic_skip.insert(muf->FullPath);
1585       }
1586       if (muf->Generated && !this->CMP0071Accept) {
1587         continue;
1588       }
1589       if (muf->MocIt || muf->UicIt) {
1590         headers.emplace_back(muf);
1591       }
1592     }
1593     std::sort(headers.begin(), headers.end(),
1594               [](MUFile const* a, MUFile const* b) {
1595                 return (a->FullPath < b->FullPath);
1596               });
1597   }
1598
1599   // Filter sources
1600   {
1601     sources.reserve(this->AutogenTarget.Sources.size());
1602     for (auto const& pair : this->AutogenTarget.Sources) {
1603       MUFile const* const muf = pair.second.get();
1604       if (muf->Generated && !this->CMP0071Accept) {
1605         continue;
1606       }
1607       if (muf->SkipMoc) {
1608         moc_skip.insert(muf->FullPath);
1609       }
1610       if (muf->SkipUic) {
1611         uic_skip.insert(muf->FullPath);
1612       }
1613       if (muf->MocIt || muf->UicIt) {
1614         sources.emplace_back(muf);
1615       }
1616     }
1617     std::sort(sources.begin(), sources.end(),
1618               [](MUFile const* a, MUFile const* b) {
1619                 return (a->FullPath < b->FullPath);
1620               });
1621   }
1622
1623   // Info writer
1624   InfoWriter info;
1625
1626   // General
1627   info.SetBool("MULTI_CONFIG", this->MultiConfig);
1628   info.SetUInt("PARALLEL", this->AutogenTarget.Parallel);
1629   info.SetUInt("VERBOSITY", this->Verbosity);
1630
1631   // Directories
1632   info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
1633   info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
1634   info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
1635   info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
1636   info.Set("BUILD_DIR", this->Dir.Build);
1637   info.SetConfig("INCLUDE_DIR", this->Dir.Include);
1638
1639   info.SetUInt("QT_VERSION_MAJOR", this->QtVersion.Major);
1640   info.SetUInt("QT_VERSION_MINOR", this->QtVersion.Minor);
1641   info.Set("QT_MOC_EXECUTABLE", this->Moc.Executable);
1642   info.Set("QT_UIC_EXECUTABLE", this->Uic.Executable);
1643
1644   info.Set("CMAKE_EXECUTABLE", cmSystemTools::GetCMakeCommand());
1645   info.SetConfig("SETTINGS_FILE", this->AutogenTarget.SettingsFile);
1646   info.SetConfig("PARSE_CACHE_FILE", this->AutogenTarget.ParseCacheFile);
1647   info.Set("DEP_FILE", this->AutogenTarget.DepFile);
1648   info.Set("DEP_FILE_RULE_NAME", this->AutogenTarget.DepFileRuleName);
1649   info.SetArray("CMAKE_LIST_FILES", this->Makefile->GetListFiles());
1650   info.SetArray("HEADER_EXTENSIONS",
1651                 this->Makefile->GetCMakeInstance()->GetHeaderExtensions());
1652   auto cfgArray = [this](std::vector<size_t> const& configs) -> Json::Value {
1653     Json::Value value;
1654     if (!configs.empty()) {
1655       value = Json::arrayValue;
1656       for (size_t ci : configs) {
1657         value.append(this->ConfigsList[ci]);
1658       }
1659     }
1660     return value;
1661   };
1662   info.SetArrayArray("HEADERS", headers,
1663                      [this, &cfgArray](Json::Value& jval, MUFile const* muf) {
1664                        jval.resize(4u);
1665                        jval[0u] = muf->FullPath;
1666                        jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm',
1667                                            muf->UicIt ? 'U' : 'u');
1668                        jval[2u] = this->GetMocBuildPath(*muf);
1669                        jval[3u] = cfgArray(muf->Configs);
1670                      });
1671   info.SetArrayArray(
1672     "SOURCES", sources, [&cfgArray](Json::Value& jval, MUFile const* muf) {
1673       jval.resize(3u);
1674       jval[0u] = muf->FullPath;
1675       jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm', muf->UicIt ? 'U' : 'u');
1676       jval[2u] = cfgArray(muf->Configs);
1677     });
1678
1679   // Write moc settings
1680   if (this->Moc.Enabled) {
1681     info.SetArray("MOC_SKIP", moc_skip);
1682     info.SetConfigArray("MOC_DEFINITIONS", this->Moc.Defines);
1683     info.SetConfigArray("MOC_INCLUDES", this->Moc.Includes);
1684     info.SetArray("MOC_OPTIONS", this->Moc.Options);
1685     info.SetBool("MOC_RELAXED_MODE", this->Moc.RelaxedMode);
1686     info.SetBool("MOC_PATH_PREFIX", this->Moc.PathPrefix);
1687     info.SetArray("MOC_MACRO_NAMES", this->Moc.MacroNames);
1688     info.SetArrayArray(
1689       "MOC_DEPEND_FILTERS", this->Moc.DependFilters,
1690       [](Json::Value& jval, std::pair<std::string, std::string> const& pair) {
1691         jval.resize(2u);
1692         jval[0u] = pair.first;
1693         jval[1u] = pair.second;
1694       });
1695     info.SetConfig("MOC_COMPILATION_FILE", this->Moc.CompilationFile);
1696     info.SetArray("MOC_PREDEFS_CMD", this->Moc.PredefsCmd);
1697     info.SetConfig("MOC_PREDEFS_FILE", this->Moc.PredefsFile);
1698   }
1699
1700   // Write uic settings
1701   if (this->Uic.Enabled) {
1702     // Add skipped .ui files
1703     uic_skip.insert(this->Uic.SkipUi.begin(), this->Uic.SkipUi.end());
1704
1705     info.SetArray("UIC_SKIP", uic_skip);
1706     info.SetArrayArray("UIC_UI_FILES", this->Uic.UiFilesWithOptions,
1707                        [](Json::Value& jval, UicT::UiFileT const& uiFile) {
1708                          jval.resize(2u);
1709                          jval[0u] = uiFile.first;
1710                          InfoWriter::MakeStringArray(jval[1u], uiFile.second);
1711                        });
1712     info.SetConfigArray("UIC_OPTIONS", this->Uic.Options);
1713     info.SetArray("UIC_SEARCH_PATHS", this->Uic.SearchPaths);
1714   }
1715
1716   info.Save(this->AutogenTarget.InfoFile);
1717
1718   return true;
1719 }
1720
1721 bool cmQtAutoGenInitializer::SetupWriteRccInfo()
1722 {
1723   for (Qrc const& qrc : this->Rcc.Qrcs) {
1724     // Utility lambdas
1725     auto MfDef = [this](std::string const& key) {
1726       return this->Makefile->GetSafeDefinition(key);
1727     };
1728
1729     InfoWriter info;
1730
1731     // General
1732     info.SetBool("MULTI_CONFIG", this->MultiConfig);
1733     info.SetUInt("VERBOSITY", this->Verbosity);
1734
1735     // Files
1736     info.Set("LOCK_FILE", qrc.LockFile);
1737     info.SetConfig("SETTINGS_FILE", qrc.SettingsFile);
1738
1739     // Directories
1740     info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
1741     info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
1742     info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
1743     info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
1744     info.Set("BUILD_DIR", this->Dir.Build);
1745     info.SetConfig("INCLUDE_DIR", this->Dir.Include);
1746
1747     // rcc executable
1748     info.Set("RCC_EXECUTABLE", this->Rcc.Executable);
1749     info.SetArray("RCC_LIST_OPTIONS",
1750                   this->Rcc.ExecutableFeatures->ListOptions);
1751
1752     // qrc file
1753     info.Set("SOURCE", qrc.QrcFile);
1754     info.Set("OUTPUT_CHECKSUM", qrc.QrcPathChecksum);
1755     info.Set("OUTPUT_NAME", cmSystemTools::GetFilenameName(qrc.OutputFile));
1756     info.SetArray("OPTIONS", qrc.Options);
1757     info.SetArray("INPUTS", qrc.Resources);
1758
1759     info.Save(qrc.InfoFile);
1760   }
1761
1762   return true;
1763 }
1764
1765 cmSourceFile* cmQtAutoGenInitializer::RegisterGeneratedSource(
1766   std::string const& filename)
1767 {
1768   cmSourceFile* gFile = this->Makefile->GetOrCreateSource(filename, true);
1769   gFile->MarkAsGenerated();
1770   gFile->SetProperty("SKIP_AUTOGEN", "1");
1771   return gFile;
1772 }
1773
1774 cmSourceFile* cmQtAutoGenInitializer::AddGeneratedSource(
1775   std::string const& filename, GenVarsT const& genVars, bool prepend)
1776 {
1777   // Register source at makefile
1778   cmSourceFile* gFile = this->RegisterGeneratedSource(filename);
1779   // Add source file to target
1780   this->GenTarget->AddSource(filename, prepend);
1781
1782   // Add source file to source group
1783   this->AddToSourceGroup(filename, genVars.GenNameUpper);
1784
1785   return gFile;
1786 }
1787
1788 void cmQtAutoGenInitializer::AddGeneratedSource(ConfigString const& filename,
1789                                                 GenVarsT const& genVars,
1790                                                 bool prepend)
1791 {
1792   // XXX(xcode-per-cfg-src): Drop the Xcode-specific part of the condition
1793   // when the Xcode generator supports per-config sources.
1794   if (!this->MultiConfig || this->GlobalGen->IsXcode()) {
1795     this->AddGeneratedSource(filename.Default, genVars, prepend);
1796     return;
1797   }
1798   for (auto const& cfg : this->ConfigsList) {
1799     std::string const& filenameCfg = filename.Config.at(cfg);
1800     // Register source at makefile
1801     this->RegisterGeneratedSource(filenameCfg);
1802     // Add source file to target for this configuration.
1803     this->GenTarget->AddSource(
1804       cmStrCat("$<$<CONFIG:"_s, cfg, ">:"_s, filenameCfg, ">"_s), prepend);
1805     // Add source file to source group
1806     this->AddToSourceGroup(filenameCfg, genVars.GenNameUpper);
1807   }
1808 }
1809
1810 void cmQtAutoGenInitializer::AddToSourceGroup(std::string const& fileName,
1811                                               cm::string_view genNameUpper)
1812 {
1813   cmSourceGroup* sourceGroup = nullptr;
1814   // Acquire source group
1815   {
1816     std::string property;
1817     std::string groupName;
1818     {
1819       // Prefer generator specific source group name
1820       std::initializer_list<std::string> const props{
1821         cmStrCat(genNameUpper, "_SOURCE_GROUP"), "AUTOGEN_SOURCE_GROUP"
1822       };
1823       for (std::string const& prop : props) {
1824         cmValue propName = this->Makefile->GetState()->GetGlobalProperty(prop);
1825         if (cmNonempty(propName)) {
1826           groupName = *propName;
1827           property = prop;
1828           break;
1829         }
1830       }
1831     }
1832     // Generate a source group on demand
1833     if (!groupName.empty()) {
1834       sourceGroup = this->Makefile->GetOrCreateSourceGroup(groupName);
1835       if (!sourceGroup) {
1836         cmSystemTools::Error(
1837           cmStrCat(genNameUpper, " error in ", property,
1838                    ": Could not find or create the source group ",
1839                    cmQtAutoGen::Quoted(groupName)));
1840       }
1841     }
1842   }
1843   if (sourceGroup) {
1844     sourceGroup->AddGroupFile(fileName);
1845   }
1846 }
1847
1848 void cmQtAutoGenInitializer::AddCleanFile(std::string const& fileName)
1849 {
1850   this->GenTarget->Target->AppendProperty("ADDITIONAL_CLEAN_FILES", fileName,
1851                                           false);
1852 }
1853
1854 void cmQtAutoGenInitializer::ConfigFileNames(ConfigString& configString,
1855                                              cm::string_view prefix,
1856                                              cm::string_view suffix)
1857 {
1858   configString.Default = cmStrCat(prefix, suffix);
1859   if (this->MultiConfig) {
1860     for (auto const& cfg : this->ConfigsList) {
1861       configString.Config[cfg] = cmStrCat(prefix, '_', cfg, suffix);
1862     }
1863   }
1864 }
1865
1866 void cmQtAutoGenInitializer::ConfigFileNamesAndGenex(
1867   ConfigString& configString, std::string& genex, cm::string_view const prefix,
1868   cm::string_view const suffix)
1869 {
1870   this->ConfigFileNames(configString, prefix, suffix);
1871   if (this->MultiConfig) {
1872     genex = cmStrCat(prefix, "_$<CONFIG>"_s, suffix);
1873   } else {
1874     genex = configString.Default;
1875   }
1876 }
1877
1878 void cmQtAutoGenInitializer::ConfigFileClean(ConfigString& configString)
1879 {
1880   this->AddCleanFile(configString.Default);
1881   if (this->MultiConfig) {
1882     for (auto const& pair : configString.Config) {
1883       this->AddCleanFile(pair.second);
1884     }
1885   }
1886 }
1887
1888 static cmQtAutoGen::IntegerVersion parseMocVersion(std::string str)
1889 {
1890   cmQtAutoGen::IntegerVersion result;
1891
1892   static const std::string prelude = "moc ";
1893   size_t pos = str.find(prelude);
1894   if (pos == std::string::npos) {
1895     return result;
1896   }
1897
1898   str.erase(0, prelude.size() + pos);
1899   std::istringstream iss(str);
1900   std::string major;
1901   std::string minor;
1902   if (!std::getline(iss, major, '.') || !std::getline(iss, minor, '.')) {
1903     return result;
1904   }
1905
1906   result.Major = static_cast<unsigned int>(std::stoi(major));
1907   result.Minor = static_cast<unsigned int>(std::stoi(minor));
1908   return result;
1909 }
1910
1911 static cmQtAutoGen::IntegerVersion GetMocVersion(
1912   const std::string& mocExecutablePath)
1913 {
1914   std::string capturedStdOut;
1915   int exitCode;
1916   if (!cmSystemTools::RunSingleCommand({ mocExecutablePath, "--version" },
1917                                        &capturedStdOut, nullptr, &exitCode,
1918                                        nullptr, cmSystemTools::OUTPUT_NONE)) {
1919     return {};
1920   }
1921
1922   if (exitCode != 0) {
1923     return {};
1924   }
1925
1926   return parseMocVersion(capturedStdOut);
1927 }
1928
1929 static std::string FindMocExecutableFromMocTarget(cmMakefile* makefile,
1930                                                   unsigned int qtMajorVersion)
1931 {
1932   std::string result;
1933   const std::string mocTargetName =
1934     "Qt" + std::to_string(qtMajorVersion) + "::moc";
1935   cmTarget* mocTarget = makefile->FindTargetToUse(mocTargetName);
1936   if (mocTarget) {
1937     result = mocTarget->GetSafeProperty("IMPORTED_LOCATION");
1938   }
1939   return result;
1940 }
1941
1942 std::pair<cmQtAutoGen::IntegerVersion, unsigned int>
1943 cmQtAutoGenInitializer::GetQtVersion(cmGeneratorTarget const* target,
1944                                      std::string mocExecutable)
1945 {
1946   // Converts a char ptr to an unsigned int value
1947   auto toUInt = [](const char* const input) -> unsigned int {
1948     unsigned long tmp = 0;
1949     if (input && cmStrToULong(input, &tmp)) {
1950       return static_cast<unsigned int>(tmp);
1951     }
1952     return 0u;
1953   };
1954   auto toUInt2 = [](cmValue input) -> unsigned int {
1955     unsigned long tmp = 0;
1956     if (input && cmStrToULong(*input, &tmp)) {
1957       return static_cast<unsigned int>(tmp);
1958     }
1959     return 0u;
1960   };
1961
1962   // Initialize return value to a default
1963   std::pair<IntegerVersion, unsigned int> res(
1964     IntegerVersion(),
1965     toUInt(target->GetLinkInterfaceDependentStringProperty("QT_MAJOR_VERSION",
1966                                                            "")));
1967
1968   // Acquire known Qt versions
1969   std::vector<cmQtAutoGen::IntegerVersion> knownQtVersions;
1970   {
1971     // Qt version variable prefixes
1972     static std::initializer_list<
1973       std::pair<cm::string_view, cm::string_view>> const keys{
1974       { "Qt6Core_VERSION_MAJOR", "Qt6Core_VERSION_MINOR" },
1975       { "Qt5Core_VERSION_MAJOR", "Qt5Core_VERSION_MINOR" },
1976       { "QT_VERSION_MAJOR", "QT_VERSION_MINOR" },
1977     };
1978
1979     knownQtVersions.reserve(keys.size() * 2);
1980
1981     // Adds a version to the result (nullptr safe)
1982     auto addVersion = [&knownQtVersions, &toUInt2](cmValue major,
1983                                                    cmValue minor) {
1984       cmQtAutoGen::IntegerVersion ver(toUInt2(major), toUInt2(minor));
1985       if (ver.Major != 0) {
1986         knownQtVersions.emplace_back(ver);
1987       }
1988     };
1989
1990     // Read versions from variables
1991     for (auto const& keyPair : keys) {
1992       addVersion(target->Makefile->GetDefinition(std::string(keyPair.first)),
1993                  target->Makefile->GetDefinition(std::string(keyPair.second)));
1994     }
1995
1996     // Read versions from directory properties
1997     for (auto const& keyPair : keys) {
1998       addVersion(target->Makefile->GetProperty(std::string(keyPair.first)),
1999                  target->Makefile->GetProperty(std::string(keyPair.second)));
2000     }
2001   }
2002
2003   // Evaluate known Qt versions
2004   if (!knownQtVersions.empty()) {
2005     if (res.second == 0) {
2006       // No specific version was requested by the target:
2007       // Use highest known Qt version.
2008       res.first = knownQtVersions.at(0);
2009     } else {
2010       // Pick a version from the known versions:
2011       for (auto it : knownQtVersions) {
2012         if (it.Major == res.second) {
2013           res.first = it;
2014           break;
2015         }
2016       }
2017     }
2018   }
2019
2020   if (res.first.Major == 0) {
2021     // We could not get the version number from variables or directory
2022     // properties. This might happen if the find_package call for Qt is wrapped
2023     // in a function. Try to find the moc executable path from the available
2024     // targets and call "moc --version" to get the Qt version.
2025     if (mocExecutable.empty()) {
2026       mocExecutable =
2027         FindMocExecutableFromMocTarget(target->Makefile, res.second);
2028     }
2029     if (!mocExecutable.empty()) {
2030       res.first = GetMocVersion(mocExecutable);
2031     }
2032   }
2033
2034   return res;
2035 }
2036
2037 std::string cmQtAutoGenInitializer::GetMocBuildPath(MUFile const& muf)
2038 {
2039   std::string res;
2040   if (!muf.MocIt) {
2041     return res;
2042   }
2043
2044   std::string basePath =
2045     cmStrCat(this->PathCheckSum.getPart(muf.FullPath), "/moc_",
2046              FileNameWithoutLastExtension(muf.FullPath));
2047
2048   res = cmStrCat(basePath, ".cpp");
2049   if (this->Moc.EmittedBuildPaths.emplace(res).second) {
2050     return res;
2051   }
2052
2053   // File name already emitted.
2054   // Try appending the header suffix to the base path.
2055   basePath = cmStrCat(basePath, '_', muf.SF->GetExtension());
2056   res = cmStrCat(basePath, ".cpp");
2057   if (this->Moc.EmittedBuildPaths.emplace(res).second) {
2058     return res;
2059   }
2060
2061   // File name with header extension already emitted.
2062   // Try adding a number to the base path.
2063   constexpr std::size_t number_begin = 2;
2064   constexpr std::size_t number_end = 256;
2065   for (std::size_t ii = number_begin; ii != number_end; ++ii) {
2066     res = cmStrCat(basePath, '_', ii, ".cpp");
2067     if (this->Moc.EmittedBuildPaths.emplace(res).second) {
2068       return res;
2069     }
2070   }
2071
2072   // Output file name conflict (unlikely, but still...)
2073   cmSystemTools::Error(
2074     cmStrCat("moc output file name conflict for ", muf.FullPath));
2075
2076   return res;
2077 }
2078
2079 bool cmQtAutoGenInitializer::GetQtExecutable(GenVarsT& genVars,
2080                                              const std::string& executable,
2081                                              bool ignoreMissingTarget) const
2082 {
2083   auto print_err = [this, &genVars](std::string const& err) {
2084     cmSystemTools::Error(cmStrCat(genVars.GenNameUpper, " for target ",
2085                                   this->GenTarget->GetName(), ": ", err));
2086   };
2087
2088   // Custom executable
2089   {
2090     std::string const prop = cmStrCat(genVars.GenNameUpper, "_EXECUTABLE");
2091     std::string const& val = this->GenTarget->Target->GetSafeProperty(prop);
2092     if (!val.empty()) {
2093       // Evaluate generator expression
2094       {
2095         cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
2096         cmGeneratorExpression ge(lfbt);
2097         std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(val);
2098         genVars.Executable = cge->Evaluate(this->LocalGen, "");
2099       }
2100       if (genVars.Executable.empty() && !ignoreMissingTarget) {
2101         print_err(prop + " evaluates to an empty value");
2102         return false;
2103       }
2104
2105       // Create empty compiler features.
2106       genVars.ExecutableFeatures =
2107         std::make_shared<cmQtAutoGen::CompilerFeatures>();
2108       return true;
2109     }
2110   }
2111
2112   // Find executable target
2113   {
2114     // Find executable target name
2115     cm::string_view prefix;
2116     if (this->QtVersion.Major == 4) {
2117       prefix = "Qt4::";
2118     } else if (this->QtVersion.Major == 5) {
2119       prefix = "Qt5::";
2120     } else if (this->QtVersion.Major == 6) {
2121       prefix = "Qt6::";
2122     }
2123     std::string const targetName = cmStrCat(prefix, executable);
2124
2125     // Find target
2126     cmGeneratorTarget* genTarget =
2127       this->LocalGen->FindGeneratorTargetToUse(targetName);
2128     if (genTarget) {
2129       genVars.ExecutableTargetName = targetName;
2130       genVars.ExecutableTarget = genTarget;
2131       if (genTarget->IsImported()) {
2132         genVars.Executable = genTarget->ImportedGetLocation("");
2133       } else {
2134         genVars.Executable = genTarget->GetLocation("");
2135       }
2136     } else {
2137       if (ignoreMissingTarget) {
2138         // Create empty compiler features.
2139         genVars.ExecutableFeatures =
2140           std::make_shared<cmQtAutoGen::CompilerFeatures>();
2141         return true;
2142       }
2143       print_err(cmStrCat("Could not find ", executable, " executable target ",
2144                          targetName));
2145       return false;
2146     }
2147   }
2148
2149   // Get executable features
2150   {
2151     std::string err;
2152     genVars.ExecutableFeatures = this->GlobalInitializer->GetCompilerFeatures(
2153       executable, genVars.Executable, err);
2154     if (!genVars.ExecutableFeatures) {
2155       print_err(err);
2156       return false;
2157     }
2158   }
2159
2160   return true;
2161 }