cmQtAutoGenInitializer.cxx 65 KB

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