cmQtAutoGenInitializer.cxx 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001
  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. void AddAutogenExecutableToDependencies(
  267. cmQtAutoGenInitializer::GenVarsT const& genVars,
  268. std::vector<std::string>& dependencies)
  269. {
  270. if (genVars.ExecutableTarget != nullptr) {
  271. dependencies.push_back(genVars.ExecutableTarget->Target->GetName());
  272. } else if (!genVars.Executable.empty()) {
  273. dependencies.push_back(genVars.Executable);
  274. }
  275. }
  276. } // End of unnamed namespace
  277. cmQtAutoGenInitializer::cmQtAutoGenInitializer(
  278. cmQtAutoGenGlobalInitializer* globalInitializer,
  279. cmGeneratorTarget* genTarget, IntegerVersion const& qtVersion,
  280. bool mocEnabled, bool uicEnabled, bool rccEnabled, bool globalAutogenTarget,
  281. bool globalAutoRccTarget)
  282. : GlobalInitializer(globalInitializer)
  283. , GenTarget(genTarget)
  284. , GlobalGen(genTarget->GetGlobalGenerator())
  285. , LocalGen(genTarget->GetLocalGenerator())
  286. , Makefile(genTarget->Makefile)
  287. , PathCheckSum(genTarget->Makefile)
  288. , QtVersion(qtVersion)
  289. {
  290. this->AutogenTarget.GlobalTarget = globalAutogenTarget;
  291. this->Moc.Enabled = mocEnabled;
  292. this->Uic.Enabled = uicEnabled;
  293. this->Rcc.Enabled = rccEnabled;
  294. this->Rcc.GlobalTarget = globalAutoRccTarget;
  295. }
  296. bool cmQtAutoGenInitializer::InitCustomTargets()
  297. {
  298. // Configurations
  299. this->MultiConfig = this->GlobalGen->IsMultiConfig();
  300. this->ConfigDefault = this->Makefile->GetDefaultConfiguration();
  301. this->ConfigsList =
  302. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  303. // Verbosity
  304. {
  305. std::string def =
  306. this->Makefile->GetSafeDefinition("CMAKE_AUTOGEN_VERBOSE");
  307. if (!def.empty()) {
  308. unsigned long iVerb = 0;
  309. if (cmStrToULong(def, &iVerb)) {
  310. // Numeric verbosity
  311. this->Verbosity = static_cast<unsigned int>(iVerb);
  312. } else {
  313. // Non numeric verbosity
  314. if (cmIsOn(def)) {
  315. this->Verbosity = 1;
  316. }
  317. }
  318. }
  319. }
  320. // Targets FOLDER
  321. {
  322. cmProp folder =
  323. this->Makefile->GetState()->GetGlobalProperty("AUTOMOC_TARGETS_FOLDER");
  324. if (folder == nullptr) {
  325. folder = this->Makefile->GetState()->GetGlobalProperty(
  326. "AUTOGEN_TARGETS_FOLDER");
  327. }
  328. // Inherit FOLDER property from target (#13688)
  329. if (folder == nullptr) {
  330. folder = this->GenTarget->GetProperty("FOLDER");
  331. }
  332. if (folder != nullptr) {
  333. this->TargetsFolder = *folder;
  334. }
  335. }
  336. // Check status of policy CMP0071 regarding handling of GENERATED files
  337. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0071)) {
  338. case cmPolicies::WARN:
  339. // Ignore GENERATED files but warn
  340. this->CMP0071Warn = true;
  341. CM_FALLTHROUGH;
  342. case cmPolicies::OLD:
  343. // Ignore GENERATED files
  344. break;
  345. case cmPolicies::REQUIRED_IF_USED:
  346. case cmPolicies::REQUIRED_ALWAYS:
  347. case cmPolicies::NEW:
  348. // Process GENERATED files
  349. this->CMP0071Accept = true;
  350. break;
  351. }
  352. // Check status of policy CMP0100 regarding handling of .hh headers
  353. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0100)) {
  354. case cmPolicies::WARN:
  355. // Ignore but .hh files but warn
  356. this->CMP0100Warn = true;
  357. CM_FALLTHROUGH;
  358. case cmPolicies::OLD:
  359. // Ignore .hh files
  360. break;
  361. case cmPolicies::REQUIRED_IF_USED:
  362. case cmPolicies::REQUIRED_ALWAYS:
  363. case cmPolicies::NEW:
  364. // Process .hh file
  365. this->CMP0100Accept = true;
  366. break;
  367. }
  368. // Common directories
  369. {
  370. // Collapsed current binary directory
  371. std::string const cbd = cmSystemTools::CollapseFullPath(
  372. std::string(), this->Makefile->GetCurrentBinaryDirectory());
  373. // Info directory
  374. this->Dir.Info = cmStrCat(cbd, "/CMakeFiles/", this->GenTarget->GetName(),
  375. "_autogen.dir");
  376. cmSystemTools::ConvertToUnixSlashes(this->Dir.Info);
  377. // Build directory
  378. this->Dir.Build = this->GenTarget->GetSafeProperty("AUTOGEN_BUILD_DIR");
  379. if (this->Dir.Build.empty()) {
  380. this->Dir.Build =
  381. cmStrCat(cbd, '/', this->GenTarget->GetName(), "_autogen");
  382. }
  383. cmSystemTools::ConvertToUnixSlashes(this->Dir.Build);
  384. // Cleanup build directory
  385. this->AddCleanFile(this->Dir.Build);
  386. // Working directory
  387. this->Dir.Work = cbd;
  388. cmSystemTools::ConvertToUnixSlashes(this->Dir.Work);
  389. // Include directory
  390. this->ConfigFileNamesAndGenex(this->Dir.Include, this->Dir.IncludeGenExp,
  391. cmStrCat(this->Dir.Build, "/include"), "");
  392. }
  393. // Moc, Uic and _autogen target settings
  394. if (this->MocOrUicEnabled()) {
  395. // Init moc specific settings
  396. if (this->Moc.Enabled && !this->InitMoc()) {
  397. return false;
  398. }
  399. // Init uic specific settings
  400. if (this->Uic.Enabled && !this->InitUic()) {
  401. return false;
  402. }
  403. // Autogen target name
  404. this->AutogenTarget.Name =
  405. cmStrCat(this->GenTarget->GetName(), "_autogen");
  406. // Autogen target parallel processing
  407. {
  408. std::string const& prop =
  409. this->GenTarget->GetSafeProperty("AUTOGEN_PARALLEL");
  410. if (prop.empty() || (prop == "AUTO")) {
  411. // Autodetect number of CPUs
  412. this->AutogenTarget.Parallel = GetParallelCPUCount();
  413. } else {
  414. this->AutogenTarget.Parallel = 1;
  415. }
  416. }
  417. // Autogen target info and settings files
  418. {
  419. // Info file
  420. this->AutogenTarget.InfoFile =
  421. cmStrCat(this->Dir.Info, "/AutogenInfo.json");
  422. // Used settings file
  423. this->ConfigFileNames(this->AutogenTarget.SettingsFile,
  424. cmStrCat(this->Dir.Info, "/AutogenUsed"), ".txt");
  425. this->ConfigFileClean(this->AutogenTarget.SettingsFile);
  426. // Parse cache file
  427. this->ConfigFileNames(this->AutogenTarget.ParseCacheFile,
  428. cmStrCat(this->Dir.Info, "/ParseCache"), ".txt");
  429. this->ConfigFileClean(this->AutogenTarget.ParseCacheFile);
  430. }
  431. // Autogen target: Compute user defined dependencies
  432. {
  433. this->AutogenTarget.DependOrigin =
  434. this->GenTarget->GetPropertyAsBool("AUTOGEN_ORIGIN_DEPENDS");
  435. std::string const& deps =
  436. this->GenTarget->GetSafeProperty("AUTOGEN_TARGET_DEPENDS");
  437. if (!deps.empty()) {
  438. for (std::string const& depName : cmExpandedList(deps)) {
  439. // Allow target and file dependencies
  440. auto* depTarget = this->Makefile->FindTargetToUse(depName);
  441. if (depTarget != nullptr) {
  442. this->AutogenTarget.DependTargets.insert(depTarget);
  443. } else {
  444. this->AutogenTarget.DependFiles.insert(depName);
  445. }
  446. }
  447. }
  448. }
  449. if (this->Moc.Enabled) {
  450. // Path prefix
  451. if (cmIsOn(this->GenTarget->GetProperty("AUTOMOC_PATH_PREFIX"))) {
  452. this->Moc.PathPrefix = true;
  453. }
  454. // CMAKE_AUTOMOC_RELAXED_MODE
  455. if (this->Makefile->IsOn("CMAKE_AUTOMOC_RELAXED_MODE")) {
  456. this->Moc.RelaxedMode = true;
  457. this->Makefile->IssueMessage(
  458. MessageType::AUTHOR_WARNING,
  459. cmStrCat("AUTOMOC: CMAKE_AUTOMOC_RELAXED_MODE is "
  460. "deprecated an will be removed in the future. Consider "
  461. "disabling it and converting the target ",
  462. this->GenTarget->GetName(), " to regular mode."));
  463. }
  464. // Options
  465. cmExpandList(this->GenTarget->GetSafeProperty("AUTOMOC_MOC_OPTIONS"),
  466. this->Moc.Options);
  467. // Filters
  468. cmExpandList(this->GenTarget->GetSafeProperty("AUTOMOC_MACRO_NAMES"),
  469. this->Moc.MacroNames);
  470. {
  471. auto filterList = cmExpandedList(
  472. this->GenTarget->GetSafeProperty("AUTOMOC_DEPEND_FILTERS"));
  473. if ((filterList.size() % 2) != 0) {
  474. cmSystemTools::Error(
  475. cmStrCat("AutoMoc: AUTOMOC_DEPEND_FILTERS predefs size ",
  476. filterList.size(), " is not a multiple of 2."));
  477. return false;
  478. }
  479. this->Moc.DependFilters.reserve(1 + (filterList.size() / 2));
  480. this->Moc.DependFilters.emplace_back(
  481. "Q_PLUGIN_METADATA",
  482. "[\n][ \t]*Q_PLUGIN_METADATA[ \t]*\\("
  483. "[^\\)]*FILE[ \t]*\"([^\"]+)\"");
  484. for (std::size_t ii = 0; ii != filterList.size(); ii += 2) {
  485. this->Moc.DependFilters.emplace_back(filterList[ii],
  486. filterList[ii + 1]);
  487. }
  488. }
  489. }
  490. }
  491. // Init rcc specific settings
  492. if (this->Rcc.Enabled && !this->InitRcc()) {
  493. return false;
  494. }
  495. // Add autogen include directory to the origin target INCLUDE_DIRECTORIES
  496. if (this->MocOrUicEnabled() || (this->Rcc.Enabled && this->MultiConfig)) {
  497. this->GenTarget->AddIncludeDirectory(this->Dir.IncludeGenExp, true);
  498. }
  499. // Scan files
  500. if (!this->InitScanFiles()) {
  501. return false;
  502. }
  503. // Create autogen target
  504. if (this->MocOrUicEnabled() && !this->InitAutogenTarget()) {
  505. return false;
  506. }
  507. // Create rcc targets
  508. if (this->Rcc.Enabled && !this->InitRccTargets()) {
  509. return false;
  510. }
  511. return true;
  512. }
  513. bool cmQtAutoGenInitializer::InitMoc()
  514. {
  515. // Mocs compilation file
  516. if (this->GlobalGen->IsXcode()) {
  517. // XXX(xcode-per-cfg-src): Drop this Xcode-specific code path
  518. // when the Xcode generator supports per-config sources.
  519. this->Moc.CompilationFile.Default =
  520. cmStrCat(this->Dir.Build, "/mocs_compilation.cpp");
  521. this->Moc.CompilationFileGenex = this->Moc.CompilationFile.Default;
  522. } else {
  523. this->ConfigFileNamesAndGenex(
  524. this->Moc.CompilationFile, this->Moc.CompilationFileGenex,
  525. cmStrCat(this->Dir.Build, "/mocs_compilation"_s), ".cpp"_s);
  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.UiFilesWithOptions.emplace_back(fullPath,
  854. cmExpandedList(uicOpts));
  855. }
  856. auto uiHeaderRelativePath = cmSystemTools::RelativePath(
  857. this->LocalGen->GetCurrentSourceDirectory(),
  858. cmSystemTools::GetFilenamePath(fullPath));
  859. // Avoid creating a path containing adjacent slashes
  860. if (!uiHeaderRelativePath.empty() &&
  861. uiHeaderRelativePath.back() != '/') {
  862. uiHeaderRelativePath += '/';
  863. }
  864. auto uiHeaderFilePath = cmStrCat(
  865. '/', uiHeaderRelativePath, "ui_"_s,
  866. cmSystemTools::GetFilenameWithoutLastExtension(fullPath), ".h"_s);
  867. ConfigString uiHeader;
  868. std::string uiHeaderGenex;
  869. this->ConfigFileNamesAndGenex(
  870. uiHeader, uiHeaderGenex, cmStrCat(this->Dir.Build, "/include"_s),
  871. uiHeaderFilePath);
  872. this->Uic.UiHeaders.emplace_back(
  873. std::make_pair(uiHeader, uiHeaderGenex));
  874. } else {
  875. // Register skipped .ui file
  876. this->Uic.SkipUi.insert(fullPath);
  877. }
  878. }
  879. }
  880. }
  881. // Process GENERATED sources and headers
  882. if (this->MocOrUicEnabled() && !this->AutogenTarget.FilesGenerated.empty()) {
  883. if (this->CMP0071Accept) {
  884. // Let the autogen target depend on the GENERATED files
  885. for (MUFile* muf : this->AutogenTarget.FilesGenerated) {
  886. this->AutogenTarget.DependFiles.insert(muf->FullPath);
  887. }
  888. } else if (this->CMP0071Warn) {
  889. cm::string_view property;
  890. if (this->Moc.Enabled && this->Uic.Enabled) {
  891. property = "SKIP_AUTOGEN";
  892. } else if (this->Moc.Enabled) {
  893. property = "SKIP_AUTOMOC";
  894. } else if (this->Uic.Enabled) {
  895. property = "SKIP_AUTOUIC";
  896. }
  897. std::string files;
  898. for (MUFile* muf : this->AutogenTarget.FilesGenerated) {
  899. files += cmStrCat(" ", Quoted(muf->FullPath), '\n');
  900. }
  901. this->Makefile->IssueMessage(
  902. MessageType::AUTHOR_WARNING,
  903. cmStrCat(
  904. cmPolicies::GetPolicyWarning(cmPolicies::CMP0071), '\n',
  905. "For compatibility, CMake is excluding the GENERATED source "
  906. "file(s):\n",
  907. files, "from processing by ",
  908. cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
  909. ". If any of the files should be processed, set CMP0071 to NEW. "
  910. "If any of the files should not be processed, "
  911. "explicitly exclude them by setting the source file property ",
  912. property, ":\n set_property(SOURCE file.h PROPERTY ", property,
  913. " ON)\n"));
  914. }
  915. }
  916. // Generate CMP0100 warning
  917. if (this->MocOrUicEnabled() &&
  918. !this->AutogenTarget.CMP0100HeadersWarn.empty()) {
  919. cm::string_view property;
  920. if (this->Moc.Enabled && this->Uic.Enabled) {
  921. property = "SKIP_AUTOGEN";
  922. } else if (this->Moc.Enabled) {
  923. property = "SKIP_AUTOMOC";
  924. } else if (this->Uic.Enabled) {
  925. property = "SKIP_AUTOUIC";
  926. }
  927. std::string files;
  928. for (cmSourceFile* sf : this->AutogenTarget.CMP0100HeadersWarn) {
  929. files += cmStrCat(" ", Quoted(sf->GetFullPath()), '\n');
  930. }
  931. this->Makefile->IssueMessage(
  932. MessageType::AUTHOR_WARNING,
  933. cmStrCat(
  934. cmPolicies::GetPolicyWarning(cmPolicies::CMP0100), '\n',
  935. "For compatibility, CMake is excluding the header file(s):\n", files,
  936. "from processing by ",
  937. cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
  938. ". If any of the files should be processed, set CMP0100 to NEW. "
  939. "If any of the files should not be processed, "
  940. "explicitly exclude them by setting the source file property ",
  941. property, ":\n set_property(SOURCE file.hh PROPERTY ", property,
  942. " ON)\n"));
  943. }
  944. // Process qrc files
  945. if (!this->Rcc.Qrcs.empty()) {
  946. const bool modernQt = (this->QtVersion.Major >= 5);
  947. // Target rcc options
  948. std::vector<std::string> optionsTarget =
  949. cmExpandedList(this->GenTarget->GetSafeProperty(kw.AUTORCC_OPTIONS));
  950. // Check if file name is unique
  951. for (Qrc& qrc : this->Rcc.Qrcs) {
  952. qrc.Unique = true;
  953. for (Qrc const& qrc2 : this->Rcc.Qrcs) {
  954. if ((&qrc != &qrc2) && (qrc.QrcName == qrc2.QrcName)) {
  955. qrc.Unique = false;
  956. break;
  957. }
  958. }
  959. }
  960. // Path checksum and file names
  961. for (Qrc& qrc : this->Rcc.Qrcs) {
  962. // Path checksum
  963. qrc.QrcPathChecksum = this->PathCheckSum.getPart(qrc.QrcFile);
  964. // Output file name
  965. qrc.OutputFile = cmStrCat(this->Dir.Build, '/', qrc.QrcPathChecksum,
  966. "/qrc_", qrc.QrcName, ".cpp");
  967. std::string const base = cmStrCat(this->Dir.Info, "/AutoRcc_",
  968. qrc.QrcName, '_', qrc.QrcPathChecksum);
  969. qrc.LockFile = cmStrCat(base, "_Lock.lock");
  970. qrc.InfoFile = cmStrCat(base, "_Info.json");
  971. this->ConfigFileNames(qrc.SettingsFile, cmStrCat(base, "_Used"), ".txt");
  972. }
  973. // rcc options
  974. for (Qrc& qrc : this->Rcc.Qrcs) {
  975. // Target options
  976. std::vector<std::string> opts = optionsTarget;
  977. // Merge computed "-name XYZ" option
  978. {
  979. std::string name = qrc.QrcName;
  980. // Replace '-' with '_'. The former is not valid for symbol names.
  981. std::replace(name.begin(), name.end(), '-', '_');
  982. if (!qrc.Unique) {
  983. name += cmStrCat('_', qrc.QrcPathChecksum);
  984. }
  985. std::vector<std::string> nameOpts;
  986. nameOpts.emplace_back("-name");
  987. nameOpts.emplace_back(std::move(name));
  988. RccMergeOptions(opts, nameOpts, modernQt);
  989. }
  990. // Merge file option
  991. RccMergeOptions(opts, qrc.Options, modernQt);
  992. qrc.Options = std::move(opts);
  993. }
  994. // rcc resources
  995. for (Qrc& qrc : this->Rcc.Qrcs) {
  996. if (!qrc.Generated) {
  997. std::string error;
  998. RccLister const lister(this->Rcc.Executable,
  999. this->Rcc.ExecutableFeatures->ListOptions);
  1000. if (!lister.list(qrc.QrcFile, qrc.Resources, error)) {
  1001. cmSystemTools::Error(error);
  1002. return false;
  1003. }
  1004. }
  1005. }
  1006. }
  1007. return true;
  1008. }
  1009. bool cmQtAutoGenInitializer::InitAutogenTarget()
  1010. {
  1011. // Register info file as generated by CMake
  1012. this->Makefile->AddCMakeOutputFile(this->AutogenTarget.InfoFile);
  1013. // Files provided by the autogen target
  1014. std::vector<std::string> autogenByproducts;
  1015. if (this->Moc.Enabled) {
  1016. this->AddGeneratedSource(this->Moc.CompilationFile, this->Moc, true);
  1017. autogenByproducts.push_back(this->Moc.CompilationFileGenex);
  1018. }
  1019. if (this->Uic.Enabled) {
  1020. for (const auto& file : this->Uic.UiHeaders) {
  1021. this->AddGeneratedSource(file.first, this->Uic);
  1022. autogenByproducts.push_back(file.second);
  1023. }
  1024. }
  1025. // Compose target comment
  1026. std::string autogenComment;
  1027. {
  1028. std::string tools;
  1029. if (this->Moc.Enabled) {
  1030. tools += "MOC";
  1031. }
  1032. if (this->Uic.Enabled) {
  1033. if (!tools.empty()) {
  1034. tools += " and ";
  1035. }
  1036. tools += "UIC";
  1037. }
  1038. autogenComment = cmStrCat("Automatic ", tools, " for target ",
  1039. this->GenTarget->GetName());
  1040. }
  1041. // Compose command lines
  1042. // FIXME: Take advantage of our per-config mocs_compilation_$<CONFIG>.cpp
  1043. // instead of fiddling with the include directories
  1044. std::vector<std::string> configs;
  1045. this->GlobalGen->GetQtAutoGenConfigs(configs);
  1046. bool stdPipesUTF8 = true;
  1047. cmCustomCommandLines commandLines;
  1048. for (auto const& config : configs) {
  1049. commandLines.push_back(cmMakeCommandLine(
  1050. { cmSystemTools::GetCMakeCommand(), "-E", "cmake_autogen",
  1051. this->AutogenTarget.InfoFile, config }));
  1052. }
  1053. // Use PRE_BUILD on demand
  1054. bool usePRE_BUILD = false;
  1055. if (this->GlobalGen->GetName().find("Visual Studio") != std::string::npos) {
  1056. // Under VS use a PRE_BUILD event instead of a separate target to
  1057. // reduce the number of targets loaded into the IDE.
  1058. // This also works around a VS 11 bug that may skip updating the target:
  1059. // https://connect.microsoft.com/VisualStudio/feedback/details/769495
  1060. usePRE_BUILD = true;
  1061. }
  1062. // Disable PRE_BUILD in some cases
  1063. if (usePRE_BUILD) {
  1064. // Cannot use PRE_BUILD with file depends
  1065. if (!this->AutogenTarget.DependFiles.empty()) {
  1066. usePRE_BUILD = false;
  1067. }
  1068. // Cannot use PRE_BUILD when a global autogen target is in place
  1069. if (this->AutogenTarget.GlobalTarget) {
  1070. usePRE_BUILD = false;
  1071. }
  1072. }
  1073. // Create the autogen target/command
  1074. if (usePRE_BUILD) {
  1075. // Add additional autogen target dependencies to origin target
  1076. for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
  1077. this->GenTarget->Target->AddUtility(depTarget->GetName(), false,
  1078. this->Makefile);
  1079. }
  1080. // Add the pre-build command directly to bypass the OBJECT_LIBRARY
  1081. // rejection in cmMakefile::AddCustomCommandToTarget because we know
  1082. // PRE_BUILD will work for an OBJECT_LIBRARY in this specific case.
  1083. //
  1084. // PRE_BUILD does not support file dependencies!
  1085. const std::vector<std::string> no_output;
  1086. const std::vector<std::string> no_deps;
  1087. cmCustomCommand cc(no_output, autogenByproducts, no_deps, commandLines,
  1088. this->Makefile->GetBacktrace(), autogenComment.c_str(),
  1089. this->Dir.Work.c_str(), stdPipesUTF8);
  1090. cc.SetEscapeOldStyle(false);
  1091. cc.SetEscapeAllowMakeVars(true);
  1092. this->GenTarget->Target->AddPreBuildCommand(std::move(cc));
  1093. } else {
  1094. // Add link library target dependencies to the autogen target
  1095. // dependencies
  1096. if (this->AutogenTarget.DependOrigin) {
  1097. // add_dependencies/addUtility do not support generator expressions.
  1098. // We depend only on the libraries found in all configs therefore.
  1099. std::map<cmGeneratorTarget const*, std::size_t> commonTargets;
  1100. for (std::string const& config : this->ConfigsList) {
  1101. cmLinkImplementationLibraries const* libs =
  1102. this->GenTarget->GetLinkImplementationLibraries(config);
  1103. if (libs != nullptr) {
  1104. for (cmLinkItem const& item : libs->Libraries) {
  1105. cmGeneratorTarget const* libTarget = item.Target;
  1106. if ((libTarget != nullptr) &&
  1107. !StaticLibraryCycle(this->GenTarget, libTarget, config)) {
  1108. // Increment target config count
  1109. commonTargets[libTarget]++;
  1110. }
  1111. }
  1112. }
  1113. }
  1114. for (auto const& item : commonTargets) {
  1115. if (item.second == this->ConfigsList.size()) {
  1116. this->AutogenTarget.DependTargets.insert(item.first->Target);
  1117. }
  1118. }
  1119. }
  1120. std::vector<std::string> dependencies(
  1121. this->AutogenTarget.DependFiles.begin(),
  1122. this->AutogenTarget.DependFiles.end());
  1123. const bool useNinjaDepfile = this->QtVersion >= IntegerVersion(5, 15) &&
  1124. this->GlobalGen->GetName().find("Ninja") != std::string::npos;
  1125. if (useNinjaDepfile) {
  1126. // Create a custom command that generates a timestamp file and
  1127. // has a depfile assigned. The depfile is created by JobDepFilesMergeT.
  1128. //
  1129. // Also create an additional '_autogen_timestamp_deps' that the custom
  1130. // command will depend on. It will have no sources or commands to
  1131. // execute, but it will have dependencies that would originally be
  1132. // assigned to the pre-Qt 5.15 'autogen' target. These dependencies will
  1133. // serve as a list of order-only dependencies for the custom command,
  1134. // without forcing the custom command to re-execute.
  1135. //
  1136. // The dependency tree would then look like
  1137. // '_autogen_timestamp_deps (order-only)' <- '/timestamp' file <-
  1138. // '_autogen' target.
  1139. const auto timestampTargetName =
  1140. cmStrCat(this->GenTarget->GetName(), "_autogen_timestamp_deps");
  1141. std::vector<std::string> timestampTargetProvides;
  1142. cmCustomCommandLines timestampTargetCommandLines;
  1143. // Add additional autogen target dependencies to
  1144. // '_autogen_timestamp_deps'.
  1145. for (const cmTarget* t : this->AutogenTarget.DependTargets) {
  1146. dependencies.push_back(t->GetName());
  1147. }
  1148. cmTarget* timestampTarget = this->LocalGen->AddUtilityCommand(
  1149. timestampTargetName, true, this->Dir.Work.c_str(),
  1150. /*byproducts=*/timestampTargetProvides,
  1151. /*depends=*/dependencies, timestampTargetCommandLines, cmPolicies::NEW,
  1152. false, nullptr);
  1153. this->LocalGen->AddGeneratorTarget(
  1154. cm::make_unique<cmGeneratorTarget>(timestampTarget, this->LocalGen));
  1155. // Set FOLDER property on the timestamp target, so it appears in the
  1156. // appropriate folder in an IDE or in the file api.
  1157. if (!this->TargetsFolder.empty()) {
  1158. timestampTarget->SetProperty("FOLDER", this->TargetsFolder);
  1159. }
  1160. // Make '/timestamp' file depend on '_autogen_timestamp_deps' and on the
  1161. // moc and uic executables (whichever are enabled).
  1162. dependencies.clear();
  1163. dependencies.push_back(timestampTargetName);
  1164. AddAutogenExecutableToDependencies(this->Moc, dependencies);
  1165. AddAutogenExecutableToDependencies(this->Uic, dependencies);
  1166. // Create the custom command that outputs the timestamp file.
  1167. const char timestampFileName[] = "timestamp";
  1168. const std::string outputFile =
  1169. cmStrCat(this->Dir.Build, "/", timestampFileName);
  1170. this->AutogenTarget.DepFile = cmStrCat(this->Dir.Build, "/deps");
  1171. this->AutogenTarget.DepFileRuleName =
  1172. cmStrCat(this->GenTarget->GetName(), "_autogen/", timestampFileName);
  1173. commandLines.push_back(cmMakeCommandLine(
  1174. { cmSystemTools::GetCMakeCommand(), "-E", "touch", outputFile }));
  1175. this->AddGeneratedSource(outputFile, this->Moc);
  1176. const std::string no_main_dependency;
  1177. this->LocalGen->AddCustomCommandToOutput(
  1178. outputFile, dependencies, no_main_dependency, commandLines,
  1179. autogenComment.c_str(), this->Dir.Work.c_str(),
  1180. /*cmp0116=*/cmPolicies::NEW, /*replace=*/false,
  1181. /*escapeOldStyle=*/false,
  1182. /*uses_terminal=*/false,
  1183. /*command_expand_lists=*/false, this->AutogenTarget.DepFile, "",
  1184. stdPipesUTF8);
  1185. // Alter variables for the autogen target which now merely wraps the
  1186. // custom command
  1187. dependencies.clear();
  1188. dependencies.push_back(outputFile);
  1189. commandLines.clear();
  1190. autogenComment.clear();
  1191. }
  1192. // Create autogen target
  1193. cmTarget* autogenTarget = this->LocalGen->AddUtilityCommand(
  1194. this->AutogenTarget.Name, true, this->Dir.Work.c_str(),
  1195. /*byproducts=*/autogenByproducts,
  1196. /*depends=*/dependencies, commandLines, cmPolicies::NEW, false,
  1197. autogenComment.c_str());
  1198. // Create autogen generator target
  1199. this->LocalGen->AddGeneratorTarget(
  1200. cm::make_unique<cmGeneratorTarget>(autogenTarget, this->LocalGen));
  1201. // Forward origin utilities to autogen target
  1202. if (this->AutogenTarget.DependOrigin) {
  1203. for (BT<std::pair<std::string, bool>> const& depName :
  1204. this->GenTarget->GetUtilities()) {
  1205. autogenTarget->AddUtility(depName.Value.first, false, this->Makefile);
  1206. }
  1207. }
  1208. if (!useNinjaDepfile) {
  1209. // Add additional autogen target dependencies to autogen target
  1210. for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
  1211. autogenTarget->AddUtility(depTarget->GetName(), false, this->Makefile);
  1212. }
  1213. }
  1214. // Set FOLDER property in autogen target
  1215. if (!this->TargetsFolder.empty()) {
  1216. autogenTarget->SetProperty("FOLDER", this->TargetsFolder);
  1217. }
  1218. // Add autogen target to the origin target dependencies
  1219. this->GenTarget->Target->AddUtility(this->AutogenTarget.Name, false,
  1220. this->Makefile);
  1221. // Add autogen target to the global autogen target dependencies
  1222. if (this->AutogenTarget.GlobalTarget) {
  1223. this->GlobalInitializer->AddToGlobalAutoGen(this->LocalGen,
  1224. this->AutogenTarget.Name);
  1225. }
  1226. }
  1227. return true;
  1228. }
  1229. bool cmQtAutoGenInitializer::InitRccTargets()
  1230. {
  1231. for (Qrc const& qrc : this->Rcc.Qrcs) {
  1232. // Register info file as generated by CMake
  1233. this->Makefile->AddCMakeOutputFile(qrc.InfoFile);
  1234. // Register file at target
  1235. {
  1236. cmSourceFile* sf = this->AddGeneratedSource(qrc.OutputFile, this->Rcc);
  1237. sf->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "On");
  1238. }
  1239. std::vector<std::string> ccOutput;
  1240. ccOutput.push_back(qrc.OutputFile);
  1241. std::vector<std::string> ccDepends;
  1242. // Add the .qrc and info file to the custom command dependencies
  1243. ccDepends.push_back(qrc.QrcFile);
  1244. ccDepends.push_back(qrc.InfoFile);
  1245. bool stdPipesUTF8 = true;
  1246. cmCustomCommandLines commandLines;
  1247. if (this->MultiConfig) {
  1248. // Build for all configurations
  1249. for (std::string const& config : this->ConfigsList) {
  1250. commandLines.push_back(
  1251. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
  1252. "cmake_autorcc", qrc.InfoFile, config }));
  1253. }
  1254. } else {
  1255. commandLines.push_back(
  1256. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
  1257. "cmake_autorcc", qrc.InfoFile, "$<CONFIG>" }));
  1258. }
  1259. std::string ccComment =
  1260. cmStrCat("Automatic RCC for ",
  1261. FileProjectRelativePath(this->Makefile, qrc.QrcFile));
  1262. if (qrc.Generated || this->Rcc.GlobalTarget) {
  1263. // Create custom rcc target
  1264. std::string ccName;
  1265. {
  1266. ccName = cmStrCat(this->GenTarget->GetName(), "_arcc_", qrc.QrcName);
  1267. if (!qrc.Unique) {
  1268. ccName += cmStrCat('_', qrc.QrcPathChecksum);
  1269. }
  1270. cmTarget* autoRccTarget = this->LocalGen->AddUtilityCommand(
  1271. ccName, true, this->Dir.Work.c_str(), ccOutput, ccDepends,
  1272. commandLines, cmPolicies::NEW, false, ccComment.c_str(), false,
  1273. false, "", stdPipesUTF8);
  1274. // Create autogen generator target
  1275. this->LocalGen->AddGeneratorTarget(
  1276. cm::make_unique<cmGeneratorTarget>(autoRccTarget, this->LocalGen));
  1277. // Set FOLDER property in autogen target
  1278. if (!this->TargetsFolder.empty()) {
  1279. autoRccTarget->SetProperty("FOLDER", this->TargetsFolder);
  1280. }
  1281. if (!this->Rcc.ExecutableTargetName.empty()) {
  1282. autoRccTarget->AddUtility(this->Rcc.ExecutableTargetName, false,
  1283. this->Makefile);
  1284. }
  1285. }
  1286. // Add autogen target to the origin target dependencies
  1287. this->GenTarget->Target->AddUtility(ccName, false, this->Makefile);
  1288. // Add autogen target to the global autogen target dependencies
  1289. if (this->Rcc.GlobalTarget) {
  1290. this->GlobalInitializer->AddToGlobalAutoRcc(this->LocalGen, ccName);
  1291. }
  1292. } else {
  1293. // Create custom rcc command
  1294. {
  1295. std::vector<std::string> ccByproducts;
  1296. // Add the resource files to the dependencies
  1297. for (std::string const& fileName : qrc.Resources) {
  1298. // Add resource file to the custom command dependencies
  1299. ccDepends.push_back(fileName);
  1300. }
  1301. if (!this->Rcc.ExecutableTargetName.empty()) {
  1302. ccDepends.push_back(this->Rcc.ExecutableTargetName);
  1303. }
  1304. std::string no_main_dependency;
  1305. cmImplicitDependsList no_implicit_depends;
  1306. this->LocalGen->AddCustomCommandToOutput(
  1307. ccOutput, ccByproducts, ccDepends, no_main_dependency,
  1308. no_implicit_depends, commandLines, ccComment.c_str(),
  1309. this->Dir.Work.c_str(), cmPolicies::NEW, false, true, false, false,
  1310. "", "", stdPipesUTF8);
  1311. }
  1312. // Reconfigure when .qrc file changes
  1313. this->Makefile->AddCMakeDependFile(qrc.QrcFile);
  1314. }
  1315. }
  1316. return true;
  1317. }
  1318. bool cmQtAutoGenInitializer::SetupCustomTargets()
  1319. {
  1320. // Create info directory on demand
  1321. if (!cmSystemTools::MakeDirectory(this->Dir.Info)) {
  1322. cmSystemTools::Error(cmStrCat("AutoGen: Could not create directory: ",
  1323. Quoted(this->Dir.Info)));
  1324. return false;
  1325. }
  1326. // Generate autogen target info file
  1327. if (this->MocOrUicEnabled()) {
  1328. // Write autogen target info files
  1329. if (!this->SetupWriteAutogenInfo()) {
  1330. return false;
  1331. }
  1332. }
  1333. // Write AUTORCC info files
  1334. return !this->Rcc.Enabled || this->SetupWriteRccInfo();
  1335. }
  1336. bool cmQtAutoGenInitializer::SetupWriteAutogenInfo()
  1337. {
  1338. // Utility lambdas
  1339. auto MfDef = [this](std::string const& key) {
  1340. return this->Makefile->GetSafeDefinition(key);
  1341. };
  1342. // Filtered headers and sources
  1343. std::set<std::string> moc_skip;
  1344. std::set<std::string> uic_skip;
  1345. std::vector<MUFile const*> headers;
  1346. std::vector<MUFile const*> sources;
  1347. // Filter headers
  1348. {
  1349. headers.reserve(this->AutogenTarget.Headers.size());
  1350. for (auto const& pair : this->AutogenTarget.Headers) {
  1351. MUFile const* const muf = pair.second.get();
  1352. if (muf->SkipMoc) {
  1353. moc_skip.insert(muf->FullPath);
  1354. }
  1355. if (muf->SkipUic) {
  1356. uic_skip.insert(muf->FullPath);
  1357. }
  1358. if (muf->Generated && !this->CMP0071Accept) {
  1359. continue;
  1360. }
  1361. if (muf->MocIt || muf->UicIt) {
  1362. headers.emplace_back(muf);
  1363. }
  1364. }
  1365. std::sort(headers.begin(), headers.end(),
  1366. [](MUFile const* a, MUFile const* b) {
  1367. return (a->FullPath < b->FullPath);
  1368. });
  1369. }
  1370. // Filter sources
  1371. {
  1372. sources.reserve(this->AutogenTarget.Sources.size());
  1373. for (auto const& pair : this->AutogenTarget.Sources) {
  1374. MUFile const* const muf = pair.second.get();
  1375. if (muf->Generated && !this->CMP0071Accept) {
  1376. continue;
  1377. }
  1378. if (muf->SkipMoc) {
  1379. moc_skip.insert(muf->FullPath);
  1380. }
  1381. if (muf->SkipUic) {
  1382. uic_skip.insert(muf->FullPath);
  1383. }
  1384. if (muf->MocIt || muf->UicIt) {
  1385. sources.emplace_back(muf);
  1386. }
  1387. }
  1388. std::sort(sources.begin(), sources.end(),
  1389. [](MUFile const* a, MUFile const* b) {
  1390. return (a->FullPath < b->FullPath);
  1391. });
  1392. }
  1393. // Info writer
  1394. InfoWriter info;
  1395. // General
  1396. info.SetBool("MULTI_CONFIG", this->MultiConfig);
  1397. info.SetUInt("PARALLEL", this->AutogenTarget.Parallel);
  1398. info.SetUInt("VERBOSITY", this->Verbosity);
  1399. // Directories
  1400. info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
  1401. info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
  1402. info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
  1403. info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
  1404. info.Set("BUILD_DIR", this->Dir.Build);
  1405. info.SetConfig("INCLUDE_DIR", this->Dir.Include);
  1406. info.SetUInt("QT_VERSION_MAJOR", this->QtVersion.Major);
  1407. info.SetUInt("QT_VERSION_MINOR", this->QtVersion.Minor);
  1408. info.Set("QT_MOC_EXECUTABLE", this->Moc.Executable);
  1409. info.Set("QT_UIC_EXECUTABLE", this->Uic.Executable);
  1410. info.Set("CMAKE_EXECUTABLE", cmSystemTools::GetCMakeCommand());
  1411. info.SetConfig("SETTINGS_FILE", this->AutogenTarget.SettingsFile);
  1412. info.SetConfig("PARSE_CACHE_FILE", this->AutogenTarget.ParseCacheFile);
  1413. info.Set("DEP_FILE", this->AutogenTarget.DepFile);
  1414. info.Set("DEP_FILE_RULE_NAME", this->AutogenTarget.DepFileRuleName);
  1415. info.SetArray("CMAKE_LIST_FILES", this->Makefile->GetListFiles());
  1416. info.SetArray("HEADER_EXTENSIONS",
  1417. this->Makefile->GetCMakeInstance()->GetHeaderExtensions());
  1418. auto cfgArray = [this](std::vector<size_t> const& configs) -> Json::Value {
  1419. Json::Value value;
  1420. if (!configs.empty()) {
  1421. value = Json::arrayValue;
  1422. for (size_t ci : configs) {
  1423. value.append(this->ConfigsList[ci]);
  1424. }
  1425. }
  1426. return value;
  1427. };
  1428. info.SetArrayArray("HEADERS", headers,
  1429. [this, &cfgArray](Json::Value& jval, MUFile const* muf) {
  1430. jval.resize(4u);
  1431. jval[0u] = muf->FullPath;
  1432. jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm',
  1433. muf->UicIt ? 'U' : 'u');
  1434. jval[2u] = this->GetMocBuildPath(*muf);
  1435. jval[3u] = cfgArray(muf->Configs);
  1436. });
  1437. info.SetArrayArray(
  1438. "SOURCES", sources, [&cfgArray](Json::Value& jval, MUFile const* muf) {
  1439. jval.resize(3u);
  1440. jval[0u] = muf->FullPath;
  1441. jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm', muf->UicIt ? 'U' : 'u');
  1442. jval[2u] = cfgArray(muf->Configs);
  1443. });
  1444. // Write moc settings
  1445. if (this->Moc.Enabled) {
  1446. info.SetArray("MOC_SKIP", moc_skip);
  1447. info.SetConfigArray("MOC_DEFINITIONS", this->Moc.Defines);
  1448. info.SetConfigArray("MOC_INCLUDES", this->Moc.Includes);
  1449. info.SetArray("MOC_OPTIONS", this->Moc.Options);
  1450. info.SetBool("MOC_RELAXED_MODE", this->Moc.RelaxedMode);
  1451. info.SetBool("MOC_PATH_PREFIX", this->Moc.PathPrefix);
  1452. info.SetArray("MOC_MACRO_NAMES", this->Moc.MacroNames);
  1453. info.SetArrayArray(
  1454. "MOC_DEPEND_FILTERS", this->Moc.DependFilters,
  1455. [](Json::Value& jval, std::pair<std::string, std::string> const& pair) {
  1456. jval.resize(2u);
  1457. jval[0u] = pair.first;
  1458. jval[1u] = pair.second;
  1459. });
  1460. info.SetConfig("MOC_COMPILATION_FILE", this->Moc.CompilationFile);
  1461. info.SetArray("MOC_PREDEFS_CMD", this->Moc.PredefsCmd);
  1462. info.SetConfig("MOC_PREDEFS_FILE", this->Moc.PredefsFile);
  1463. }
  1464. // Write uic settings
  1465. if (this->Uic.Enabled) {
  1466. // Add skipped .ui files
  1467. uic_skip.insert(this->Uic.SkipUi.begin(), this->Uic.SkipUi.end());
  1468. info.SetArray("UIC_SKIP", uic_skip);
  1469. info.SetArrayArray("UIC_UI_FILES", this->Uic.UiFilesWithOptions,
  1470. [](Json::Value& jval, UicT::UiFileT const& uiFile) {
  1471. jval.resize(2u);
  1472. jval[0u] = uiFile.first;
  1473. InfoWriter::MakeStringArray(jval[1u], uiFile.second);
  1474. });
  1475. info.SetConfigArray("UIC_OPTIONS", this->Uic.Options);
  1476. info.SetArray("UIC_SEARCH_PATHS", this->Uic.SearchPaths);
  1477. }
  1478. info.Save(this->AutogenTarget.InfoFile);
  1479. return true;
  1480. }
  1481. bool cmQtAutoGenInitializer::SetupWriteRccInfo()
  1482. {
  1483. for (Qrc const& qrc : this->Rcc.Qrcs) {
  1484. // Utility lambdas
  1485. auto MfDef = [this](std::string const& key) {
  1486. return this->Makefile->GetSafeDefinition(key);
  1487. };
  1488. InfoWriter info;
  1489. // General
  1490. info.SetBool("MULTI_CONFIG", this->MultiConfig);
  1491. info.SetUInt("VERBOSITY", this->Verbosity);
  1492. // Files
  1493. info.Set("LOCK_FILE", qrc.LockFile);
  1494. info.SetConfig("SETTINGS_FILE", qrc.SettingsFile);
  1495. // Directories
  1496. info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
  1497. info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
  1498. info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
  1499. info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
  1500. info.Set("BUILD_DIR", this->Dir.Build);
  1501. info.SetConfig("INCLUDE_DIR", this->Dir.Include);
  1502. // rcc executable
  1503. info.Set("RCC_EXECUTABLE", this->Rcc.Executable);
  1504. info.SetArray("RCC_LIST_OPTIONS",
  1505. this->Rcc.ExecutableFeatures->ListOptions);
  1506. // qrc file
  1507. info.Set("SOURCE", qrc.QrcFile);
  1508. info.Set("OUTPUT_CHECKSUM", qrc.QrcPathChecksum);
  1509. info.Set("OUTPUT_NAME", cmSystemTools::GetFilenameName(qrc.OutputFile));
  1510. info.SetArray("OPTIONS", qrc.Options);
  1511. info.SetArray("INPUTS", qrc.Resources);
  1512. info.Save(qrc.InfoFile);
  1513. }
  1514. return true;
  1515. }
  1516. cmSourceFile* cmQtAutoGenInitializer::RegisterGeneratedSource(
  1517. std::string const& filename)
  1518. {
  1519. cmSourceFile* gFile = this->Makefile->GetOrCreateSource(filename, true);
  1520. gFile->MarkAsGenerated();
  1521. gFile->SetProperty("SKIP_AUTOGEN", "1");
  1522. return gFile;
  1523. }
  1524. cmSourceFile* cmQtAutoGenInitializer::AddGeneratedSource(
  1525. std::string const& filename, GenVarsT const& genVars, bool prepend)
  1526. {
  1527. // Register source at makefile
  1528. cmSourceFile* gFile = this->RegisterGeneratedSource(filename);
  1529. // Add source file to target
  1530. this->GenTarget->AddSource(filename, prepend);
  1531. // Add source file to source group
  1532. this->AddToSourceGroup(filename, genVars.GenNameUpper);
  1533. return gFile;
  1534. }
  1535. void cmQtAutoGenInitializer::AddGeneratedSource(ConfigString const& filename,
  1536. GenVarsT const& genVars,
  1537. bool prepend)
  1538. {
  1539. // XXX(xcode-per-cfg-src): Drop the Xcode-specific part of the condition
  1540. // when the Xcode generator supports per-config sources.
  1541. if (!this->MultiConfig || this->GlobalGen->IsXcode()) {
  1542. this->AddGeneratedSource(filename.Default, genVars, prepend);
  1543. return;
  1544. }
  1545. for (auto const& cfg : this->ConfigsList) {
  1546. std::string const& filenameCfg = filename.Config.at(cfg);
  1547. // Register source at makefile
  1548. this->RegisterGeneratedSource(filenameCfg);
  1549. // Add source file to target for this configuration.
  1550. this->GenTarget->AddSource(
  1551. cmStrCat("$<$<CONFIG:"_s, cfg, ">:"_s, filenameCfg, ">"_s), prepend);
  1552. // Add source file to source group
  1553. this->AddToSourceGroup(filenameCfg, genVars.GenNameUpper);
  1554. }
  1555. }
  1556. void cmQtAutoGenInitializer::AddToSourceGroup(std::string const& fileName,
  1557. cm::string_view genNameUpper)
  1558. {
  1559. cmSourceGroup* sourceGroup = nullptr;
  1560. // Acquire source group
  1561. {
  1562. std::string property;
  1563. std::string groupName;
  1564. {
  1565. // Prefer generator specific source group name
  1566. std::initializer_list<std::string> const props{
  1567. cmStrCat(genNameUpper, "_SOURCE_GROUP"), "AUTOGEN_SOURCE_GROUP"
  1568. };
  1569. for (std::string const& prop : props) {
  1570. cmProp propName = this->Makefile->GetState()->GetGlobalProperty(prop);
  1571. if (cmNonempty(propName)) {
  1572. groupName = *propName;
  1573. property = prop;
  1574. break;
  1575. }
  1576. }
  1577. }
  1578. // Generate a source group on demand
  1579. if (!groupName.empty()) {
  1580. sourceGroup = this->Makefile->GetOrCreateSourceGroup(groupName);
  1581. if (sourceGroup == nullptr) {
  1582. cmSystemTools::Error(
  1583. cmStrCat(genNameUpper, " error in ", property,
  1584. ": Could not find or create the source group ",
  1585. cmQtAutoGen::Quoted(groupName)));
  1586. }
  1587. }
  1588. }
  1589. if (sourceGroup != nullptr) {
  1590. sourceGroup->AddGroupFile(fileName);
  1591. }
  1592. }
  1593. void cmQtAutoGenInitializer::AddCleanFile(std::string const& fileName)
  1594. {
  1595. this->GenTarget->Target->AppendProperty("ADDITIONAL_CLEAN_FILES", fileName,
  1596. false);
  1597. }
  1598. void cmQtAutoGenInitializer::ConfigFileNames(ConfigString& configString,
  1599. cm::string_view prefix,
  1600. cm::string_view suffix)
  1601. {
  1602. configString.Default = cmStrCat(prefix, suffix);
  1603. if (this->MultiConfig) {
  1604. for (auto const& cfg : this->ConfigsList) {
  1605. configString.Config[cfg] = cmStrCat(prefix, '_', cfg, suffix);
  1606. }
  1607. }
  1608. }
  1609. void cmQtAutoGenInitializer::ConfigFileNamesAndGenex(
  1610. ConfigString& configString, std::string& genex, cm::string_view const prefix,
  1611. cm::string_view const suffix)
  1612. {
  1613. this->ConfigFileNames(configString, prefix, suffix);
  1614. if (this->MultiConfig) {
  1615. genex = cmStrCat(prefix, "_$<CONFIG>"_s, suffix);
  1616. } else {
  1617. genex = configString.Default;
  1618. }
  1619. }
  1620. void cmQtAutoGenInitializer::ConfigFileClean(ConfigString& configString)
  1621. {
  1622. this->AddCleanFile(configString.Default);
  1623. if (this->MultiConfig) {
  1624. for (auto const& pair : configString.Config) {
  1625. this->AddCleanFile(pair.second);
  1626. }
  1627. }
  1628. }
  1629. std::pair<cmQtAutoGen::IntegerVersion, unsigned int>
  1630. cmQtAutoGenInitializer::GetQtVersion(cmGeneratorTarget const* target)
  1631. {
  1632. // Converts a char ptr to an unsigned int value
  1633. auto toUInt = [](const char* const input) -> unsigned int {
  1634. unsigned long tmp = 0;
  1635. if (input != nullptr && cmStrToULong(input, &tmp)) {
  1636. return static_cast<unsigned int>(tmp);
  1637. }
  1638. return 0u;
  1639. };
  1640. auto toUInt2 = [](cmProp input) -> unsigned int {
  1641. unsigned long tmp = 0;
  1642. if (input != nullptr && cmStrToULong(*input, &tmp)) {
  1643. return static_cast<unsigned int>(tmp);
  1644. }
  1645. return 0u;
  1646. };
  1647. // Initialize return value to a default
  1648. std::pair<IntegerVersion, unsigned int> res(
  1649. IntegerVersion(),
  1650. toUInt(target->GetLinkInterfaceDependentStringProperty("QT_MAJOR_VERSION",
  1651. "")));
  1652. // Acquire known Qt versions
  1653. std::vector<cmQtAutoGen::IntegerVersion> knownQtVersions;
  1654. {
  1655. // Qt version variable prefixes
  1656. static std::initializer_list<
  1657. std::pair<cm::string_view, cm::string_view>> const keys{
  1658. { "Qt6Core_VERSION_MAJOR", "Qt6Core_VERSION_MINOR" },
  1659. { "Qt5Core_VERSION_MAJOR", "Qt5Core_VERSION_MINOR" },
  1660. { "QT_VERSION_MAJOR", "QT_VERSION_MINOR" },
  1661. };
  1662. knownQtVersions.reserve(keys.size() * 2);
  1663. // Adds a version to the result (nullptr safe)
  1664. auto addVersion = [&knownQtVersions, &toUInt2](cmProp major,
  1665. cmProp minor) {
  1666. cmQtAutoGen::IntegerVersion ver(toUInt2(major), toUInt2(minor));
  1667. if (ver.Major != 0) {
  1668. knownQtVersions.emplace_back(ver);
  1669. }
  1670. };
  1671. // Read versions from variables
  1672. for (auto const& keyPair : keys) {
  1673. addVersion(target->Makefile->GetDefinition(std::string(keyPair.first)),
  1674. target->Makefile->GetDefinition(std::string(keyPair.second)));
  1675. }
  1676. // Read versions from directory properties
  1677. for (auto const& keyPair : keys) {
  1678. addVersion(target->Makefile->GetProperty(std::string(keyPair.first)),
  1679. target->Makefile->GetProperty(std::string(keyPair.second)));
  1680. }
  1681. }
  1682. // Evaluate known Qt versions
  1683. if (!knownQtVersions.empty()) {
  1684. if (res.second == 0) {
  1685. // No specific version was requested by the target:
  1686. // Use highest known Qt version.
  1687. res.first = knownQtVersions.at(0);
  1688. } else {
  1689. // Pick a version from the known versions:
  1690. for (auto it : knownQtVersions) {
  1691. if (it.Major == res.second) {
  1692. res.first = it;
  1693. break;
  1694. }
  1695. }
  1696. }
  1697. }
  1698. return res;
  1699. }
  1700. std::string cmQtAutoGenInitializer::GetMocBuildPath(MUFile const& muf)
  1701. {
  1702. std::string res;
  1703. if (!muf.MocIt) {
  1704. return res;
  1705. }
  1706. std::string basePath =
  1707. cmStrCat(this->PathCheckSum.getPart(muf.FullPath), "/moc_",
  1708. FileNameWithoutLastExtension(muf.FullPath));
  1709. res = cmStrCat(basePath, ".cpp");
  1710. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  1711. return res;
  1712. }
  1713. // File name already emitted.
  1714. // Try appending the header suffix to the base path.
  1715. basePath = cmStrCat(basePath, '_', muf.SF->GetExtension());
  1716. res = cmStrCat(basePath, ".cpp");
  1717. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  1718. return res;
  1719. }
  1720. // File name with header extension already emitted.
  1721. // Try adding a number to the base path.
  1722. constexpr std::size_t number_begin = 2;
  1723. constexpr std::size_t number_end = 256;
  1724. for (std::size_t ii = number_begin; ii != number_end; ++ii) {
  1725. res = cmStrCat(basePath, '_', ii, ".cpp");
  1726. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  1727. return res;
  1728. }
  1729. }
  1730. // Output file name conflict (unlikely, but still...)
  1731. cmSystemTools::Error(
  1732. cmStrCat("moc output file name conflict for ", muf.FullPath));
  1733. return res;
  1734. }
  1735. bool cmQtAutoGenInitializer::GetQtExecutable(GenVarsT& genVars,
  1736. const std::string& executable,
  1737. bool ignoreMissingTarget) const
  1738. {
  1739. auto print_err = [this, &genVars](std::string const& err) {
  1740. cmSystemTools::Error(cmStrCat(genVars.GenNameUpper, " for target ",
  1741. this->GenTarget->GetName(), ": ", err));
  1742. };
  1743. // Custom executable
  1744. {
  1745. std::string const prop = cmStrCat(genVars.GenNameUpper, "_EXECUTABLE");
  1746. std::string const& val = this->GenTarget->Target->GetSafeProperty(prop);
  1747. if (!val.empty()) {
  1748. // Evaluate generator expression
  1749. {
  1750. cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
  1751. cmGeneratorExpression ge(lfbt);
  1752. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(val);
  1753. genVars.Executable = cge->Evaluate(this->LocalGen, "");
  1754. }
  1755. if (genVars.Executable.empty() && !ignoreMissingTarget) {
  1756. print_err(prop + " evaluates to an empty value");
  1757. return false;
  1758. }
  1759. // Create empty compiler features.
  1760. genVars.ExecutableFeatures =
  1761. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  1762. return true;
  1763. }
  1764. }
  1765. // Find executable target
  1766. {
  1767. // Find executable target name
  1768. cm::string_view prefix;
  1769. if (this->QtVersion.Major == 4) {
  1770. prefix = "Qt4::";
  1771. } else if (this->QtVersion.Major == 5) {
  1772. prefix = "Qt5::";
  1773. } else if (this->QtVersion.Major == 6) {
  1774. prefix = "Qt6::";
  1775. }
  1776. std::string const targetName = cmStrCat(prefix, executable);
  1777. // Find target
  1778. cmGeneratorTarget* genTarget =
  1779. this->LocalGen->FindGeneratorTargetToUse(targetName);
  1780. if (genTarget != nullptr) {
  1781. genVars.ExecutableTargetName = targetName;
  1782. genVars.ExecutableTarget = genTarget;
  1783. if (genTarget->IsImported()) {
  1784. genVars.Executable = genTarget->ImportedGetLocation("");
  1785. } else {
  1786. genVars.Executable = genTarget->GetLocation("");
  1787. }
  1788. } else {
  1789. if (ignoreMissingTarget) {
  1790. // Create empty compiler features.
  1791. genVars.ExecutableFeatures =
  1792. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  1793. return true;
  1794. }
  1795. print_err(cmStrCat("Could not find ", executable, " executable target ",
  1796. targetName));
  1797. return false;
  1798. }
  1799. }
  1800. // Get executable features
  1801. {
  1802. std::string err;
  1803. genVars.ExecutableFeatures = this->GlobalInitializer->GetCompilerFeatures(
  1804. executable, genVars.Executable, err);
  1805. if (!genVars.ExecutableFeatures) {
  1806. print_err(err);
  1807. return false;
  1808. }
  1809. }
  1810. return true;
  1811. }