cmQtAutoGenInitializer.cxx 72 KB

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