cmQtAutoGenInitializer.cxx 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512
  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 != nullptr) {
  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. for (const auto& file : this->Uic.UiHeaders) {
  1239. this->AddGeneratedSource(file.first, this->Uic);
  1240. autogenByproducts.push_back(file.second);
  1241. }
  1242. }
  1243. // Compose target comment
  1244. std::string autogenComment;
  1245. {
  1246. std::string tools;
  1247. if (this->Moc.Enabled) {
  1248. tools += "MOC";
  1249. }
  1250. if (this->Uic.Enabled) {
  1251. if (!tools.empty()) {
  1252. tools += " and ";
  1253. }
  1254. tools += "UIC";
  1255. }
  1256. autogenComment = cmStrCat("Automatic ", tools, " for target ",
  1257. this->GenTarget->GetName());
  1258. }
  1259. // Compose command lines
  1260. // FIXME: Take advantage of our per-config mocs_compilation_$<CONFIG>.cpp
  1261. // instead of fiddling with the include directories
  1262. bool constexpr stdPipesUTF8 = true;
  1263. cmCustomCommandLines commandLines;
  1264. AddCMakeProcessToCommandLines(this->AutogenTarget.InfoFile, "cmake_autogen",
  1265. commandLines);
  1266. // Use PRE_BUILD on demand
  1267. bool usePRE_BUILD = false;
  1268. if (this->GlobalGen->GetName().find("Visual Studio") != std::string::npos) {
  1269. // Under VS use a PRE_BUILD event instead of a separate target to
  1270. // reduce the number of targets loaded into the IDE.
  1271. // This also works around a VS 11 bug that may skip updating the target:
  1272. // https://connect.microsoft.com/VisualStudio/feedback/details/769495
  1273. usePRE_BUILD = true;
  1274. }
  1275. // Disable PRE_BUILD in some cases
  1276. if (usePRE_BUILD) {
  1277. // Cannot use PRE_BUILD with file depends
  1278. if (!this->AutogenTarget.DependFiles.empty()) {
  1279. usePRE_BUILD = false;
  1280. }
  1281. // Cannot use PRE_BUILD when a global autogen target is in place
  1282. if (this->AutogenTarget.GlobalTarget) {
  1283. usePRE_BUILD = false;
  1284. }
  1285. }
  1286. // Create the autogen target/command
  1287. if (usePRE_BUILD) {
  1288. // Add additional autogen target dependencies to origin target
  1289. for (cmTarget const* depTarget : this->AutogenTarget.DependTargets) {
  1290. this->GenTarget->Target->AddUtility(depTarget->GetName(), false,
  1291. this->Makefile);
  1292. }
  1293. if (!this->Uic.UiFilesNoOptions.empty() ||
  1294. !this->Uic.UiFilesWithOptions.empty()) {
  1295. // Add a generated timestamp file
  1296. ConfigString timestampFile;
  1297. std::string timestampFileGenex;
  1298. ConfigFileNamesAndGenex(timestampFile, timestampFileGenex,
  1299. cmStrCat(this->Dir.Build, "/autouic"_s),
  1300. ".stamp"_s);
  1301. this->AddGeneratedSource(timestampFile, this->Uic);
  1302. // Add a step in the pre-build command to touch the timestamp file
  1303. commandLines.push_back(
  1304. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E", "touch",
  1305. timestampFileGenex }));
  1306. // UIC needs to be re-run if any of the known UI files change or the
  1307. // executable itself has been updated
  1308. auto uicDependencies = this->Uic.UiFilesNoOptions;
  1309. for (auto const& uiFile : this->Uic.UiFilesWithOptions) {
  1310. uicDependencies.push_back(uiFile.first);
  1311. }
  1312. AddAutogenExecutableToDependencies(this->Uic, uicDependencies);
  1313. // Add a rule file to cause the target to build if a dependency has
  1314. // changed, which will trigger the pre-build command to run autogen
  1315. auto cc = cm::make_unique<cmCustomCommand>();
  1316. cc->SetOutputs(timestampFileGenex);
  1317. cc->SetDepends(uicDependencies);
  1318. cc->SetComment("");
  1319. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1320. cc->SetEscapeOldStyle(false);
  1321. cc->SetStdPipesUTF8(stdPipesUTF8);
  1322. this->LocalGen->AddCustomCommandToOutput(std::move(cc));
  1323. }
  1324. // Add the pre-build command directly to bypass the OBJECT_LIBRARY
  1325. // rejection in cmMakefile::AddCustomCommandToTarget because we know
  1326. // PRE_BUILD will work for an OBJECT_LIBRARY in this specific case.
  1327. //
  1328. // PRE_BUILD does not support file dependencies!
  1329. cmCustomCommand cc;
  1330. cc.SetByproducts(autogenByproducts);
  1331. cc.SetCommandLines(commandLines);
  1332. cc.SetComment(autogenComment.c_str());
  1333. cc.SetBacktrace(this->Makefile->GetBacktrace());
  1334. cc.SetWorkingDirectory(this->Dir.Work.c_str());
  1335. cc.SetStdPipesUTF8(stdPipesUTF8);
  1336. cc.SetEscapeOldStyle(false);
  1337. cc.SetEscapeAllowMakeVars(true);
  1338. this->GenTarget->Target->AddPreBuildCommand(std::move(cc));
  1339. } else {
  1340. // Add link library target dependencies to the autogen target
  1341. // dependencies
  1342. if (this->AutogenTarget.DependOrigin) {
  1343. // add_dependencies/addUtility do not support generator expressions.
  1344. // We depend only on the libraries found in all configs therefore.
  1345. std::map<cmGeneratorTarget const*, std::size_t> commonTargets;
  1346. for (std::string const& config : this->ConfigsList) {
  1347. cmLinkImplementationLibraries const* libs =
  1348. this->GenTarget->GetLinkImplementationLibraries(
  1349. config, cmGeneratorTarget::UseTo::Link);
  1350. if (libs) {
  1351. for (cmLinkItem const& item : libs->Libraries) {
  1352. cmGeneratorTarget const* libTarget = item.Target;
  1353. if (libTarget &&
  1354. !StaticLibraryCycle(this->GenTarget, libTarget, config)) {
  1355. // Increment target config count
  1356. commonTargets[libTarget]++;
  1357. }
  1358. }
  1359. }
  1360. }
  1361. for (auto const& item : commonTargets) {
  1362. if (item.second == this->ConfigsList.size()) {
  1363. this->AutogenTarget.DependTargets.insert(item.first->Target);
  1364. }
  1365. }
  1366. }
  1367. cmTarget* timestampTarget = nullptr;
  1368. std::vector<std::string> dependencies(
  1369. this->AutogenTarget.DependFiles.begin(),
  1370. this->AutogenTarget.DependFiles.end());
  1371. if (useDepfile) {
  1372. // Create a custom command that generates a timestamp file and
  1373. // has a depfile assigned. The depfile is created by JobDepFilesMergeT.
  1374. //
  1375. // Also create an additional '_autogen_timestamp_deps' that the custom
  1376. // command will depend on. It will have no sources or commands to
  1377. // execute, but it will have dependencies that would originally be
  1378. // assigned to the pre-Qt 5.15 'autogen' target. These dependencies will
  1379. // serve as a list of order-only dependencies for the custom command,
  1380. // without forcing the custom command to re-execute.
  1381. //
  1382. // The dependency tree would then look like
  1383. // '_autogen_timestamp_deps (order-only)' <- '/timestamp' file <-
  1384. // '_autogen' target.
  1385. const auto timestampTargetName =
  1386. cmStrCat(this->GenTarget->GetName(), "_autogen_timestamp_deps");
  1387. auto cc = cm::make_unique<cmCustomCommand>();
  1388. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1389. cc->SetDepends(dependencies);
  1390. cc->SetEscapeOldStyle(false);
  1391. timestampTarget = this->LocalGen->AddUtilityCommand(timestampTargetName,
  1392. true, std::move(cc));
  1393. this->LocalGen->AddGeneratorTarget(
  1394. cm::make_unique<cmGeneratorTarget>(timestampTarget, this->LocalGen));
  1395. // Set FOLDER property on the timestamp target, so it appears in the
  1396. // appropriate folder in an IDE or in the file api.
  1397. if (!this->TargetsFolder.empty()) {
  1398. timestampTarget->SetProperty("FOLDER", this->TargetsFolder);
  1399. }
  1400. // Make '/timestamp' file depend on '_autogen_timestamp_deps' and on the
  1401. // moc and uic executables (whichever are enabled).
  1402. dependencies.clear();
  1403. dependencies.push_back(timestampTargetName);
  1404. AddAutogenExecutableToDependencies(this->Moc, dependencies);
  1405. AddAutogenExecutableToDependencies(this->Uic, dependencies);
  1406. std::string outputFile;
  1407. std::string depFile;
  1408. // Create the custom command that outputs the timestamp file.
  1409. if (this->MultiConfig && this->UseBetterGraph) {
  1410. // create timestamp file with $<CONFIG> in the name so that
  1411. // every cmake_autogen target has its own timestamp file
  1412. std::string const configView = "$<CONFIG>";
  1413. std::string const timestampFileWithoutConfig = "timestamp_";
  1414. std::string const depFileWithoutConfig =
  1415. cmStrCat(this->Dir.Build, "/deps_");
  1416. std::string const timestampFileName =
  1417. timestampFileWithoutConfig + configView;
  1418. outputFile = cmStrCat(this->Dir.Build, "/", timestampFileName);
  1419. auto const depFileWithConfig =
  1420. cmStrCat(depFileWithoutConfig, configView);
  1421. depFile = depFileWithConfig;
  1422. commandLines.push_back(cmMakeCommandLine(
  1423. { cmSystemTools::GetCMakeCommand(), "-E", "touch", outputFile }));
  1424. ConfigString outputFileWithConfig;
  1425. for (std::string const& config : this->ConfigsList) {
  1426. auto tempTimestampFileName = timestampFileWithoutConfig + config;
  1427. auto tempDepFile = depFileWithoutConfig + config;
  1428. outputFileWithConfig.Config[config] = tempTimestampFileName;
  1429. this->AutogenTarget.DepFileRuleName.Config[config] =
  1430. cmStrCat(this->Dir.RelativeBuild, "/", tempTimestampFileName);
  1431. this->AutogenTarget.DepFile.Config[config] = tempDepFile;
  1432. }
  1433. this->AddGeneratedSource(outputFileWithConfig, this->Moc);
  1434. } else {
  1435. cm::string_view const timestampFileName = "timestamp";
  1436. outputFile = cmStrCat(this->Dir.Build, "/", timestampFileName);
  1437. this->AutogenTarget.DepFile.Default =
  1438. cmStrCat(this->Dir.Build, "/deps");
  1439. depFile = this->AutogenTarget.DepFile.Default;
  1440. this->AutogenTarget.DepFileRuleName.Default =
  1441. cmStrCat(this->Dir.RelativeBuild, "/", timestampFileName);
  1442. commandLines.push_back(cmMakeCommandLine(
  1443. { cmSystemTools::GetCMakeCommand(), "-E", "touch", outputFile }));
  1444. this->AddGeneratedSource(outputFile, this->Moc);
  1445. }
  1446. cc = cm::make_unique<cmCustomCommand>();
  1447. cc->SetOutputs(outputFile);
  1448. cc->SetByproducts(timestampByproducts);
  1449. cc->SetDepends(dependencies);
  1450. cc->SetCommandLines(commandLines);
  1451. cc->SetComment(autogenComment.c_str());
  1452. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1453. cc->SetEscapeOldStyle(false);
  1454. cc->SetDepfile(depFile);
  1455. cc->SetStdPipesUTF8(stdPipesUTF8);
  1456. this->LocalGen->AddCustomCommandToOutput(std::move(cc));
  1457. dependencies.clear();
  1458. dependencies.emplace_back(std::move(outputFile));
  1459. commandLines.clear();
  1460. autogenComment.clear();
  1461. }
  1462. // Create autogen target
  1463. auto cc = cm::make_unique<cmCustomCommand>();
  1464. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1465. cc->SetByproducts(autogenByproducts);
  1466. cc->SetDepends(dependencies);
  1467. cc->SetCommandLines(commandLines);
  1468. cc->SetEscapeOldStyle(false);
  1469. cc->SetComment(autogenComment.c_str());
  1470. cmTarget* autogenTarget = this->LocalGen->AddUtilityCommand(
  1471. this->AutogenTarget.Name, true, std::move(cc));
  1472. // Create autogen generator target
  1473. this->LocalGen->AddGeneratorTarget(
  1474. cm::make_unique<cmGeneratorTarget>(autogenTarget, this->LocalGen));
  1475. // Order the autogen target(s) just before the original target.
  1476. cmTarget* orderTarget = timestampTarget ? timestampTarget : autogenTarget;
  1477. // Forward origin utilities to autogen target
  1478. if (this->AutogenTarget.DependOrigin) {
  1479. for (BT<std::pair<std::string, bool>> const& depName :
  1480. this->GenTarget->GetUtilities()) {
  1481. orderTarget->AddUtility(depName.Value.first, false, this->Makefile);
  1482. }
  1483. }
  1484. // Add additional autogen target dependencies to autogen target
  1485. for (cmTarget const* depTarget : this->AutogenTarget.DependTargets) {
  1486. orderTarget->AddUtility(depTarget->GetName(), false, this->Makefile);
  1487. }
  1488. // Set FOLDER property in autogen target
  1489. if (!this->TargetsFolder.empty()) {
  1490. autogenTarget->SetProperty("FOLDER", this->TargetsFolder);
  1491. }
  1492. // Add autogen target to the origin target dependencies
  1493. this->GenTarget->Target->AddUtility(this->AutogenTarget.Name, false,
  1494. this->Makefile);
  1495. // Add autogen target to the global autogen target dependencies
  1496. if (this->AutogenTarget.GlobalTarget) {
  1497. this->GlobalInitializer->AddToGlobalAutoGen(this->LocalGen,
  1498. this->AutogenTarget.Name);
  1499. }
  1500. }
  1501. return true;
  1502. }
  1503. void cmQtAutoGenInitializer::AddCMakeProcessToCommandLines(
  1504. std::string const& infoFile, std::string const& processName,
  1505. cmCustomCommandLines& commandLines)
  1506. {
  1507. if (this->CrossConfig && this->UseBetterGraph) {
  1508. commandLines.push_back(cmMakeCommandLine(
  1509. { cmSystemTools::GetCMakeCommand(), "-E", processName, infoFile,
  1510. "$<CONFIG>", "$<COMMAND_CONFIG:$<CONFIG>>" }));
  1511. } else if ((this->MultiConfig && this->GlobalGen->IsXcode()) ||
  1512. this->CrossConfig) {
  1513. for (std::string const& config : this->ConfigsList) {
  1514. commandLines.push_back(
  1515. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
  1516. processName, infoFile, config }));
  1517. }
  1518. } else {
  1519. std::string autoInfoFileConfig;
  1520. if (this->MultiConfig) {
  1521. autoInfoFileConfig = "$<CONFIG>";
  1522. } else {
  1523. std::vector<std::string> configs;
  1524. this->GlobalGen->GetQtAutoGenConfigs(configs);
  1525. autoInfoFileConfig = configs[0];
  1526. }
  1527. commandLines.push_back(
  1528. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E", processName,
  1529. infoFile, autoInfoFileConfig }));
  1530. }
  1531. }
  1532. bool cmQtAutoGenInitializer::InitRccTargets()
  1533. {
  1534. for (Qrc const& qrc : this->Rcc.Qrcs) {
  1535. // Register info file as generated by CMake
  1536. this->Makefile->AddCMakeOutputFile(qrc.InfoFile);
  1537. // Register file at target
  1538. {
  1539. cmSourceFile* sf = this->AddGeneratedSource(qrc.OutputFile, this->Rcc);
  1540. sf->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "On");
  1541. }
  1542. std::vector<std::string> ccOutput{ qrc.OutputFile };
  1543. // Add the .qrc and info file to the custom command dependencies
  1544. std::vector<std::string> ccDepends{ qrc.QrcFile, qrc.InfoFile };
  1545. cmCustomCommandLines commandLines;
  1546. AddCMakeProcessToCommandLines(qrc.InfoFile, "cmake_autorcc", commandLines);
  1547. std::string const ccComment =
  1548. cmStrCat("Automatic RCC for ",
  1549. FileProjectRelativePath(this->Makefile, qrc.QrcFile));
  1550. auto cc = cm::make_unique<cmCustomCommand>();
  1551. cc->SetWorkingDirectory(this->Dir.Work.c_str());
  1552. cc->SetCommandLines(commandLines);
  1553. cc->SetComment(ccComment.c_str());
  1554. cc->SetStdPipesUTF8(true);
  1555. if (qrc.Generated || this->Rcc.GlobalTarget) {
  1556. // Create custom rcc target
  1557. std::string ccName;
  1558. {
  1559. ccName = cmStrCat(this->GenTarget->GetName(), "_arcc_", qrc.QrcName);
  1560. if (!qrc.Unique) {
  1561. ccName += cmStrCat('_', qrc.QrcPathChecksum);
  1562. }
  1563. cc->SetByproducts(ccOutput);
  1564. cc->SetDepends(ccDepends);
  1565. cc->SetEscapeOldStyle(false);
  1566. cmTarget* autoRccTarget =
  1567. this->LocalGen->AddUtilityCommand(ccName, true, std::move(cc));
  1568. // Create autogen generator target
  1569. this->LocalGen->AddGeneratorTarget(
  1570. cm::make_unique<cmGeneratorTarget>(autoRccTarget, this->LocalGen));
  1571. // Set FOLDER property in autogen target
  1572. if (!this->TargetsFolder.empty()) {
  1573. autoRccTarget->SetProperty("FOLDER", this->TargetsFolder);
  1574. }
  1575. if (!this->Rcc.ExecutableTargetName.empty()) {
  1576. autoRccTarget->AddUtility(this->Rcc.ExecutableTargetName, false,
  1577. this->Makefile);
  1578. }
  1579. }
  1580. // Add autogen target to the origin target dependencies
  1581. this->GenTarget->Target->AddUtility(ccName, false, this->Makefile);
  1582. // Add autogen target to the global autogen target dependencies
  1583. if (this->Rcc.GlobalTarget) {
  1584. this->GlobalInitializer->AddToGlobalAutoRcc(this->LocalGen, ccName);
  1585. }
  1586. } else {
  1587. // Create custom rcc command
  1588. {
  1589. // Add the resource files to the dependencies
  1590. if (this->MultiConfig && this->UseBetterGraph) {
  1591. for (auto const& config : this->ConfigsList) {
  1592. // Add resource file to the custom command dependencies
  1593. auto resourceFilesWithConfig = cmStrCat(
  1594. "$<$<CONFIG:", config,
  1595. ">:", cmList{ qrc.Resources.Config.at(config) }.to_string(),
  1596. ">");
  1597. ccDepends.emplace_back(std::move(resourceFilesWithConfig));
  1598. }
  1599. } else {
  1600. for (std::string const& fileName : qrc.Resources.Default) {
  1601. // Add resource file to the custom command dependencies
  1602. ccDepends.push_back(fileName);
  1603. }
  1604. }
  1605. if (!this->Rcc.ExecutableTargetName.empty()) {
  1606. ccDepends.push_back(this->Rcc.ExecutableTargetName);
  1607. }
  1608. AddAutogenExecutableToDependencies(this->Rcc, ccDepends);
  1609. cc->SetOutputs(ccOutput);
  1610. cc->SetDepends(ccDepends);
  1611. this->LocalGen->AddCustomCommandToOutput(std::move(cc));
  1612. }
  1613. // Reconfigure when .qrc file changes
  1614. this->Makefile->AddCMakeDependFile(qrc.QrcFile);
  1615. }
  1616. }
  1617. return true;
  1618. }
  1619. bool cmQtAutoGenInitializer::SetupCustomTargets()
  1620. {
  1621. // Create info directory on demand
  1622. if (!cmSystemTools::MakeDirectory(this->Dir.Info)) {
  1623. cmSystemTools::Error(cmStrCat("AutoGen: Could not create directory: ",
  1624. Quoted(this->Dir.Info)));
  1625. return false;
  1626. }
  1627. // Generate autogen target info file
  1628. if (this->MocOrUicEnabled()) {
  1629. // Write autogen target info files
  1630. if (!this->SetupWriteAutogenInfo()) {
  1631. return false;
  1632. }
  1633. }
  1634. // Write AUTORCC info files
  1635. return !this->Rcc.Enabled || this->SetupWriteRccInfo();
  1636. }
  1637. bool cmQtAutoGenInitializer::SetupWriteAutogenInfo()
  1638. {
  1639. // Utility lambdas
  1640. auto MfDef = [this](std::string const& key) {
  1641. return this->Makefile->GetSafeDefinition(key);
  1642. };
  1643. // Filtered headers and sources
  1644. std::set<std::string> moc_skip;
  1645. std::set<std::string> uic_skip;
  1646. std::vector<MUFile const*> headers;
  1647. std::vector<MUFile const*> sources;
  1648. // Filter headers
  1649. {
  1650. headers.reserve(this->AutogenTarget.Headers.size());
  1651. for (auto const& pair : this->AutogenTarget.Headers) {
  1652. MUFile const* const muf = pair.second.get();
  1653. if (muf->SkipMoc) {
  1654. moc_skip.insert(muf->FullPath);
  1655. }
  1656. if (muf->SkipUic) {
  1657. uic_skip.insert(muf->FullPath);
  1658. }
  1659. if (muf->Generated && !this->CMP0071Accept) {
  1660. continue;
  1661. }
  1662. if (muf->MocIt || muf->UicIt) {
  1663. headers.emplace_back(muf);
  1664. }
  1665. }
  1666. std::sort(headers.begin(), headers.end(),
  1667. [](MUFile const* a, MUFile const* b) {
  1668. return (a->FullPath < b->FullPath);
  1669. });
  1670. }
  1671. // Filter sources
  1672. {
  1673. sources.reserve(this->AutogenTarget.Sources.size());
  1674. for (auto const& pair : this->AutogenTarget.Sources) {
  1675. MUFile const* const muf = pair.second.get();
  1676. if (muf->Generated && !this->CMP0071Accept) {
  1677. continue;
  1678. }
  1679. if (muf->SkipMoc) {
  1680. moc_skip.insert(muf->FullPath);
  1681. }
  1682. if (muf->SkipUic) {
  1683. uic_skip.insert(muf->FullPath);
  1684. }
  1685. if (muf->MocIt || muf->UicIt) {
  1686. sources.emplace_back(muf);
  1687. }
  1688. }
  1689. std::sort(sources.begin(), sources.end(),
  1690. [](MUFile const* a, MUFile const* b) {
  1691. return (a->FullPath < b->FullPath);
  1692. });
  1693. }
  1694. // Info writer
  1695. InfoWriter info;
  1696. // General
  1697. info.SetBool("MULTI_CONFIG", this->MultiConfig);
  1698. info.SetBool("CROSS_CONFIG", this->CrossConfig);
  1699. info.SetBool("USE_BETTER_GRAPH", this->UseBetterGraph);
  1700. info.SetUInt("PARALLEL", this->AutogenTarget.Parallel);
  1701. #ifdef _WIN32
  1702. info.SetUInt("AUTOGEN_COMMAND_LINE_LENGTH_MAX",
  1703. this->AutogenTarget.MaxCommandLineLength);
  1704. #endif
  1705. info.SetUInt("VERBOSITY", this->Verbosity);
  1706. // Directories
  1707. info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
  1708. info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
  1709. info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
  1710. info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
  1711. info.Set("BUILD_DIR", this->Dir.Build);
  1712. info.SetConfig("INCLUDE_DIR", this->Dir.Include);
  1713. info.SetUInt("QT_VERSION_MAJOR", this->QtVersion.Major);
  1714. info.SetUInt("QT_VERSION_MINOR", this->QtVersion.Minor);
  1715. info.SetConfig("QT_MOC_EXECUTABLE", this->Moc.Executable);
  1716. info.SetConfig("QT_UIC_EXECUTABLE", this->Uic.Executable);
  1717. info.Set("CMAKE_EXECUTABLE", cmSystemTools::GetCMakeCommand());
  1718. info.SetConfig("SETTINGS_FILE", this->AutogenTarget.SettingsFile);
  1719. info.SetConfig("PARSE_CACHE_FILE", this->AutogenTarget.ParseCacheFile);
  1720. info.SetConfig("DEP_FILE", this->AutogenTarget.DepFile);
  1721. info.SetConfig("DEP_FILE_RULE_NAME", this->AutogenTarget.DepFileRuleName);
  1722. info.SetArray("CMAKE_LIST_FILES", this->Makefile->GetListFiles());
  1723. info.SetArray("HEADER_EXTENSIONS",
  1724. this->Makefile->GetCMakeInstance()->GetHeaderExtensions());
  1725. auto cfgArray = [this](std::vector<size_t> const& configs) -> Json::Value {
  1726. Json::Value value;
  1727. if (!configs.empty()) {
  1728. value = Json::arrayValue;
  1729. for (size_t ci : configs) {
  1730. value.append(this->ConfigsList[ci]);
  1731. }
  1732. }
  1733. return value;
  1734. };
  1735. info.SetArrayArray("HEADERS", headers,
  1736. [this, &cfgArray](Json::Value& jval, MUFile const* muf) {
  1737. jval.resize(4u);
  1738. jval[0u] = muf->FullPath;
  1739. jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm',
  1740. muf->UicIt ? 'U' : 'u');
  1741. jval[2u] = this->GetMocBuildPath(*muf);
  1742. jval[3u] = cfgArray(muf->Configs);
  1743. });
  1744. info.SetArrayArray(
  1745. "SOURCES", sources, [&cfgArray](Json::Value& jval, MUFile const* muf) {
  1746. jval.resize(3u);
  1747. jval[0u] = muf->FullPath;
  1748. jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm', muf->UicIt ? 'U' : 'u');
  1749. jval[2u] = cfgArray(muf->Configs);
  1750. });
  1751. // Write moc settings
  1752. if (this->Moc.Enabled) {
  1753. info.SetArray("MOC_SKIP", moc_skip);
  1754. info.SetConfigArray("MOC_DEFINITIONS", this->Moc.Defines);
  1755. info.SetConfigArray("MOC_INCLUDES", this->Moc.Includes);
  1756. info.SetArray("MOC_OPTIONS", this->Moc.Options);
  1757. info.SetBool("MOC_RELAXED_MODE", this->Moc.RelaxedMode);
  1758. info.SetBool("MOC_PATH_PREFIX", this->Moc.PathPrefix);
  1759. EvaluatedTargetPropertyEntries InterfaceAutoMocMacroNamesEntries;
  1760. if (this->MultiConfig) {
  1761. for (auto const& cfg : this->ConfigsList) {
  1762. if (!cfg.empty()) {
  1763. cmGeneratorExpressionDAGChecker dagChecker(
  1764. this->GenTarget, "AUTOMOC_MACRO_NAMES", nullptr, nullptr,
  1765. this->LocalGen, cfg);
  1766. AddInterfaceEntries(this->GenTarget, cfg,
  1767. "INTERFACE_AUTOMOC_MACRO_NAMES", "CXX",
  1768. &dagChecker, InterfaceAutoMocMacroNamesEntries,
  1769. IncludeRuntimeInterface::Yes);
  1770. }
  1771. }
  1772. } else {
  1773. cmGeneratorExpressionDAGChecker dagChecker(
  1774. this->GenTarget, "AUTOMOC_MACRO_NAMES", nullptr, nullptr,
  1775. this->LocalGen, this->ConfigDefault);
  1776. AddInterfaceEntries(this->GenTarget, this->ConfigDefault,
  1777. "INTERFACE_AUTOMOC_MACRO_NAMES", "CXX", &dagChecker,
  1778. InterfaceAutoMocMacroNamesEntries,
  1779. IncludeRuntimeInterface::Yes);
  1780. }
  1781. for (auto const& entry : InterfaceAutoMocMacroNamesEntries.Entries) {
  1782. this->Moc.MacroNames.insert(this->Moc.MacroNames.end(),
  1783. entry.Values.begin(), entry.Values.end());
  1784. }
  1785. this->Moc.MacroNames.erase(cmRemoveDuplicates(this->Moc.MacroNames),
  1786. this->Moc.MacroNames.end());
  1787. info.SetArray("MOC_MACRO_NAMES", this->Moc.MacroNames);
  1788. info.SetArrayArray(
  1789. "MOC_DEPEND_FILTERS", this->Moc.DependFilters,
  1790. [](Json::Value& jval, std::pair<std::string, std::string> const& pair) {
  1791. jval.resize(2u);
  1792. jval[0u] = pair.first;
  1793. jval[1u] = pair.second;
  1794. });
  1795. info.SetConfig("MOC_COMPILATION_FILE", this->Moc.CompilationFile);
  1796. info.SetConfig("MOC_PREDEFS_FILE", this->Moc.PredefsFile);
  1797. cmStandardLevelResolver const resolver{ this->Makefile };
  1798. auto const CompileOptionFlag =
  1799. resolver.GetCompileOptionDef(this->GenTarget, "CXX", "");
  1800. auto const CompileOptionValue =
  1801. this->GenTarget->Makefile->GetSafeDefinition(CompileOptionFlag);
  1802. if (!CompileOptionValue.empty()) {
  1803. if (this->Moc.PredefsCmd.size() >= 3) {
  1804. this->Moc.PredefsCmd.insert(this->Moc.PredefsCmd.begin() + 1,
  1805. CompileOptionValue);
  1806. }
  1807. }
  1808. info.SetArray("MOC_PREDEFS_CMD", this->Moc.PredefsCmd);
  1809. }
  1810. // Write uic settings
  1811. if (this->Uic.Enabled) {
  1812. // Add skipped .ui files
  1813. uic_skip.insert(this->Uic.SkipUi.begin(), this->Uic.SkipUi.end());
  1814. info.SetArray("UIC_SKIP", uic_skip);
  1815. info.SetArrayArray("UIC_UI_FILES", this->Uic.UiFilesWithOptions,
  1816. [](Json::Value& jval, UicT::UiFileT const& uiFile) {
  1817. jval.resize(2u);
  1818. jval[0u] = uiFile.first;
  1819. InfoWriter::MakeStringArray(jval[1u], uiFile.second);
  1820. });
  1821. info.SetConfigArray("UIC_OPTIONS", this->Uic.Options);
  1822. info.SetArray("UIC_SEARCH_PATHS", this->Uic.SearchPaths);
  1823. }
  1824. info.Save(this->AutogenTarget.InfoFile);
  1825. return true;
  1826. }
  1827. bool cmQtAutoGenInitializer::SetupWriteRccInfo()
  1828. {
  1829. for (Qrc const& qrc : this->Rcc.Qrcs) {
  1830. // Utility lambdas
  1831. auto MfDef = [this](std::string const& key) {
  1832. return this->Makefile->GetSafeDefinition(key);
  1833. };
  1834. InfoWriter info;
  1835. // General
  1836. info.SetBool("MULTI_CONFIG", this->MultiConfig);
  1837. info.SetBool("CROSS_CONFIG", this->CrossConfig);
  1838. info.SetBool("USE_BETTER_GRAPH", this->UseBetterGraph);
  1839. info.SetUInt("VERBOSITY", this->Verbosity);
  1840. info.Set("GENERATOR", this->GlobalGen->GetName());
  1841. // Files
  1842. info.Set("LOCK_FILE", qrc.LockFile);
  1843. info.SetConfig("SETTINGS_FILE", qrc.SettingsFile);
  1844. // Directories
  1845. info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
  1846. info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
  1847. info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
  1848. info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
  1849. info.Set("BUILD_DIR", this->Dir.Build);
  1850. info.SetConfig("INCLUDE_DIR", this->Dir.Include);
  1851. // rcc executable
  1852. info.SetConfig("RCC_EXECUTABLE", this->Rcc.Executable);
  1853. info.SetConfigArray(
  1854. "RCC_LIST_OPTIONS",
  1855. generateListOptions(this->Rcc.ExecutableFeatures, this->MultiConfig));
  1856. // qrc file
  1857. info.Set("SOURCE", qrc.QrcFile);
  1858. info.Set("OUTPUT_CHECKSUM", qrc.QrcPathChecksum);
  1859. info.Set("OUTPUT_NAME", cmSystemTools::GetFilenameName(qrc.OutputFile));
  1860. info.SetArray("OPTIONS", qrc.Options);
  1861. info.SetConfigArray("INPUTS", qrc.Resources);
  1862. info.Save(qrc.InfoFile);
  1863. }
  1864. return true;
  1865. }
  1866. cmSourceFile* cmQtAutoGenInitializer::RegisterGeneratedSource(
  1867. std::string const& filename)
  1868. {
  1869. cmSourceFile* gFile = this->Makefile->GetOrCreateSource(filename, true);
  1870. gFile->MarkAsGenerated();
  1871. gFile->SetProperty("SKIP_AUTOGEN", "1");
  1872. gFile->SetProperty("SKIP_LINTING", "ON");
  1873. gFile->SetProperty("CXX_SCAN_FOR_MODULES", "0");
  1874. return gFile;
  1875. }
  1876. cmSourceFile* cmQtAutoGenInitializer::AddGeneratedSource(
  1877. std::string const& filename, GenVarsT const& genVars, bool prepend)
  1878. {
  1879. // Register source at makefile
  1880. cmSourceFile* gFile = this->RegisterGeneratedSource(filename);
  1881. // Add source file to target
  1882. this->GenTarget->AddSource(filename, prepend);
  1883. // Add source file to source group
  1884. this->AddToSourceGroup(filename, genVars.GenNameUpper);
  1885. return gFile;
  1886. }
  1887. void cmQtAutoGenInitializer::AddGeneratedSource(ConfigString const& filename,
  1888. GenVarsT const& genVars,
  1889. bool prepend)
  1890. {
  1891. // XXX(xcode-per-cfg-src): Drop the Xcode-specific part of the condition
  1892. // when the Xcode generator supports per-config sources.
  1893. if (!this->MultiConfig || this->GlobalGen->IsXcode()) {
  1894. cmSourceFile* sf =
  1895. this->AddGeneratedSource(filename.Default, genVars, prepend);
  1896. handleSkipPch(sf);
  1897. return;
  1898. }
  1899. for (auto const& cfg : this->ConfigsList) {
  1900. std::string const& filenameCfg = filename.Config.at(cfg);
  1901. // Register source at makefile
  1902. cmSourceFile* sf = this->RegisterGeneratedSource(filenameCfg);
  1903. handleSkipPch(sf);
  1904. // Add source file to target for this configuration.
  1905. this->GenTarget->AddSource(
  1906. cmStrCat("$<$<CONFIG:"_s, cfg, ">:"_s, filenameCfg, ">"_s), prepend);
  1907. // Add source file to source group
  1908. this->AddToSourceGroup(filenameCfg, genVars.GenNameUpper);
  1909. }
  1910. }
  1911. void cmQtAutoGenInitializer::AddToSourceGroup(std::string const& fileName,
  1912. cm::string_view genNameUpper)
  1913. {
  1914. cmSourceGroup* sourceGroup = nullptr;
  1915. // Acquire source group
  1916. {
  1917. std::string property;
  1918. std::string groupName;
  1919. {
  1920. // Prefer generator specific source group name
  1921. std::initializer_list<std::string> const props{
  1922. cmStrCat(genNameUpper, "_SOURCE_GROUP"), "AUTOGEN_SOURCE_GROUP"
  1923. };
  1924. for (std::string const& prop : props) {
  1925. cmValue propName = this->Makefile->GetState()->GetGlobalProperty(prop);
  1926. if (cmNonempty(propName)) {
  1927. groupName = *propName;
  1928. property = prop;
  1929. break;
  1930. }
  1931. }
  1932. }
  1933. // Generate a source group on demand
  1934. if (!groupName.empty()) {
  1935. sourceGroup = this->Makefile->GetOrCreateSourceGroup(groupName);
  1936. if (!sourceGroup) {
  1937. cmSystemTools::Error(
  1938. cmStrCat(genNameUpper, " error in ", property,
  1939. ": Could not find or create the source group ",
  1940. cmQtAutoGen::Quoted(groupName)));
  1941. }
  1942. }
  1943. }
  1944. if (sourceGroup) {
  1945. sourceGroup->AddGroupFile(fileName);
  1946. }
  1947. }
  1948. void cmQtAutoGenInitializer::AddCleanFile(std::string const& fileName)
  1949. {
  1950. this->GenTarget->Target->AppendProperty("ADDITIONAL_CLEAN_FILES", fileName);
  1951. }
  1952. void cmQtAutoGenInitializer::ConfigFileNames(ConfigString& configString,
  1953. cm::string_view prefix,
  1954. cm::string_view suffix)
  1955. {
  1956. configString.Default = cmStrCat(prefix, suffix);
  1957. if (this->MultiConfig) {
  1958. for (auto const& cfg : this->ConfigsList) {
  1959. configString.Config[cfg] = cmStrCat(prefix, '_', cfg, suffix);
  1960. }
  1961. }
  1962. }
  1963. void cmQtAutoGenInitializer::ConfigFileNamesAndGenex(
  1964. ConfigString& configString, std::string& genex, cm::string_view const prefix,
  1965. cm::string_view const suffix)
  1966. {
  1967. this->ConfigFileNames(configString, prefix, suffix);
  1968. if (this->MultiConfig) {
  1969. genex = cmStrCat(prefix, "_$<CONFIG>"_s, suffix);
  1970. } else {
  1971. genex = configString.Default;
  1972. }
  1973. }
  1974. void cmQtAutoGenInitializer::ConfigFileClean(ConfigString& configString)
  1975. {
  1976. this->AddCleanFile(configString.Default);
  1977. if (this->MultiConfig) {
  1978. for (auto const& pair : configString.Config) {
  1979. this->AddCleanFile(pair.second);
  1980. }
  1981. }
  1982. }
  1983. static cmQtAutoGen::IntegerVersion parseMocVersion(std::string str)
  1984. {
  1985. cmQtAutoGen::IntegerVersion result;
  1986. static const std::string prelude = "moc ";
  1987. size_t const pos = str.find(prelude);
  1988. if (pos == std::string::npos) {
  1989. return result;
  1990. }
  1991. str.erase(0, prelude.size() + pos);
  1992. std::istringstream iss(str);
  1993. std::string major;
  1994. std::string minor;
  1995. if (!std::getline(iss, major, '.') || !std::getline(iss, minor, '.')) {
  1996. return result;
  1997. }
  1998. result.Major = static_cast<unsigned int>(std::stoi(major));
  1999. result.Minor = static_cast<unsigned int>(std::stoi(minor));
  2000. return result;
  2001. }
  2002. static cmQtAutoGen::IntegerVersion GetMocVersion(
  2003. const std::string& mocExecutablePath)
  2004. {
  2005. std::string capturedStdOut;
  2006. int exitCode;
  2007. if (!cmSystemTools::RunSingleCommand({ mocExecutablePath, "--version" },
  2008. &capturedStdOut, nullptr, &exitCode,
  2009. nullptr, cmSystemTools::OUTPUT_NONE)) {
  2010. return {};
  2011. }
  2012. if (exitCode != 0) {
  2013. return {};
  2014. }
  2015. return parseMocVersion(capturedStdOut);
  2016. }
  2017. static std::string FindMocExecutableFromMocTarget(cmMakefile const* makefile,
  2018. unsigned int qtMajorVersion)
  2019. {
  2020. std::string result;
  2021. const std::string mocTargetName =
  2022. "Qt" + std::to_string(qtMajorVersion) + "::moc";
  2023. cmTarget const* mocTarget = makefile->FindTargetToUse(mocTargetName);
  2024. if (mocTarget) {
  2025. result = mocTarget->GetSafeProperty("IMPORTED_LOCATION");
  2026. }
  2027. return result;
  2028. }
  2029. std::pair<cmQtAutoGen::IntegerVersion, unsigned int>
  2030. cmQtAutoGenInitializer::GetQtVersion(cmGeneratorTarget const* target,
  2031. std::string mocExecutable)
  2032. {
  2033. // Converts a char ptr to an unsigned int value
  2034. auto toUInt = [](const char* const input) -> unsigned int {
  2035. unsigned long tmp = 0;
  2036. if (input && cmStrToULong(input, &tmp)) {
  2037. return static_cast<unsigned int>(tmp);
  2038. }
  2039. return 0u;
  2040. };
  2041. auto toUInt2 = [](cmValue input) -> unsigned int {
  2042. unsigned long tmp = 0;
  2043. if (input && cmStrToULong(*input, &tmp)) {
  2044. return static_cast<unsigned int>(tmp);
  2045. }
  2046. return 0u;
  2047. };
  2048. // Initialize return value to a default
  2049. std::pair<IntegerVersion, unsigned int> res(
  2050. IntegerVersion(),
  2051. toUInt(target->GetLinkInterfaceDependentStringProperty("QT_MAJOR_VERSION",
  2052. "")));
  2053. // Acquire known Qt versions
  2054. std::vector<cmQtAutoGen::IntegerVersion> knownQtVersions;
  2055. {
  2056. // Qt version variable prefixes
  2057. static std::initializer_list<
  2058. std::pair<cm::string_view, cm::string_view>> const keys{
  2059. { "Qt6Core_VERSION_MAJOR", "Qt6Core_VERSION_MINOR" },
  2060. { "Qt5Core_VERSION_MAJOR", "Qt5Core_VERSION_MINOR" },
  2061. { "QT_VERSION_MAJOR", "QT_VERSION_MINOR" },
  2062. };
  2063. knownQtVersions.reserve(keys.size() * 2);
  2064. // Adds a version to the result (nullptr safe)
  2065. auto addVersion = [&knownQtVersions, &toUInt2](cmValue major,
  2066. cmValue minor) {
  2067. cmQtAutoGen::IntegerVersion ver(toUInt2(major), toUInt2(minor));
  2068. if (ver.Major != 0) {
  2069. knownQtVersions.emplace_back(ver);
  2070. }
  2071. };
  2072. // Read versions from variables
  2073. for (auto const& keyPair : keys) {
  2074. addVersion(target->Makefile->GetDefinition(std::string(keyPair.first)),
  2075. target->Makefile->GetDefinition(std::string(keyPair.second)));
  2076. }
  2077. // Read versions from directory properties
  2078. for (auto const& keyPair : keys) {
  2079. addVersion(target->Makefile->GetProperty(std::string(keyPair.first)),
  2080. target->Makefile->GetProperty(std::string(keyPair.second)));
  2081. }
  2082. }
  2083. // Evaluate known Qt versions
  2084. if (!knownQtVersions.empty()) {
  2085. if (res.second == 0) {
  2086. // No specific version was requested by the target:
  2087. // Use highest known Qt version.
  2088. res.first = knownQtVersions.at(0);
  2089. } else {
  2090. // Pick a version from the known versions:
  2091. for (auto const& it : knownQtVersions) {
  2092. if (it.Major == res.second) {
  2093. res.first = it;
  2094. break;
  2095. }
  2096. }
  2097. }
  2098. }
  2099. if (res.first.Major == 0) {
  2100. // We could not get the version number from variables or directory
  2101. // properties. This might happen if the find_package call for Qt is wrapped
  2102. // in a function. Try to find the moc executable path from the available
  2103. // targets and call "moc --version" to get the Qt version.
  2104. if (mocExecutable.empty()) {
  2105. mocExecutable =
  2106. FindMocExecutableFromMocTarget(target->Makefile, res.second);
  2107. }
  2108. if (!mocExecutable.empty()) {
  2109. res.first = GetMocVersion(mocExecutable);
  2110. }
  2111. }
  2112. return res;
  2113. }
  2114. std::string cmQtAutoGenInitializer::GetMocBuildPath(MUFile const& muf)
  2115. {
  2116. std::string res;
  2117. if (!muf.MocIt) {
  2118. return res;
  2119. }
  2120. std::string basePath =
  2121. cmStrCat(this->PathCheckSum.getPart(muf.FullPath), "/moc_",
  2122. FileNameWithoutLastExtension(muf.FullPath));
  2123. res = cmStrCat(basePath, ".cpp");
  2124. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  2125. return res;
  2126. }
  2127. // File name already emitted.
  2128. // Try appending the header suffix to the base path.
  2129. basePath = cmStrCat(basePath, '_', muf.SF->GetExtension());
  2130. res = cmStrCat(basePath, ".cpp");
  2131. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  2132. return res;
  2133. }
  2134. // File name with header extension already emitted.
  2135. // Try adding a number to the base path.
  2136. constexpr std::size_t number_begin = 2;
  2137. constexpr std::size_t number_end = 256;
  2138. for (std::size_t ii = number_begin; ii != number_end; ++ii) {
  2139. res = cmStrCat(basePath, '_', ii, ".cpp");
  2140. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  2141. return res;
  2142. }
  2143. }
  2144. // Output file name conflict (unlikely, but still...)
  2145. cmSystemTools::Error(
  2146. cmStrCat("moc output file name conflict for ", muf.FullPath));
  2147. return res;
  2148. }
  2149. bool cmQtAutoGenInitializer::GetQtExecutable(GenVarsT& genVars,
  2150. const std::string& executable,
  2151. bool ignoreMissingTarget) const
  2152. {
  2153. auto print_err = [this, &genVars](std::string const& err) {
  2154. cmSystemTools::Error(cmStrCat(genVars.GenNameUpper, " for target ",
  2155. this->GenTarget->GetName(), ": ", err));
  2156. };
  2157. // Custom executable
  2158. {
  2159. std::string const prop = cmStrCat(genVars.GenNameUpper, "_EXECUTABLE");
  2160. std::string const& val = this->GenTarget->Target->GetSafeProperty(prop);
  2161. if (!val.empty()) {
  2162. // Evaluate generator expression
  2163. {
  2164. cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
  2165. cmGeneratorExpression ge(*this->Makefile->GetCMakeInstance(), lfbt);
  2166. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(val);
  2167. if (this->MultiConfig && this->UseBetterGraph) {
  2168. for (auto const& config : this->ConfigsList) {
  2169. genVars.Executable.Config[config] =
  2170. cge->Evaluate(this->LocalGen, config);
  2171. }
  2172. } else {
  2173. genVars.Executable.Default = cge->Evaluate(this->LocalGen, "");
  2174. }
  2175. }
  2176. if (genVars.Executable.Default.empty() &&
  2177. genVars.Executable.Config.empty() && !ignoreMissingTarget) {
  2178. print_err(prop + " evaluates to an empty value");
  2179. return false;
  2180. }
  2181. // Create empty compiler features.
  2182. if (this->MultiConfig && this->UseBetterGraph) {
  2183. for (auto const& config : this->ConfigsList) {
  2184. genVars.ExecutableFeatures.Config[config] =
  2185. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  2186. }
  2187. } else {
  2188. genVars.ExecutableFeatures.Default =
  2189. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  2190. }
  2191. return true;
  2192. }
  2193. }
  2194. // Find executable target
  2195. {
  2196. // Find executable target name
  2197. cm::string_view prefix;
  2198. if (this->QtVersion.Major == 4) {
  2199. prefix = "Qt4::";
  2200. } else if (this->QtVersion.Major == 5) {
  2201. prefix = "Qt5::";
  2202. } else if (this->QtVersion.Major == 6) {
  2203. prefix = "Qt6::";
  2204. }
  2205. std::string const targetName = cmStrCat(prefix, executable);
  2206. // Find target
  2207. cmGeneratorTarget* genTarget =
  2208. this->LocalGen->FindGeneratorTargetToUse(targetName);
  2209. if (genTarget) {
  2210. genVars.ExecutableTargetName = targetName;
  2211. genVars.ExecutableTarget = genTarget;
  2212. if (genTarget->IsImported()) {
  2213. if (this->MultiConfig && this->UseBetterGraph) {
  2214. for (auto const& config : this->ConfigsList) {
  2215. genVars.Executable.Config[config] =
  2216. genTarget->ImportedGetLocation(config);
  2217. }
  2218. } else {
  2219. genVars.Executable.Default =
  2220. genTarget->ImportedGetLocation(this->ConfigDefault);
  2221. }
  2222. } else {
  2223. if (this->MultiConfig && this->UseBetterGraph) {
  2224. for (auto const& config : this->ConfigsList) {
  2225. genVars.Executable.Config[config] = genTarget->GetLocation(config);
  2226. }
  2227. } else {
  2228. genVars.Executable.Default =
  2229. genTarget->GetLocation(this->ConfigDefault);
  2230. }
  2231. }
  2232. } else {
  2233. if (ignoreMissingTarget) {
  2234. // Create empty compiler features.
  2235. if (this->MultiConfig && this->UseBetterGraph) {
  2236. for (auto const& config : this->ConfigsList) {
  2237. genVars.ExecutableFeatures.Config[config] =
  2238. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  2239. }
  2240. } else {
  2241. genVars.ExecutableFeatures.Default =
  2242. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  2243. }
  2244. return true;
  2245. }
  2246. print_err(cmStrCat("Could not find ", executable, " executable target ",
  2247. targetName));
  2248. return false;
  2249. }
  2250. }
  2251. // Get executable features
  2252. {
  2253. std::string err;
  2254. genVars.ExecutableFeatures = this->GlobalInitializer->GetCompilerFeatures(
  2255. executable, genVars.Executable, err, this->MultiConfig,
  2256. this->UseBetterGraph);
  2257. if (this->MultiConfig && this->UseBetterGraph) {
  2258. for (auto const& config : this->ConfigsList) {
  2259. if (!genVars.ExecutableFeatures.Config[config]) {
  2260. if (!genVars.ExecutableFeatures.Config[config]) {
  2261. print_err(err);
  2262. return false;
  2263. }
  2264. }
  2265. }
  2266. } else {
  2267. if (!genVars.ExecutableFeatures.Default) {
  2268. print_err(err);
  2269. return false;
  2270. }
  2271. }
  2272. }
  2273. return true;
  2274. }
  2275. void cmQtAutoGenInitializer::handleSkipPch(cmSourceFile* sf)
  2276. {
  2277. bool skipPch = true;
  2278. for (auto const& pair : this->AutogenTarget.Sources) {
  2279. if (!pair.first->GetIsGenerated() &&
  2280. !pair.first->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  2281. skipPch = false;
  2282. }
  2283. }
  2284. if (skipPch) {
  2285. sf->SetProperty("SKIP_PRECOMPILE_HEADERS", "ON");
  2286. }
  2287. }