cmQtAutoGenInitializer.cxx 85 KB

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