cmQtAutoGenInitializer.cxx 63 KB

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