cmQtAutoGenInitializer.cxx 60 KB

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