cmQtAutoGenInitializer.cxx 82 KB

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