cmQtAutoGenInitializer.cxx 67 KB

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