cmQtAutoGenInitializer.cxx 86 KB

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