cmQtAutoGenInitializer.cxx 85 KB

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