cmQtAutoGenInitializer.cxx 78 KB

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