cmQtAutoGenInitializer.cxx 66 KB

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