cmQtAutoGenInitializer.cxx 72 KB

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