cmQtAutoGenInitializer.cxx 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127
  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 "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) {
  107. for (cmLinkItem const& item : libs->Libraries) {
  108. cmGeneratorTarget const* depTarget = item.Target;
  109. if (depTarget &&
  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) {
  325. folder = this->Makefile->GetState()->GetGlobalProperty(
  326. "AUTOGEN_TARGETS_FOLDER");
  327. }
  328. // Inherit FOLDER property from target (#13688)
  329. if (!folder) {
  330. folder = this->GenTarget->GetProperty("FOLDER");
  331. }
  332. if (folder) {
  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) {
  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) {
  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) {
  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) {
  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) {
  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.UiFilesNoOptions.emplace_back(fullPath);
  854. } else {
  855. this->Uic.UiFilesWithOptions.emplace_back(fullPath,
  856. cmExpandedList(uicOpts));
  857. }
  858. auto uiHeaderRelativePath = cmSystemTools::RelativePath(
  859. this->LocalGen->GetCurrentSourceDirectory(),
  860. cmSystemTools::GetFilenamePath(fullPath));
  861. // Avoid creating a path containing adjacent slashes
  862. if (!uiHeaderRelativePath.empty() &&
  863. uiHeaderRelativePath.back() != '/') {
  864. uiHeaderRelativePath += '/';
  865. }
  866. auto uiHeaderFilePath = cmStrCat(
  867. '/', uiHeaderRelativePath, "ui_"_s,
  868. cmSystemTools::GetFilenameWithoutLastExtension(fullPath), ".h"_s);
  869. ConfigString uiHeader;
  870. std::string uiHeaderGenex;
  871. this->ConfigFileNamesAndGenex(
  872. uiHeader, uiHeaderGenex, cmStrCat(this->Dir.Build, "/include"_s),
  873. uiHeaderFilePath);
  874. this->Uic.UiHeaders.emplace_back(
  875. std::make_pair(uiHeader, uiHeaderGenex));
  876. } else {
  877. // Register skipped .ui file
  878. this->Uic.SkipUi.insert(fullPath);
  879. }
  880. }
  881. }
  882. }
  883. // Process GENERATED sources and headers
  884. if (this->MocOrUicEnabled() && !this->AutogenTarget.FilesGenerated.empty()) {
  885. if (this->CMP0071Accept) {
  886. // Let the autogen target depend on the GENERATED files
  887. for (MUFile* muf : this->AutogenTarget.FilesGenerated) {
  888. this->AutogenTarget.DependFiles.insert(muf->FullPath);
  889. }
  890. } else if (this->CMP0071Warn) {
  891. cm::string_view property;
  892. if (this->Moc.Enabled && this->Uic.Enabled) {
  893. property = "SKIP_AUTOGEN";
  894. } else if (this->Moc.Enabled) {
  895. property = "SKIP_AUTOMOC";
  896. } else if (this->Uic.Enabled) {
  897. property = "SKIP_AUTOUIC";
  898. }
  899. std::string files;
  900. for (MUFile* muf : this->AutogenTarget.FilesGenerated) {
  901. files += cmStrCat(" ", Quoted(muf->FullPath), '\n');
  902. }
  903. this->Makefile->IssueMessage(
  904. MessageType::AUTHOR_WARNING,
  905. cmStrCat(
  906. cmPolicies::GetPolicyWarning(cmPolicies::CMP0071), '\n',
  907. "For compatibility, CMake is excluding the GENERATED source "
  908. "file(s):\n",
  909. files, "from processing by ",
  910. cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
  911. ". If any of the files should be processed, set CMP0071 to NEW. "
  912. "If any of the files should not be processed, "
  913. "explicitly exclude them by setting the source file property ",
  914. property, ":\n set_property(SOURCE file.h PROPERTY ", property,
  915. " ON)\n"));
  916. }
  917. }
  918. // Generate CMP0100 warning
  919. if (this->MocOrUicEnabled() &&
  920. !this->AutogenTarget.CMP0100HeadersWarn.empty()) {
  921. cm::string_view property;
  922. if (this->Moc.Enabled && this->Uic.Enabled) {
  923. property = "SKIP_AUTOGEN";
  924. } else if (this->Moc.Enabled) {
  925. property = "SKIP_AUTOMOC";
  926. } else if (this->Uic.Enabled) {
  927. property = "SKIP_AUTOUIC";
  928. }
  929. std::string files;
  930. for (cmSourceFile* sf : this->AutogenTarget.CMP0100HeadersWarn) {
  931. files += cmStrCat(" ", Quoted(sf->GetFullPath()), '\n');
  932. }
  933. this->Makefile->IssueMessage(
  934. MessageType::AUTHOR_WARNING,
  935. cmStrCat(
  936. cmPolicies::GetPolicyWarning(cmPolicies::CMP0100), '\n',
  937. "For compatibility, CMake is excluding the header file(s):\n", files,
  938. "from processing by ",
  939. cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
  940. ". If any of the files should be processed, set CMP0100 to NEW. "
  941. "If any of the files should not be processed, "
  942. "explicitly exclude them by setting the source file property ",
  943. property, ":\n set_property(SOURCE file.hh PROPERTY ", property,
  944. " ON)\n"));
  945. }
  946. // Process qrc files
  947. if (!this->Rcc.Qrcs.empty()) {
  948. const bool modernQt = (this->QtVersion.Major >= 5);
  949. // Target rcc options
  950. std::vector<std::string> optionsTarget =
  951. cmExpandedList(this->GenTarget->GetSafeProperty(kw.AUTORCC_OPTIONS));
  952. // Check if file name is unique
  953. for (Qrc& qrc : this->Rcc.Qrcs) {
  954. qrc.Unique = true;
  955. for (Qrc const& qrc2 : this->Rcc.Qrcs) {
  956. if ((&qrc != &qrc2) && (qrc.QrcName == qrc2.QrcName)) {
  957. qrc.Unique = false;
  958. break;
  959. }
  960. }
  961. }
  962. // Path checksum and file names
  963. for (Qrc& qrc : this->Rcc.Qrcs) {
  964. // Path checksum
  965. qrc.QrcPathChecksum = this->PathCheckSum.getPart(qrc.QrcFile);
  966. // Output file name
  967. qrc.OutputFile = cmStrCat(this->Dir.Build, '/', qrc.QrcPathChecksum,
  968. "/qrc_", qrc.QrcName, ".cpp");
  969. std::string const base = cmStrCat(this->Dir.Info, "/AutoRcc_",
  970. qrc.QrcName, '_', qrc.QrcPathChecksum);
  971. qrc.LockFile = cmStrCat(base, "_Lock.lock");
  972. qrc.InfoFile = cmStrCat(base, "_Info.json");
  973. this->ConfigFileNames(qrc.SettingsFile, cmStrCat(base, "_Used"), ".txt");
  974. }
  975. // rcc options
  976. for (Qrc& qrc : this->Rcc.Qrcs) {
  977. // Target options
  978. std::vector<std::string> opts = optionsTarget;
  979. // Merge computed "-name XYZ" option
  980. {
  981. std::string name = qrc.QrcName;
  982. // Replace '-' with '_'. The former is not valid for symbol names.
  983. std::replace(name.begin(), name.end(), '-', '_');
  984. if (!qrc.Unique) {
  985. name += cmStrCat('_', qrc.QrcPathChecksum);
  986. }
  987. std::vector<std::string> nameOpts;
  988. nameOpts.emplace_back("-name");
  989. nameOpts.emplace_back(std::move(name));
  990. RccMergeOptions(opts, nameOpts, modernQt);
  991. }
  992. // Merge file option
  993. RccMergeOptions(opts, qrc.Options, modernQt);
  994. qrc.Options = std::move(opts);
  995. }
  996. // rcc resources
  997. for (Qrc& qrc : this->Rcc.Qrcs) {
  998. if (!qrc.Generated) {
  999. std::string error;
  1000. RccLister const lister(this->Rcc.Executable,
  1001. this->Rcc.ExecutableFeatures->ListOptions);
  1002. if (!lister.list(qrc.QrcFile, qrc.Resources, error)) {
  1003. cmSystemTools::Error(error);
  1004. return false;
  1005. }
  1006. }
  1007. }
  1008. }
  1009. return true;
  1010. }
  1011. bool cmQtAutoGenInitializer::InitAutogenTarget()
  1012. {
  1013. // Register info file as generated by CMake
  1014. this->Makefile->AddCMakeOutputFile(this->AutogenTarget.InfoFile);
  1015. // Determine whether to use a depfile for the AUTOGEN target.
  1016. const bool useNinjaDepfile = this->QtVersion >= IntegerVersion(5, 15) &&
  1017. this->GlobalGen->GetName().find("Ninja") != std::string::npos;
  1018. // Files provided by the autogen target
  1019. std::vector<std::string> autogenByproducts;
  1020. std::vector<std::string> timestampByproducts;
  1021. if (this->Moc.Enabled) {
  1022. this->AddGeneratedSource(this->Moc.CompilationFile, this->Moc, true);
  1023. if (useNinjaDepfile) {
  1024. if (this->MultiConfig) {
  1025. // Make all mocs_compilation_<CONFIG>.cpp files byproducts of the
  1026. // ${target}_autogen/timestamp custom command.
  1027. // We cannot just use Moc.CompilationFileGenex here, because that
  1028. // custom command runs cmake_autogen for each configuration.
  1029. for (const auto& p : this->Moc.CompilationFile.Config) {
  1030. timestampByproducts.push_back(p.second);
  1031. }
  1032. } else {
  1033. timestampByproducts.push_back(this->Moc.CompilationFileGenex);
  1034. }
  1035. } else {
  1036. autogenByproducts.push_back(this->Moc.CompilationFileGenex);
  1037. }
  1038. }
  1039. if (this->Uic.Enabled) {
  1040. for (const auto& file : this->Uic.UiHeaders) {
  1041. this->AddGeneratedSource(file.first, this->Uic);
  1042. autogenByproducts.push_back(file.second);
  1043. }
  1044. }
  1045. // Compose target comment
  1046. std::string autogenComment;
  1047. {
  1048. std::string tools;
  1049. if (this->Moc.Enabled) {
  1050. tools += "MOC";
  1051. }
  1052. if (this->Uic.Enabled) {
  1053. if (!tools.empty()) {
  1054. tools += " and ";
  1055. }
  1056. tools += "UIC";
  1057. }
  1058. autogenComment = cmStrCat("Automatic ", tools, " for target ",
  1059. this->GenTarget->GetName());
  1060. }
  1061. // Compose command lines
  1062. // FIXME: Take advantage of our per-config mocs_compilation_$<CONFIG>.cpp
  1063. // instead of fiddling with the include directories
  1064. std::vector<std::string> configs;
  1065. this->GlobalGen->GetQtAutoGenConfigs(configs);
  1066. bool stdPipesUTF8 = true;
  1067. cmCustomCommandLines commandLines;
  1068. for (auto const& config : configs) {
  1069. commandLines.push_back(cmMakeCommandLine(
  1070. { cmSystemTools::GetCMakeCommand(), "-E", "cmake_autogen",
  1071. this->AutogenTarget.InfoFile, config }));
  1072. }
  1073. // Use PRE_BUILD on demand
  1074. bool usePRE_BUILD = false;
  1075. if (this->GlobalGen->GetName().find("Visual Studio") != std::string::npos) {
  1076. // Under VS use a PRE_BUILD event instead of a separate target to
  1077. // reduce the number of targets loaded into the IDE.
  1078. // This also works around a VS 11 bug that may skip updating the target:
  1079. // https://connect.microsoft.com/VisualStudio/feedback/details/769495
  1080. usePRE_BUILD = true;
  1081. }
  1082. // Disable PRE_BUILD in some cases
  1083. if (usePRE_BUILD) {
  1084. // Cannot use PRE_BUILD with file depends
  1085. if (!this->AutogenTarget.DependFiles.empty()) {
  1086. usePRE_BUILD = false;
  1087. }
  1088. // Cannot use PRE_BUILD when a global autogen target is in place
  1089. if (this->AutogenTarget.GlobalTarget) {
  1090. usePRE_BUILD = false;
  1091. }
  1092. }
  1093. // Create the autogen target/command
  1094. if (usePRE_BUILD) {
  1095. // Add additional autogen target dependencies to origin target
  1096. for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
  1097. this->GenTarget->Target->AddUtility(depTarget->GetName(), false,
  1098. this->Makefile);
  1099. }
  1100. if (!this->Uic.UiFilesNoOptions.empty() ||
  1101. !this->Uic.UiFilesWithOptions.empty()) {
  1102. // Add a generated timestamp file
  1103. ConfigString timestampFile;
  1104. std::string timestampFileGenex;
  1105. ConfigFileNamesAndGenex(timestampFile, timestampFileGenex,
  1106. cmStrCat(this->Dir.Build, "/autouic"_s),
  1107. ".stamp"_s);
  1108. this->AddGeneratedSource(timestampFile, this->Uic);
  1109. // Add a step in the pre-build command to touch the timestamp file
  1110. commandLines.push_back(
  1111. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E", "touch",
  1112. timestampFileGenex }));
  1113. // UIC needs to be re-run if any of the known UI files change or the
  1114. // executable itself has been updated
  1115. auto uicDependencies = this->Uic.UiFilesNoOptions;
  1116. for (auto const& uiFile : this->Uic.UiFilesWithOptions) {
  1117. uicDependencies.push_back(uiFile.first);
  1118. }
  1119. AddAutogenExecutableToDependencies(this->Uic, uicDependencies);
  1120. // Add a rule file to cause the target to build if a dependency has
  1121. // changed, which will trigger the pre-build command to run autogen
  1122. std::string no_main_dependency;
  1123. cmCustomCommandLines no_command_lines;
  1124. this->LocalGen->AddCustomCommandToOutput(
  1125. timestampFileGenex, uicDependencies, no_main_dependency,
  1126. no_command_lines, /*comment=*/"", this->Dir.Work.c_str(),
  1127. /*cmp0116=*/cmPolicies::NEW, /*replace=*/false,
  1128. /*escapeOldStyle=*/false, /*uses_terminal=*/false,
  1129. /*command_expand_lists=*/false, /*depfile=*/"", /*job_pool=*/"",
  1130. stdPipesUTF8);
  1131. }
  1132. // Add the pre-build command directly to bypass the OBJECT_LIBRARY
  1133. // rejection in cmMakefile::AddCustomCommandToTarget because we know
  1134. // PRE_BUILD will work for an OBJECT_LIBRARY in this specific case.
  1135. //
  1136. // PRE_BUILD does not support file dependencies!
  1137. const std::vector<std::string> no_output;
  1138. const std::vector<std::string> no_deps;
  1139. cmCustomCommand cc(no_output, autogenByproducts, no_deps, commandLines,
  1140. this->Makefile->GetBacktrace(), autogenComment.c_str(),
  1141. this->Dir.Work.c_str(), stdPipesUTF8);
  1142. cc.SetEscapeOldStyle(false);
  1143. cc.SetEscapeAllowMakeVars(true);
  1144. this->GenTarget->Target->AddPreBuildCommand(std::move(cc));
  1145. } else {
  1146. // Add link library target dependencies to the autogen target
  1147. // dependencies
  1148. if (this->AutogenTarget.DependOrigin) {
  1149. // add_dependencies/addUtility do not support generator expressions.
  1150. // We depend only on the libraries found in all configs therefore.
  1151. std::map<cmGeneratorTarget const*, std::size_t> commonTargets;
  1152. for (std::string const& config : this->ConfigsList) {
  1153. cmLinkImplementationLibraries const* libs =
  1154. this->GenTarget->GetLinkImplementationLibraries(config);
  1155. if (libs) {
  1156. for (cmLinkItem const& item : libs->Libraries) {
  1157. cmGeneratorTarget const* libTarget = item.Target;
  1158. if (libTarget &&
  1159. !StaticLibraryCycle(this->GenTarget, libTarget, config)) {
  1160. // Increment target config count
  1161. commonTargets[libTarget]++;
  1162. }
  1163. }
  1164. }
  1165. }
  1166. for (auto const& item : commonTargets) {
  1167. if (item.second == this->ConfigsList.size()) {
  1168. this->AutogenTarget.DependTargets.insert(item.first->Target);
  1169. }
  1170. }
  1171. }
  1172. std::vector<std::string> dependencies(
  1173. this->AutogenTarget.DependFiles.begin(),
  1174. this->AutogenTarget.DependFiles.end());
  1175. if (useNinjaDepfile) {
  1176. // Create a custom command that generates a timestamp file and
  1177. // has a depfile assigned. The depfile is created by JobDepFilesMergeT.
  1178. //
  1179. // Also create an additional '_autogen_timestamp_deps' that the custom
  1180. // command will depend on. It will have no sources or commands to
  1181. // execute, but it will have dependencies that would originally be
  1182. // assigned to the pre-Qt 5.15 'autogen' target. These dependencies will
  1183. // serve as a list of order-only dependencies for the custom command,
  1184. // without forcing the custom command to re-execute.
  1185. //
  1186. // The dependency tree would then look like
  1187. // '_autogen_timestamp_deps (order-only)' <- '/timestamp' file <-
  1188. // '_autogen' target.
  1189. const auto timestampTargetName =
  1190. cmStrCat(this->GenTarget->GetName(), "_autogen_timestamp_deps");
  1191. std::vector<std::string> timestampTargetProvides;
  1192. cmCustomCommandLines timestampTargetCommandLines;
  1193. // Add additional autogen target dependencies to
  1194. // '_autogen_timestamp_deps'.
  1195. for (const cmTarget* t : this->AutogenTarget.DependTargets) {
  1196. dependencies.push_back(t->GetName());
  1197. }
  1198. cmTarget* timestampTarget = this->LocalGen->AddUtilityCommand(
  1199. timestampTargetName, true, this->Dir.Work.c_str(),
  1200. /*byproducts=*/timestampTargetProvides,
  1201. /*depends=*/dependencies, timestampTargetCommandLines, cmPolicies::NEW,
  1202. false, nullptr);
  1203. this->LocalGen->AddGeneratorTarget(
  1204. cm::make_unique<cmGeneratorTarget>(timestampTarget, this->LocalGen));
  1205. // Set FOLDER property on the timestamp target, so it appears in the
  1206. // appropriate folder in an IDE or in the file api.
  1207. if (!this->TargetsFolder.empty()) {
  1208. timestampTarget->SetProperty("FOLDER", this->TargetsFolder);
  1209. }
  1210. // Make '/timestamp' file depend on '_autogen_timestamp_deps' and on the
  1211. // moc and uic executables (whichever are enabled).
  1212. dependencies.clear();
  1213. dependencies.push_back(timestampTargetName);
  1214. AddAutogenExecutableToDependencies(this->Moc, dependencies);
  1215. AddAutogenExecutableToDependencies(this->Uic, dependencies);
  1216. // Create the custom command that outputs the timestamp file.
  1217. const char timestampFileName[] = "timestamp";
  1218. const std::string outputFile =
  1219. cmStrCat(this->Dir.Build, "/", timestampFileName);
  1220. this->AutogenTarget.DepFile = cmStrCat(this->Dir.Build, "/deps");
  1221. this->AutogenTarget.DepFileRuleName =
  1222. cmStrCat(this->GenTarget->GetName(), "_autogen/", timestampFileName);
  1223. commandLines.push_back(cmMakeCommandLine(
  1224. { cmSystemTools::GetCMakeCommand(), "-E", "touch", outputFile }));
  1225. this->AddGeneratedSource(outputFile, this->Moc);
  1226. const std::string no_main_dependency;
  1227. this->LocalGen->AddCustomCommandToOutput(
  1228. { outputFile }, timestampByproducts, dependencies, no_main_dependency,
  1229. /*implicit_depends=*/{}, commandLines, autogenComment.c_str(),
  1230. this->Dir.Work.c_str(),
  1231. /*cmp0116=*/cmPolicies::NEW, /*replace=*/false,
  1232. /*escapeOldStyle=*/false,
  1233. /*uses_terminal=*/false,
  1234. /*command_expand_lists=*/false, this->AutogenTarget.DepFile, "",
  1235. stdPipesUTF8);
  1236. // Alter variables for the autogen target which now merely wraps the
  1237. // custom command
  1238. dependencies.clear();
  1239. dependencies.push_back(outputFile);
  1240. commandLines.clear();
  1241. autogenComment.clear();
  1242. }
  1243. // Create autogen target
  1244. cmTarget* autogenTarget = this->LocalGen->AddUtilityCommand(
  1245. this->AutogenTarget.Name, true, this->Dir.Work.c_str(),
  1246. /*byproducts=*/autogenByproducts,
  1247. /*depends=*/dependencies, commandLines, cmPolicies::NEW, false,
  1248. autogenComment.c_str());
  1249. // Create autogen generator target
  1250. this->LocalGen->AddGeneratorTarget(
  1251. cm::make_unique<cmGeneratorTarget>(autogenTarget, this->LocalGen));
  1252. // Forward origin utilities to autogen target
  1253. if (this->AutogenTarget.DependOrigin) {
  1254. for (BT<std::pair<std::string, bool>> const& depName :
  1255. this->GenTarget->GetUtilities()) {
  1256. autogenTarget->AddUtility(depName.Value.first, false, this->Makefile);
  1257. }
  1258. }
  1259. if (!useNinjaDepfile) {
  1260. // Add additional autogen target dependencies to autogen target
  1261. for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
  1262. autogenTarget->AddUtility(depTarget->GetName(), false, this->Makefile);
  1263. }
  1264. }
  1265. // Set FOLDER property in autogen target
  1266. if (!this->TargetsFolder.empty()) {
  1267. autogenTarget->SetProperty("FOLDER", this->TargetsFolder);
  1268. }
  1269. // Add autogen target to the origin target dependencies
  1270. this->GenTarget->Target->AddUtility(this->AutogenTarget.Name, false,
  1271. this->Makefile);
  1272. // Add autogen target to the global autogen target dependencies
  1273. if (this->AutogenTarget.GlobalTarget) {
  1274. this->GlobalInitializer->AddToGlobalAutoGen(this->LocalGen,
  1275. this->AutogenTarget.Name);
  1276. }
  1277. }
  1278. return true;
  1279. }
  1280. bool cmQtAutoGenInitializer::InitRccTargets()
  1281. {
  1282. for (Qrc const& qrc : this->Rcc.Qrcs) {
  1283. // Register info file as generated by CMake
  1284. this->Makefile->AddCMakeOutputFile(qrc.InfoFile);
  1285. // Register file at target
  1286. {
  1287. cmSourceFile* sf = this->AddGeneratedSource(qrc.OutputFile, this->Rcc);
  1288. sf->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "On");
  1289. }
  1290. std::vector<std::string> ccOutput;
  1291. ccOutput.push_back(qrc.OutputFile);
  1292. std::vector<std::string> ccDepends;
  1293. // Add the .qrc and info file to the custom command dependencies
  1294. ccDepends.push_back(qrc.QrcFile);
  1295. ccDepends.push_back(qrc.InfoFile);
  1296. bool stdPipesUTF8 = true;
  1297. cmCustomCommandLines commandLines;
  1298. if (this->MultiConfig) {
  1299. // Build for all configurations
  1300. for (std::string const& config : this->ConfigsList) {
  1301. commandLines.push_back(
  1302. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
  1303. "cmake_autorcc", qrc.InfoFile, config }));
  1304. }
  1305. } else {
  1306. commandLines.push_back(
  1307. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
  1308. "cmake_autorcc", qrc.InfoFile, "$<CONFIG>" }));
  1309. }
  1310. std::string ccComment =
  1311. cmStrCat("Automatic RCC for ",
  1312. FileProjectRelativePath(this->Makefile, qrc.QrcFile));
  1313. if (qrc.Generated || this->Rcc.GlobalTarget) {
  1314. // Create custom rcc target
  1315. std::string ccName;
  1316. {
  1317. ccName = cmStrCat(this->GenTarget->GetName(), "_arcc_", qrc.QrcName);
  1318. if (!qrc.Unique) {
  1319. ccName += cmStrCat('_', qrc.QrcPathChecksum);
  1320. }
  1321. cmTarget* autoRccTarget = this->LocalGen->AddUtilityCommand(
  1322. ccName, true, this->Dir.Work.c_str(), ccOutput, ccDepends,
  1323. commandLines, cmPolicies::NEW, false, ccComment.c_str(), false,
  1324. false, "", stdPipesUTF8);
  1325. // Create autogen generator target
  1326. this->LocalGen->AddGeneratorTarget(
  1327. cm::make_unique<cmGeneratorTarget>(autoRccTarget, this->LocalGen));
  1328. // Set FOLDER property in autogen target
  1329. if (!this->TargetsFolder.empty()) {
  1330. autoRccTarget->SetProperty("FOLDER", this->TargetsFolder);
  1331. }
  1332. if (!this->Rcc.ExecutableTargetName.empty()) {
  1333. autoRccTarget->AddUtility(this->Rcc.ExecutableTargetName, false,
  1334. this->Makefile);
  1335. }
  1336. }
  1337. // Add autogen target to the origin target dependencies
  1338. this->GenTarget->Target->AddUtility(ccName, false, this->Makefile);
  1339. // Add autogen target to the global autogen target dependencies
  1340. if (this->Rcc.GlobalTarget) {
  1341. this->GlobalInitializer->AddToGlobalAutoRcc(this->LocalGen, ccName);
  1342. }
  1343. } else {
  1344. // Create custom rcc command
  1345. {
  1346. std::vector<std::string> ccByproducts;
  1347. // Add the resource files to the dependencies
  1348. for (std::string const& fileName : qrc.Resources) {
  1349. // Add resource file to the custom command dependencies
  1350. ccDepends.push_back(fileName);
  1351. }
  1352. if (!this->Rcc.ExecutableTargetName.empty()) {
  1353. ccDepends.push_back(this->Rcc.ExecutableTargetName);
  1354. }
  1355. std::string no_main_dependency;
  1356. cmImplicitDependsList no_implicit_depends;
  1357. this->LocalGen->AddCustomCommandToOutput(
  1358. ccOutput, ccByproducts, ccDepends, no_main_dependency,
  1359. no_implicit_depends, commandLines, ccComment.c_str(),
  1360. this->Dir.Work.c_str(), cmPolicies::NEW, false, true, false, false,
  1361. "", "", stdPipesUTF8);
  1362. }
  1363. // Reconfigure when .qrc file changes
  1364. this->Makefile->AddCMakeDependFile(qrc.QrcFile);
  1365. }
  1366. }
  1367. return true;
  1368. }
  1369. bool cmQtAutoGenInitializer::SetupCustomTargets()
  1370. {
  1371. // Create info directory on demand
  1372. if (!cmSystemTools::MakeDirectory(this->Dir.Info)) {
  1373. cmSystemTools::Error(cmStrCat("AutoGen: Could not create directory: ",
  1374. Quoted(this->Dir.Info)));
  1375. return false;
  1376. }
  1377. // Generate autogen target info file
  1378. if (this->MocOrUicEnabled()) {
  1379. // Write autogen target info files
  1380. if (!this->SetupWriteAutogenInfo()) {
  1381. return false;
  1382. }
  1383. }
  1384. // Write AUTORCC info files
  1385. return !this->Rcc.Enabled || this->SetupWriteRccInfo();
  1386. }
  1387. bool cmQtAutoGenInitializer::SetupWriteAutogenInfo()
  1388. {
  1389. // Utility lambdas
  1390. auto MfDef = [this](std::string const& key) {
  1391. return this->Makefile->GetSafeDefinition(key);
  1392. };
  1393. // Filtered headers and sources
  1394. std::set<std::string> moc_skip;
  1395. std::set<std::string> uic_skip;
  1396. std::vector<MUFile const*> headers;
  1397. std::vector<MUFile const*> sources;
  1398. // Filter headers
  1399. {
  1400. headers.reserve(this->AutogenTarget.Headers.size());
  1401. for (auto const& pair : this->AutogenTarget.Headers) {
  1402. MUFile const* const muf = pair.second.get();
  1403. if (muf->SkipMoc) {
  1404. moc_skip.insert(muf->FullPath);
  1405. }
  1406. if (muf->SkipUic) {
  1407. uic_skip.insert(muf->FullPath);
  1408. }
  1409. if (muf->Generated && !this->CMP0071Accept) {
  1410. continue;
  1411. }
  1412. if (muf->MocIt || muf->UicIt) {
  1413. headers.emplace_back(muf);
  1414. }
  1415. }
  1416. std::sort(headers.begin(), headers.end(),
  1417. [](MUFile const* a, MUFile const* b) {
  1418. return (a->FullPath < b->FullPath);
  1419. });
  1420. }
  1421. // Filter sources
  1422. {
  1423. sources.reserve(this->AutogenTarget.Sources.size());
  1424. for (auto const& pair : this->AutogenTarget.Sources) {
  1425. MUFile const* const muf = pair.second.get();
  1426. if (muf->Generated && !this->CMP0071Accept) {
  1427. continue;
  1428. }
  1429. if (muf->SkipMoc) {
  1430. moc_skip.insert(muf->FullPath);
  1431. }
  1432. if (muf->SkipUic) {
  1433. uic_skip.insert(muf->FullPath);
  1434. }
  1435. if (muf->MocIt || muf->UicIt) {
  1436. sources.emplace_back(muf);
  1437. }
  1438. }
  1439. std::sort(sources.begin(), sources.end(),
  1440. [](MUFile const* a, MUFile const* b) {
  1441. return (a->FullPath < b->FullPath);
  1442. });
  1443. }
  1444. // Info writer
  1445. InfoWriter info;
  1446. // General
  1447. info.SetBool("MULTI_CONFIG", this->MultiConfig);
  1448. info.SetUInt("PARALLEL", this->AutogenTarget.Parallel);
  1449. info.SetUInt("VERBOSITY", this->Verbosity);
  1450. // Directories
  1451. info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
  1452. info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
  1453. info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
  1454. info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
  1455. info.Set("BUILD_DIR", this->Dir.Build);
  1456. info.SetConfig("INCLUDE_DIR", this->Dir.Include);
  1457. info.SetUInt("QT_VERSION_MAJOR", this->QtVersion.Major);
  1458. info.SetUInt("QT_VERSION_MINOR", this->QtVersion.Minor);
  1459. info.Set("QT_MOC_EXECUTABLE", this->Moc.Executable);
  1460. info.Set("QT_UIC_EXECUTABLE", this->Uic.Executable);
  1461. info.Set("CMAKE_EXECUTABLE", cmSystemTools::GetCMakeCommand());
  1462. info.SetConfig("SETTINGS_FILE", this->AutogenTarget.SettingsFile);
  1463. info.SetConfig("PARSE_CACHE_FILE", this->AutogenTarget.ParseCacheFile);
  1464. info.Set("DEP_FILE", this->AutogenTarget.DepFile);
  1465. info.Set("DEP_FILE_RULE_NAME", this->AutogenTarget.DepFileRuleName);
  1466. info.SetArray("CMAKE_LIST_FILES", this->Makefile->GetListFiles());
  1467. info.SetArray("HEADER_EXTENSIONS",
  1468. this->Makefile->GetCMakeInstance()->GetHeaderExtensions());
  1469. auto cfgArray = [this](std::vector<size_t> const& configs) -> Json::Value {
  1470. Json::Value value;
  1471. if (!configs.empty()) {
  1472. value = Json::arrayValue;
  1473. for (size_t ci : configs) {
  1474. value.append(this->ConfigsList[ci]);
  1475. }
  1476. }
  1477. return value;
  1478. };
  1479. info.SetArrayArray("HEADERS", headers,
  1480. [this, &cfgArray](Json::Value& jval, MUFile const* muf) {
  1481. jval.resize(4u);
  1482. jval[0u] = muf->FullPath;
  1483. jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm',
  1484. muf->UicIt ? 'U' : 'u');
  1485. jval[2u] = this->GetMocBuildPath(*muf);
  1486. jval[3u] = cfgArray(muf->Configs);
  1487. });
  1488. info.SetArrayArray(
  1489. "SOURCES", sources, [&cfgArray](Json::Value& jval, MUFile const* muf) {
  1490. jval.resize(3u);
  1491. jval[0u] = muf->FullPath;
  1492. jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm', muf->UicIt ? 'U' : 'u');
  1493. jval[2u] = cfgArray(muf->Configs);
  1494. });
  1495. // Write moc settings
  1496. if (this->Moc.Enabled) {
  1497. info.SetArray("MOC_SKIP", moc_skip);
  1498. info.SetConfigArray("MOC_DEFINITIONS", this->Moc.Defines);
  1499. info.SetConfigArray("MOC_INCLUDES", this->Moc.Includes);
  1500. info.SetArray("MOC_OPTIONS", this->Moc.Options);
  1501. info.SetBool("MOC_RELAXED_MODE", this->Moc.RelaxedMode);
  1502. info.SetBool("MOC_PATH_PREFIX", this->Moc.PathPrefix);
  1503. info.SetArray("MOC_MACRO_NAMES", this->Moc.MacroNames);
  1504. info.SetArrayArray(
  1505. "MOC_DEPEND_FILTERS", this->Moc.DependFilters,
  1506. [](Json::Value& jval, std::pair<std::string, std::string> const& pair) {
  1507. jval.resize(2u);
  1508. jval[0u] = pair.first;
  1509. jval[1u] = pair.second;
  1510. });
  1511. info.SetConfig("MOC_COMPILATION_FILE", this->Moc.CompilationFile);
  1512. info.SetArray("MOC_PREDEFS_CMD", this->Moc.PredefsCmd);
  1513. info.SetConfig("MOC_PREDEFS_FILE", this->Moc.PredefsFile);
  1514. }
  1515. // Write uic settings
  1516. if (this->Uic.Enabled) {
  1517. // Add skipped .ui files
  1518. uic_skip.insert(this->Uic.SkipUi.begin(), this->Uic.SkipUi.end());
  1519. info.SetArray("UIC_SKIP", uic_skip);
  1520. info.SetArrayArray("UIC_UI_FILES", this->Uic.UiFilesWithOptions,
  1521. [](Json::Value& jval, UicT::UiFileT const& uiFile) {
  1522. jval.resize(2u);
  1523. jval[0u] = uiFile.first;
  1524. InfoWriter::MakeStringArray(jval[1u], uiFile.second);
  1525. });
  1526. info.SetConfigArray("UIC_OPTIONS", this->Uic.Options);
  1527. info.SetArray("UIC_SEARCH_PATHS", this->Uic.SearchPaths);
  1528. }
  1529. info.Save(this->AutogenTarget.InfoFile);
  1530. return true;
  1531. }
  1532. bool cmQtAutoGenInitializer::SetupWriteRccInfo()
  1533. {
  1534. for (Qrc const& qrc : this->Rcc.Qrcs) {
  1535. // Utility lambdas
  1536. auto MfDef = [this](std::string const& key) {
  1537. return this->Makefile->GetSafeDefinition(key);
  1538. };
  1539. InfoWriter info;
  1540. // General
  1541. info.SetBool("MULTI_CONFIG", this->MultiConfig);
  1542. info.SetUInt("VERBOSITY", this->Verbosity);
  1543. // Files
  1544. info.Set("LOCK_FILE", qrc.LockFile);
  1545. info.SetConfig("SETTINGS_FILE", qrc.SettingsFile);
  1546. // Directories
  1547. info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
  1548. info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
  1549. info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
  1550. info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
  1551. info.Set("BUILD_DIR", this->Dir.Build);
  1552. info.SetConfig("INCLUDE_DIR", this->Dir.Include);
  1553. // rcc executable
  1554. info.Set("RCC_EXECUTABLE", this->Rcc.Executable);
  1555. info.SetArray("RCC_LIST_OPTIONS",
  1556. this->Rcc.ExecutableFeatures->ListOptions);
  1557. // qrc file
  1558. info.Set("SOURCE", qrc.QrcFile);
  1559. info.Set("OUTPUT_CHECKSUM", qrc.QrcPathChecksum);
  1560. info.Set("OUTPUT_NAME", cmSystemTools::GetFilenameName(qrc.OutputFile));
  1561. info.SetArray("OPTIONS", qrc.Options);
  1562. info.SetArray("INPUTS", qrc.Resources);
  1563. info.Save(qrc.InfoFile);
  1564. }
  1565. return true;
  1566. }
  1567. cmSourceFile* cmQtAutoGenInitializer::RegisterGeneratedSource(
  1568. std::string const& filename)
  1569. {
  1570. cmSourceFile* gFile = this->Makefile->GetOrCreateSource(filename, true);
  1571. gFile->MarkAsGenerated();
  1572. gFile->SetProperty("SKIP_AUTOGEN", "1");
  1573. return gFile;
  1574. }
  1575. cmSourceFile* cmQtAutoGenInitializer::AddGeneratedSource(
  1576. std::string const& filename, GenVarsT const& genVars, bool prepend)
  1577. {
  1578. // Register source at makefile
  1579. cmSourceFile* gFile = this->RegisterGeneratedSource(filename);
  1580. // Add source file to target
  1581. this->GenTarget->AddSource(filename, prepend);
  1582. // Add source file to source group
  1583. this->AddToSourceGroup(filename, genVars.GenNameUpper);
  1584. return gFile;
  1585. }
  1586. void cmQtAutoGenInitializer::AddGeneratedSource(ConfigString const& filename,
  1587. GenVarsT const& genVars,
  1588. bool prepend)
  1589. {
  1590. // XXX(xcode-per-cfg-src): Drop the Xcode-specific part of the condition
  1591. // when the Xcode generator supports per-config sources.
  1592. if (!this->MultiConfig || this->GlobalGen->IsXcode()) {
  1593. this->AddGeneratedSource(filename.Default, genVars, prepend);
  1594. return;
  1595. }
  1596. for (auto const& cfg : this->ConfigsList) {
  1597. std::string const& filenameCfg = filename.Config.at(cfg);
  1598. // Register source at makefile
  1599. this->RegisterGeneratedSource(filenameCfg);
  1600. // Add source file to target for this configuration.
  1601. this->GenTarget->AddSource(
  1602. cmStrCat("$<$<CONFIG:"_s, cfg, ">:"_s, filenameCfg, ">"_s), prepend);
  1603. // Add source file to source group
  1604. this->AddToSourceGroup(filenameCfg, genVars.GenNameUpper);
  1605. }
  1606. }
  1607. void cmQtAutoGenInitializer::AddToSourceGroup(std::string const& fileName,
  1608. cm::string_view genNameUpper)
  1609. {
  1610. cmSourceGroup* sourceGroup = nullptr;
  1611. // Acquire source group
  1612. {
  1613. std::string property;
  1614. std::string groupName;
  1615. {
  1616. // Prefer generator specific source group name
  1617. std::initializer_list<std::string> const props{
  1618. cmStrCat(genNameUpper, "_SOURCE_GROUP"), "AUTOGEN_SOURCE_GROUP"
  1619. };
  1620. for (std::string const& prop : props) {
  1621. cmProp propName = this->Makefile->GetState()->GetGlobalProperty(prop);
  1622. if (cmNonempty(propName)) {
  1623. groupName = *propName;
  1624. property = prop;
  1625. break;
  1626. }
  1627. }
  1628. }
  1629. // Generate a source group on demand
  1630. if (!groupName.empty()) {
  1631. sourceGroup = this->Makefile->GetOrCreateSourceGroup(groupName);
  1632. if (!sourceGroup) {
  1633. cmSystemTools::Error(
  1634. cmStrCat(genNameUpper, " error in ", property,
  1635. ": Could not find or create the source group ",
  1636. cmQtAutoGen::Quoted(groupName)));
  1637. }
  1638. }
  1639. }
  1640. if (sourceGroup) {
  1641. sourceGroup->AddGroupFile(fileName);
  1642. }
  1643. }
  1644. void cmQtAutoGenInitializer::AddCleanFile(std::string const& fileName)
  1645. {
  1646. this->GenTarget->Target->AppendProperty("ADDITIONAL_CLEAN_FILES", fileName,
  1647. false);
  1648. }
  1649. void cmQtAutoGenInitializer::ConfigFileNames(ConfigString& configString,
  1650. cm::string_view prefix,
  1651. cm::string_view suffix)
  1652. {
  1653. configString.Default = cmStrCat(prefix, suffix);
  1654. if (this->MultiConfig) {
  1655. for (auto const& cfg : this->ConfigsList) {
  1656. configString.Config[cfg] = cmStrCat(prefix, '_', cfg, suffix);
  1657. }
  1658. }
  1659. }
  1660. void cmQtAutoGenInitializer::ConfigFileNamesAndGenex(
  1661. ConfigString& configString, std::string& genex, cm::string_view const prefix,
  1662. cm::string_view const suffix)
  1663. {
  1664. this->ConfigFileNames(configString, prefix, suffix);
  1665. if (this->MultiConfig) {
  1666. genex = cmStrCat(prefix, "_$<CONFIG>"_s, suffix);
  1667. } else {
  1668. genex = configString.Default;
  1669. }
  1670. }
  1671. void cmQtAutoGenInitializer::ConfigFileClean(ConfigString& configString)
  1672. {
  1673. this->AddCleanFile(configString.Default);
  1674. if (this->MultiConfig) {
  1675. for (auto const& pair : configString.Config) {
  1676. this->AddCleanFile(pair.second);
  1677. }
  1678. }
  1679. }
  1680. static cmQtAutoGen::IntegerVersion parseMocVersion(std::string str)
  1681. {
  1682. cmQtAutoGen::IntegerVersion result;
  1683. static const std::string prelude = "moc ";
  1684. size_t pos = str.find(prelude);
  1685. if (pos == std::string::npos) {
  1686. return result;
  1687. }
  1688. str.erase(0, prelude.size() + pos);
  1689. std::istringstream iss(str);
  1690. std::string major;
  1691. std::string minor;
  1692. if (!std::getline(iss, major, '.') || !std::getline(iss, minor, '.')) {
  1693. return result;
  1694. }
  1695. result.Major = static_cast<unsigned int>(std::stoi(major));
  1696. result.Minor = static_cast<unsigned int>(std::stoi(minor));
  1697. return result;
  1698. }
  1699. static cmQtAutoGen::IntegerVersion GetMocVersion(
  1700. const std::string& mocExecutablePath)
  1701. {
  1702. std::string capturedStdOut;
  1703. int exitCode;
  1704. if (!cmSystemTools::RunSingleCommand({ mocExecutablePath, "--version" },
  1705. &capturedStdOut, nullptr, &exitCode,
  1706. nullptr, cmSystemTools::OUTPUT_NONE)) {
  1707. return {};
  1708. }
  1709. if (exitCode != 0) {
  1710. return {};
  1711. }
  1712. return parseMocVersion(capturedStdOut);
  1713. }
  1714. static std::string FindMocExecutableFromMocTarget(cmMakefile* makefile,
  1715. unsigned int qtMajorVersion)
  1716. {
  1717. std::string result;
  1718. const std::string mocTargetName =
  1719. "Qt" + std::to_string(qtMajorVersion) + "::moc";
  1720. cmTarget* mocTarget = makefile->FindTargetToUse(mocTargetName);
  1721. if (mocTarget) {
  1722. result = mocTarget->GetSafeProperty("IMPORTED_LOCATION");
  1723. }
  1724. return result;
  1725. }
  1726. std::pair<cmQtAutoGen::IntegerVersion, unsigned int>
  1727. cmQtAutoGenInitializer::GetQtVersion(cmGeneratorTarget const* target,
  1728. std::string mocExecutable)
  1729. {
  1730. // Converts a char ptr to an unsigned int value
  1731. auto toUInt = [](const char* const input) -> unsigned int {
  1732. unsigned long tmp = 0;
  1733. if (input && cmStrToULong(input, &tmp)) {
  1734. return static_cast<unsigned int>(tmp);
  1735. }
  1736. return 0u;
  1737. };
  1738. auto toUInt2 = [](cmProp input) -> unsigned int {
  1739. unsigned long tmp = 0;
  1740. if (input && cmStrToULong(*input, &tmp)) {
  1741. return static_cast<unsigned int>(tmp);
  1742. }
  1743. return 0u;
  1744. };
  1745. // Initialize return value to a default
  1746. std::pair<IntegerVersion, unsigned int> res(
  1747. IntegerVersion(),
  1748. toUInt(target->GetLinkInterfaceDependentStringProperty("QT_MAJOR_VERSION",
  1749. "")));
  1750. // Acquire known Qt versions
  1751. std::vector<cmQtAutoGen::IntegerVersion> knownQtVersions;
  1752. {
  1753. // Qt version variable prefixes
  1754. static std::initializer_list<
  1755. std::pair<cm::string_view, cm::string_view>> const keys{
  1756. { "Qt6Core_VERSION_MAJOR", "Qt6Core_VERSION_MINOR" },
  1757. { "Qt5Core_VERSION_MAJOR", "Qt5Core_VERSION_MINOR" },
  1758. { "QT_VERSION_MAJOR", "QT_VERSION_MINOR" },
  1759. };
  1760. knownQtVersions.reserve(keys.size() * 2);
  1761. // Adds a version to the result (nullptr safe)
  1762. auto addVersion = [&knownQtVersions, &toUInt2](cmProp major,
  1763. cmProp minor) {
  1764. cmQtAutoGen::IntegerVersion ver(toUInt2(major), toUInt2(minor));
  1765. if (ver.Major != 0) {
  1766. knownQtVersions.emplace_back(ver);
  1767. }
  1768. };
  1769. // Read versions from variables
  1770. for (auto const& keyPair : keys) {
  1771. addVersion(target->Makefile->GetDefinition(std::string(keyPair.first)),
  1772. target->Makefile->GetDefinition(std::string(keyPair.second)));
  1773. }
  1774. // Read versions from directory properties
  1775. for (auto const& keyPair : keys) {
  1776. addVersion(target->Makefile->GetProperty(std::string(keyPair.first)),
  1777. target->Makefile->GetProperty(std::string(keyPair.second)));
  1778. }
  1779. }
  1780. // Evaluate known Qt versions
  1781. if (!knownQtVersions.empty()) {
  1782. if (res.second == 0) {
  1783. // No specific version was requested by the target:
  1784. // Use highest known Qt version.
  1785. res.first = knownQtVersions.at(0);
  1786. } else {
  1787. // Pick a version from the known versions:
  1788. for (auto it : knownQtVersions) {
  1789. if (it.Major == res.second) {
  1790. res.first = it;
  1791. break;
  1792. }
  1793. }
  1794. }
  1795. }
  1796. if (res.first.Major == 0) {
  1797. // We could not get the version number from variables or directory
  1798. // properties. This might happen if the find_package call for Qt is wrapped
  1799. // in a function. Try to find the moc executable path from the available
  1800. // targets and call "moc --version" to get the Qt version.
  1801. if (mocExecutable.empty()) {
  1802. mocExecutable =
  1803. FindMocExecutableFromMocTarget(target->Makefile, res.second);
  1804. }
  1805. if (!mocExecutable.empty()) {
  1806. res.first = GetMocVersion(mocExecutable);
  1807. }
  1808. }
  1809. return res;
  1810. }
  1811. std::string cmQtAutoGenInitializer::GetMocBuildPath(MUFile const& muf)
  1812. {
  1813. std::string res;
  1814. if (!muf.MocIt) {
  1815. return res;
  1816. }
  1817. std::string basePath =
  1818. cmStrCat(this->PathCheckSum.getPart(muf.FullPath), "/moc_",
  1819. FileNameWithoutLastExtension(muf.FullPath));
  1820. res = cmStrCat(basePath, ".cpp");
  1821. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  1822. return res;
  1823. }
  1824. // File name already emitted.
  1825. // Try appending the header suffix to the base path.
  1826. basePath = cmStrCat(basePath, '_', muf.SF->GetExtension());
  1827. res = cmStrCat(basePath, ".cpp");
  1828. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  1829. return res;
  1830. }
  1831. // File name with header extension already emitted.
  1832. // Try adding a number to the base path.
  1833. constexpr std::size_t number_begin = 2;
  1834. constexpr std::size_t number_end = 256;
  1835. for (std::size_t ii = number_begin; ii != number_end; ++ii) {
  1836. res = cmStrCat(basePath, '_', ii, ".cpp");
  1837. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  1838. return res;
  1839. }
  1840. }
  1841. // Output file name conflict (unlikely, but still...)
  1842. cmSystemTools::Error(
  1843. cmStrCat("moc output file name conflict for ", muf.FullPath));
  1844. return res;
  1845. }
  1846. bool cmQtAutoGenInitializer::GetQtExecutable(GenVarsT& genVars,
  1847. const std::string& executable,
  1848. bool ignoreMissingTarget) const
  1849. {
  1850. auto print_err = [this, &genVars](std::string const& err) {
  1851. cmSystemTools::Error(cmStrCat(genVars.GenNameUpper, " for target ",
  1852. this->GenTarget->GetName(), ": ", err));
  1853. };
  1854. // Custom executable
  1855. {
  1856. std::string const prop = cmStrCat(genVars.GenNameUpper, "_EXECUTABLE");
  1857. std::string const& val = this->GenTarget->Target->GetSafeProperty(prop);
  1858. if (!val.empty()) {
  1859. // Evaluate generator expression
  1860. {
  1861. cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
  1862. cmGeneratorExpression ge(lfbt);
  1863. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(val);
  1864. genVars.Executable = cge->Evaluate(this->LocalGen, "");
  1865. }
  1866. if (genVars.Executable.empty() && !ignoreMissingTarget) {
  1867. print_err(prop + " evaluates to an empty value");
  1868. return false;
  1869. }
  1870. // Create empty compiler features.
  1871. genVars.ExecutableFeatures =
  1872. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  1873. return true;
  1874. }
  1875. }
  1876. // Find executable target
  1877. {
  1878. // Find executable target name
  1879. cm::string_view prefix;
  1880. if (this->QtVersion.Major == 4) {
  1881. prefix = "Qt4::";
  1882. } else if (this->QtVersion.Major == 5) {
  1883. prefix = "Qt5::";
  1884. } else if (this->QtVersion.Major == 6) {
  1885. prefix = "Qt6::";
  1886. }
  1887. std::string const targetName = cmStrCat(prefix, executable);
  1888. // Find target
  1889. cmGeneratorTarget* genTarget =
  1890. this->LocalGen->FindGeneratorTargetToUse(targetName);
  1891. if (genTarget) {
  1892. genVars.ExecutableTargetName = targetName;
  1893. genVars.ExecutableTarget = genTarget;
  1894. if (genTarget->IsImported()) {
  1895. genVars.Executable = genTarget->ImportedGetLocation("");
  1896. } else {
  1897. genVars.Executable = genTarget->GetLocation("");
  1898. }
  1899. } else {
  1900. if (ignoreMissingTarget) {
  1901. // Create empty compiler features.
  1902. genVars.ExecutableFeatures =
  1903. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  1904. return true;
  1905. }
  1906. print_err(cmStrCat("Could not find ", executable, " executable target ",
  1907. targetName));
  1908. return false;
  1909. }
  1910. }
  1911. // Get executable features
  1912. {
  1913. std::string err;
  1914. genVars.ExecutableFeatures = this->GlobalInitializer->GetCompilerFeatures(
  1915. executable, genVars.Executable, err);
  1916. if (!genVars.ExecutableFeatures) {
  1917. print_err(err);
  1918. return false;
  1919. }
  1920. }
  1921. return true;
  1922. }