cmQtAutoGenInitializer.cxx 73 KB

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