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