cmQtAutoGenInitializer.cxx 60 KB

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