cmQtAutoGenInitializer.cxx 61 KB

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