cmQtAutoGenInitializer.cxx 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915
  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 <cmext/algorithm>
  18. #include <cm3p/json/value.h>
  19. #include <cm3p/json/writer.h>
  20. #include "cmsys/SystemInformation.hxx"
  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 "cmProperty.h"
  34. #include "cmQtAutoGen.h"
  35. #include "cmQtAutoGenGlobalInitializer.h"
  36. #include "cmSourceFile.h"
  37. #include "cmSourceFileLocationKind.h"
  38. #include "cmSourceGroup.h"
  39. #include "cmState.h"
  40. #include "cmStateTypes.h"
  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. cmProp 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 const& prop =
  399. this->GenTarget->GetSafeProperty("AUTOGEN_PARALLEL");
  400. if (prop.empty() || (prop == "AUTO")) {
  401. // Autodetect number of CPUs
  402. this->AutogenTarget.Parallel = GetParallelCPUCount();
  403. } else {
  404. this->AutogenTarget.Parallel = 1;
  405. }
  406. }
  407. // Autogen target info and settings files
  408. {
  409. // Info file
  410. this->AutogenTarget.InfoFile =
  411. cmStrCat(this->Dir.Info, "/AutogenInfo.json");
  412. // Used settings file
  413. ConfigFileNames(this->AutogenTarget.SettingsFile,
  414. cmStrCat(this->Dir.Info, "/AutogenUsed"), ".txt");
  415. ConfigFileClean(this->AutogenTarget.SettingsFile);
  416. // Parse cache file
  417. ConfigFileNames(this->AutogenTarget.ParseCacheFile,
  418. cmStrCat(this->Dir.Info, "/ParseCache"), ".txt");
  419. ConfigFileClean(this->AutogenTarget.ParseCacheFile);
  420. }
  421. // Autogen target: Compute user defined dependencies
  422. {
  423. this->AutogenTarget.DependOrigin =
  424. this->GenTarget->GetPropertyAsBool("AUTOGEN_ORIGIN_DEPENDS");
  425. std::string const& deps =
  426. this->GenTarget->GetSafeProperty("AUTOGEN_TARGET_DEPENDS");
  427. if (!deps.empty()) {
  428. for (std::string const& depName : cmExpandedList(deps)) {
  429. // Allow target and file dependencies
  430. auto* depTarget = this->Makefile->FindTargetToUse(depName);
  431. if (depTarget != nullptr) {
  432. this->AutogenTarget.DependTargets.insert(depTarget);
  433. } else {
  434. this->AutogenTarget.DependFiles.insert(depName);
  435. }
  436. }
  437. }
  438. }
  439. if (this->Moc.Enabled) {
  440. // Path prefix
  441. if (cmIsOn(this->GenTarget->GetSafeProperty("AUTOMOC_PATH_PREFIX"))) {
  442. this->Moc.PathPrefix = true;
  443. }
  444. // CMAKE_AUTOMOC_RELAXED_MODE
  445. if (this->Makefile->IsOn("CMAKE_AUTOMOC_RELAXED_MODE")) {
  446. this->Moc.RelaxedMode = true;
  447. this->Makefile->IssueMessage(
  448. MessageType::AUTHOR_WARNING,
  449. cmStrCat("AUTOMOC: CMAKE_AUTOMOC_RELAXED_MODE is "
  450. "deprecated an will be removed in the future. Consider "
  451. "disabling it and converting the target ",
  452. this->GenTarget->GetName(), " to regular mode."));
  453. }
  454. // Options
  455. cmExpandList(this->GenTarget->GetSafeProperty("AUTOMOC_MOC_OPTIONS"),
  456. this->Moc.Options);
  457. // Filters
  458. cmExpandList(this->GenTarget->GetSafeProperty("AUTOMOC_MACRO_NAMES"),
  459. this->Moc.MacroNames);
  460. {
  461. auto filterList = cmExpandedList(
  462. this->GenTarget->GetSafeProperty("AUTOMOC_DEPEND_FILTERS"));
  463. if ((filterList.size() % 2) != 0) {
  464. cmSystemTools::Error(
  465. cmStrCat("AutoMoc: AUTOMOC_DEPEND_FILTERS predefs size ",
  466. filterList.size(), " is not a multiple of 2."));
  467. return false;
  468. }
  469. this->Moc.DependFilters.reserve(1 + (filterList.size() / 2));
  470. this->Moc.DependFilters.emplace_back(
  471. "Q_PLUGIN_METADATA",
  472. "[\n][ \t]*Q_PLUGIN_METADATA[ \t]*\\("
  473. "[^\\)]*FILE[ \t]*\"([^\"]+)\"");
  474. for (std::size_t ii = 0; ii != filterList.size(); ii += 2) {
  475. this->Moc.DependFilters.emplace_back(filterList[ii],
  476. filterList[ii + 1]);
  477. }
  478. }
  479. }
  480. }
  481. // Init rcc specific settings
  482. if (this->Rcc.Enabled && !InitRcc()) {
  483. return false;
  484. }
  485. // Add autogen include directory to the origin target INCLUDE_DIRECTORIES
  486. if (this->MocOrUicEnabled() || (this->Rcc.Enabled && this->MultiConfig)) {
  487. this->GenTarget->AddIncludeDirectory(this->Dir.IncludeGenExp, true);
  488. }
  489. // Scan files
  490. if (!this->InitScanFiles()) {
  491. return false;
  492. }
  493. // Create autogen target
  494. if (this->MocOrUicEnabled() && !this->InitAutogenTarget()) {
  495. return false;
  496. }
  497. // Create rcc targets
  498. if (this->Rcc.Enabled && !this->InitRccTargets()) {
  499. return false;
  500. }
  501. return true;
  502. }
  503. bool cmQtAutoGenInitializer::InitMoc()
  504. {
  505. // Mocs compilation file
  506. this->Moc.CompilationFile =
  507. cmStrCat(this->Dir.Build, "/mocs_compilation.cpp");
  508. // Moc predefs
  509. if (this->GenTarget->GetPropertyAsBool("AUTOMOC_COMPILER_PREDEFINES") &&
  510. (this->QtVersion >= IntegerVersion(5, 8))) {
  511. // Command
  512. this->Makefile->GetDefExpandList("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 (cm::contains(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 (!cm::contains(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 (!cm::contains(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. bool stdPipesUTF8 = true;
  1004. cmCustomCommandLines commandLines;
  1005. for (auto const& config : configs) {
  1006. commandLines.push_back(cmMakeCommandLine(
  1007. { cmSystemTools::GetCMakeCommand(), "-E", "cmake_autogen",
  1008. this->AutogenTarget.InfoFile, config }));
  1009. }
  1010. // Use PRE_BUILD on demand
  1011. bool usePRE_BUILD = false;
  1012. if (this->GlobalGen->GetName().find("Visual Studio") != std::string::npos) {
  1013. // Under VS use a PRE_BUILD event instead of a separate target to
  1014. // reduce the number of targets loaded into the IDE.
  1015. // This also works around a VS 11 bug that may skip updating the target:
  1016. // https://connect.microsoft.com/VisualStudio/feedback/details/769495
  1017. usePRE_BUILD = true;
  1018. }
  1019. // Disable PRE_BUILD in some cases
  1020. if (usePRE_BUILD) {
  1021. // Cannot use PRE_BUILD with file depends
  1022. if (!this->AutogenTarget.DependFiles.empty()) {
  1023. usePRE_BUILD = false;
  1024. }
  1025. // Cannot use PRE_BUILD when a global autogen target is in place
  1026. if (AutogenTarget.GlobalTarget) {
  1027. usePRE_BUILD = false;
  1028. }
  1029. }
  1030. // Create the autogen target/command
  1031. if (usePRE_BUILD) {
  1032. // Add additional autogen target dependencies to origin target
  1033. for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
  1034. this->GenTarget->Target->AddUtility(depTarget->GetName(), false,
  1035. this->Makefile);
  1036. }
  1037. // Add the pre-build command directly to bypass the OBJECT_LIBRARY
  1038. // rejection in cmMakefile::AddCustomCommandToTarget because we know
  1039. // PRE_BUILD will work for an OBJECT_LIBRARY in this specific case.
  1040. //
  1041. // PRE_BUILD does not support file dependencies!
  1042. const std::vector<std::string> no_output;
  1043. const std::vector<std::string> no_deps;
  1044. cmCustomCommand cc(no_output, autogenProvides, no_deps, commandLines,
  1045. this->Makefile->GetBacktrace(), autogenComment.c_str(),
  1046. this->Dir.Work.c_str(), stdPipesUTF8);
  1047. cc.SetEscapeOldStyle(false);
  1048. cc.SetEscapeAllowMakeVars(true);
  1049. this->GenTarget->Target->AddPreBuildCommand(std::move(cc));
  1050. } else {
  1051. // Add link library target dependencies to the autogen target
  1052. // dependencies
  1053. if (this->AutogenTarget.DependOrigin) {
  1054. // add_dependencies/addUtility do not support generator expressions.
  1055. // We depend only on the libraries found in all configs therefore.
  1056. std::map<cmGeneratorTarget const*, std::size_t> commonTargets;
  1057. for (std::string const& config : this->ConfigsList) {
  1058. cmLinkImplementationLibraries const* libs =
  1059. this->GenTarget->GetLinkImplementationLibraries(config);
  1060. if (libs != nullptr) {
  1061. for (cmLinkItem const& item : libs->Libraries) {
  1062. cmGeneratorTarget const* libTarget = item.Target;
  1063. if ((libTarget != nullptr) &&
  1064. !StaticLibraryCycle(this->GenTarget, libTarget, config)) {
  1065. // Increment target config count
  1066. commonTargets[libTarget]++;
  1067. }
  1068. }
  1069. }
  1070. }
  1071. for (auto const& item : commonTargets) {
  1072. if (item.second == this->ConfigsList.size()) {
  1073. this->AutogenTarget.DependTargets.insert(item.first->Target);
  1074. }
  1075. }
  1076. }
  1077. std::vector<std::string> dependencies(
  1078. this->AutogenTarget.DependFiles.begin(),
  1079. this->AutogenTarget.DependFiles.end());
  1080. const bool useNinjaDepfile = this->QtVersion >= IntegerVersion(5, 15) &&
  1081. this->GlobalGen->GetName().find("Ninja") != std::string::npos;
  1082. if (useNinjaDepfile) {
  1083. // Create a custom command that generates a timestamp file and
  1084. // has a depfile assigned. The depfile is created by JobDepFilesMergeT.
  1085. //
  1086. // Also create an additional '_autogen_timestamp_deps' that the custom
  1087. // command will depend on. It will have no sources or commands to
  1088. // execute, but it will have dependencies that would originally be
  1089. // assigned to the pre-Qt 5.15 'autogen' target. These dependencies will
  1090. // serve as a list of order-only dependencies for the custom command,
  1091. // without forcing the custom command to re-execute.
  1092. //
  1093. // The dependency tree would then look like
  1094. // '_autogen_timestamp_deps (order-only)' <- '/timestamp' file <-
  1095. // '_autogen' target.
  1096. const auto timestampTargetName =
  1097. cmStrCat(this->GenTarget->GetName(), "_autogen_timestamp_deps");
  1098. std::vector<std::string> timestampTargetProvides;
  1099. cmCustomCommandLines timestampTargetCommandLines;
  1100. // Add additional autogen target dependencies to
  1101. // '_autogen_timestamp_deps'.
  1102. for (const cmTarget* t : this->AutogenTarget.DependTargets) {
  1103. dependencies.push_back(t->GetName());
  1104. }
  1105. cmTarget* timestampTarget = this->LocalGen->AddUtilityCommand(
  1106. timestampTargetName, true, this->Dir.Work.c_str(),
  1107. /*byproducts=*/timestampTargetProvides,
  1108. /*depends=*/dependencies, timestampTargetCommandLines, false, nullptr);
  1109. this->LocalGen->AddGeneratorTarget(
  1110. cm::make_unique<cmGeneratorTarget>(timestampTarget, this->LocalGen));
  1111. // Set FOLDER property on the timestamp target, so it appears in the
  1112. // appropriate folder in an IDE or in the file api.
  1113. if (!this->TargetsFolder.empty()) {
  1114. timestampTarget->SetProperty("FOLDER", this->TargetsFolder);
  1115. }
  1116. // Make '/timestamp' file depend on '_autogen_timestamp_deps' and on the
  1117. // moc and uic executables (whichever are enabled).
  1118. dependencies.clear();
  1119. dependencies.push_back(timestampTargetName);
  1120. if (this->Moc.ExecutableTarget != nullptr) {
  1121. dependencies.push_back(this->Moc.ExecutableTarget->Target->GetName());
  1122. } else if (!this->Moc.Executable.empty()) {
  1123. dependencies.push_back(this->Moc.Executable);
  1124. }
  1125. if (this->Uic.ExecutableTarget != nullptr) {
  1126. dependencies.push_back(this->Uic.ExecutableTarget->Target->GetName());
  1127. } else if (!this->Uic.Executable.empty()) {
  1128. dependencies.push_back(this->Uic.Executable);
  1129. }
  1130. // Create the custom command that outputs the timestamp file.
  1131. const char timestampFileName[] = "timestamp";
  1132. const std::string outputFile =
  1133. cmStrCat(this->Dir.Build, "/", timestampFileName);
  1134. this->AutogenTarget.DepFile = cmStrCat(this->Dir.Build, "/deps");
  1135. auto relativeBinaryDir = cmSystemTools::RelativePath(
  1136. this->LocalGen->GetBinaryDirectory(),
  1137. this->LocalGen->GetCurrentBinaryDirectory());
  1138. if (!relativeBinaryDir.empty()) {
  1139. relativeBinaryDir = cmStrCat(relativeBinaryDir, "/");
  1140. }
  1141. this->AutogenTarget.DepFileRuleName =
  1142. cmStrCat(relativeBinaryDir, this->GenTarget->GetName(), "_autogen/",
  1143. timestampFileName);
  1144. commandLines.push_back(cmMakeCommandLine(
  1145. { cmSystemTools::GetCMakeCommand(), "-E", "touch", outputFile }));
  1146. this->AddGeneratedSource(outputFile, this->Moc);
  1147. const std::string no_main_dependency;
  1148. this->LocalGen->AddCustomCommandToOutput(
  1149. outputFile, dependencies, no_main_dependency, commandLines,
  1150. autogenComment.c_str(), this->Dir.Work.c_str(), /*replace=*/false,
  1151. /*escapeOldStyle=*/false,
  1152. /*uses_terminal=*/false,
  1153. /*command_expand_lists=*/false, this->AutogenTarget.DepFile, "",
  1154. stdPipesUTF8);
  1155. // Alter variables for the autogen target which now merely wraps the
  1156. // custom command
  1157. dependencies.clear();
  1158. dependencies.push_back(outputFile);
  1159. commandLines.clear();
  1160. autogenComment.clear();
  1161. }
  1162. // Create autogen target
  1163. cmTarget* autogenTarget = this->LocalGen->AddUtilityCommand(
  1164. this->AutogenTarget.Name, true, this->Dir.Work.c_str(),
  1165. /*byproducts=*/autogenProvides,
  1166. /*depends=*/dependencies, commandLines, false, autogenComment.c_str());
  1167. // Create autogen generator target
  1168. this->LocalGen->AddGeneratorTarget(
  1169. cm::make_unique<cmGeneratorTarget>(autogenTarget, this->LocalGen));
  1170. // Forward origin utilities to autogen target
  1171. if (this->AutogenTarget.DependOrigin) {
  1172. for (BT<std::pair<std::string, bool>> const& depName :
  1173. this->GenTarget->GetUtilities()) {
  1174. autogenTarget->AddUtility(depName.Value.first, false, this->Makefile);
  1175. }
  1176. }
  1177. if (!useNinjaDepfile) {
  1178. // Add additional autogen target dependencies to autogen target
  1179. for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
  1180. autogenTarget->AddUtility(depTarget->GetName(), false, this->Makefile);
  1181. }
  1182. }
  1183. // Set FOLDER property in autogen target
  1184. if (!this->TargetsFolder.empty()) {
  1185. autogenTarget->SetProperty("FOLDER", this->TargetsFolder);
  1186. }
  1187. // Add autogen target to the origin target dependencies
  1188. this->GenTarget->Target->AddUtility(this->AutogenTarget.Name, false,
  1189. this->Makefile);
  1190. // Add autogen target to the global autogen target dependencies
  1191. if (this->AutogenTarget.GlobalTarget) {
  1192. this->GlobalInitializer->AddToGlobalAutoGen(this->LocalGen,
  1193. this->AutogenTarget.Name);
  1194. }
  1195. }
  1196. return true;
  1197. }
  1198. bool cmQtAutoGenInitializer::InitRccTargets()
  1199. {
  1200. for (Qrc const& qrc : this->Rcc.Qrcs) {
  1201. // Register info file as generated by CMake
  1202. this->Makefile->AddCMakeOutputFile(qrc.InfoFile);
  1203. // Register file at target
  1204. {
  1205. cmSourceFile* sf = this->AddGeneratedSource(qrc.OutputFile, this->Rcc);
  1206. sf->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "On");
  1207. }
  1208. std::vector<std::string> ccOutput;
  1209. ccOutput.push_back(qrc.OutputFile);
  1210. std::vector<std::string> ccDepends;
  1211. // Add the .qrc and info file to the custom command dependencies
  1212. ccDepends.push_back(qrc.QrcFile);
  1213. ccDepends.push_back(qrc.InfoFile);
  1214. bool stdPipesUTF8 = true;
  1215. cmCustomCommandLines commandLines;
  1216. if (this->MultiConfig) {
  1217. // Build for all configurations
  1218. for (std::string const& config : this->ConfigsList) {
  1219. commandLines.push_back(
  1220. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
  1221. "cmake_autorcc", qrc.InfoFile, config }));
  1222. }
  1223. } else {
  1224. commandLines.push_back(
  1225. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
  1226. "cmake_autorcc", qrc.InfoFile, "$<CONFIG>" }));
  1227. }
  1228. std::string ccComment =
  1229. cmStrCat("Automatic RCC for ",
  1230. FileProjectRelativePath(this->Makefile, qrc.QrcFile));
  1231. if (qrc.Generated || this->Rcc.GlobalTarget) {
  1232. // Create custom rcc target
  1233. std::string ccName;
  1234. {
  1235. ccName = cmStrCat(this->GenTarget->GetName(), "_arcc_", qrc.QrcName);
  1236. if (!qrc.Unique) {
  1237. ccName += cmStrCat('_', qrc.QrcPathChecksum);
  1238. }
  1239. cmTarget* autoRccTarget = this->LocalGen->AddUtilityCommand(
  1240. ccName, true, this->Dir.Work.c_str(), ccOutput, ccDepends,
  1241. commandLines, false, ccComment.c_str(), false, false, "",
  1242. stdPipesUTF8);
  1243. // Create autogen generator target
  1244. this->LocalGen->AddGeneratorTarget(
  1245. cm::make_unique<cmGeneratorTarget>(autoRccTarget, this->LocalGen));
  1246. // Set FOLDER property in autogen target
  1247. if (!this->TargetsFolder.empty()) {
  1248. autoRccTarget->SetProperty("FOLDER", this->TargetsFolder);
  1249. }
  1250. if (!this->Rcc.ExecutableTargetName.empty()) {
  1251. autoRccTarget->AddUtility(this->Rcc.ExecutableTargetName, false,
  1252. this->Makefile);
  1253. }
  1254. }
  1255. // Add autogen target to the origin target dependencies
  1256. this->GenTarget->Target->AddUtility(ccName, false, this->Makefile);
  1257. // Add autogen target to the global autogen target dependencies
  1258. if (this->Rcc.GlobalTarget) {
  1259. this->GlobalInitializer->AddToGlobalAutoRcc(this->LocalGen, ccName);
  1260. }
  1261. } else {
  1262. // Create custom rcc command
  1263. {
  1264. std::vector<std::string> ccByproducts;
  1265. // Add the resource files to the dependencies
  1266. for (std::string const& fileName : qrc.Resources) {
  1267. // Add resource file to the custom command dependencies
  1268. ccDepends.push_back(fileName);
  1269. }
  1270. if (!this->Rcc.ExecutableTargetName.empty()) {
  1271. ccDepends.push_back(this->Rcc.ExecutableTargetName);
  1272. }
  1273. std::string no_main_dependency;
  1274. cmImplicitDependsList no_implicit_depends;
  1275. this->LocalGen->AddCustomCommandToOutput(
  1276. ccOutput, ccByproducts, ccDepends, no_main_dependency,
  1277. no_implicit_depends, commandLines, ccComment.c_str(),
  1278. this->Dir.Work.c_str(), false, true, false, false, "", "",
  1279. stdPipesUTF8);
  1280. }
  1281. // Reconfigure when .qrc file changes
  1282. this->Makefile->AddCMakeDependFile(qrc.QrcFile);
  1283. }
  1284. }
  1285. return true;
  1286. }
  1287. bool cmQtAutoGenInitializer::SetupCustomTargets()
  1288. {
  1289. // Create info directory on demand
  1290. if (!cmSystemTools::MakeDirectory(this->Dir.Info)) {
  1291. cmSystemTools::Error(cmStrCat("AutoGen: Could not create directory: ",
  1292. Quoted(this->Dir.Info)));
  1293. return false;
  1294. }
  1295. // Generate autogen target info file
  1296. if (this->MocOrUicEnabled()) {
  1297. // Write autogen target info files
  1298. if (!this->SetupWriteAutogenInfo()) {
  1299. return false;
  1300. }
  1301. }
  1302. // Write AUTORCC info files
  1303. return !this->Rcc.Enabled || this->SetupWriteRccInfo();
  1304. }
  1305. bool cmQtAutoGenInitializer::SetupWriteAutogenInfo()
  1306. {
  1307. // Utility lambdas
  1308. auto MfDef = [this](std::string const& key) {
  1309. return this->Makefile->GetSafeDefinition(key);
  1310. };
  1311. // Filtered headers and sources
  1312. std::set<std::string> moc_skip;
  1313. std::set<std::string> uic_skip;
  1314. std::vector<MUFile const*> headers;
  1315. std::vector<MUFile const*> sources;
  1316. // Filter headers
  1317. {
  1318. headers.reserve(this->AutogenTarget.Headers.size());
  1319. for (auto const& pair : this->AutogenTarget.Headers) {
  1320. MUFile const* const muf = pair.second.get();
  1321. if (muf->Generated && !this->CMP0071Accept) {
  1322. continue;
  1323. }
  1324. if (muf->SkipMoc) {
  1325. moc_skip.insert(muf->FullPath);
  1326. }
  1327. if (muf->SkipUic) {
  1328. uic_skip.insert(muf->FullPath);
  1329. }
  1330. if (muf->MocIt || muf->UicIt) {
  1331. headers.emplace_back(muf);
  1332. }
  1333. }
  1334. std::sort(headers.begin(), headers.end(),
  1335. [](MUFile const* a, MUFile const* b) {
  1336. return (a->FullPath < b->FullPath);
  1337. });
  1338. }
  1339. // Filter sources
  1340. {
  1341. sources.reserve(this->AutogenTarget.Sources.size());
  1342. for (auto const& pair : this->AutogenTarget.Sources) {
  1343. MUFile const* const muf = pair.second.get();
  1344. if (muf->Generated && !this->CMP0071Accept) {
  1345. continue;
  1346. }
  1347. if (muf->SkipMoc) {
  1348. moc_skip.insert(muf->FullPath);
  1349. }
  1350. if (muf->SkipUic) {
  1351. uic_skip.insert(muf->FullPath);
  1352. }
  1353. if (muf->MocIt || muf->UicIt) {
  1354. sources.emplace_back(muf);
  1355. }
  1356. }
  1357. std::sort(sources.begin(), sources.end(),
  1358. [](MUFile const* a, MUFile const* b) {
  1359. return (a->FullPath < b->FullPath);
  1360. });
  1361. }
  1362. // Info writer
  1363. InfoWriter info;
  1364. // General
  1365. info.SetBool("MULTI_CONFIG", this->MultiConfig);
  1366. info.SetUInt("PARALLEL", this->AutogenTarget.Parallel);
  1367. info.SetUInt("VERBOSITY", this->Verbosity);
  1368. // Directories
  1369. info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
  1370. info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
  1371. info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
  1372. info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
  1373. info.Set("BUILD_DIR", this->Dir.Build);
  1374. info.SetConfig("INCLUDE_DIR", this->Dir.Include);
  1375. info.SetUInt("QT_VERSION_MAJOR", this->QtVersion.Major);
  1376. info.SetUInt("QT_VERSION_MINOR", this->QtVersion.Minor);
  1377. info.Set("QT_MOC_EXECUTABLE", this->Moc.Executable);
  1378. info.Set("QT_UIC_EXECUTABLE", this->Uic.Executable);
  1379. info.Set("CMAKE_EXECUTABLE", cmSystemTools::GetCMakeCommand());
  1380. info.SetConfig("SETTINGS_FILE", this->AutogenTarget.SettingsFile);
  1381. info.SetConfig("PARSE_CACHE_FILE", this->AutogenTarget.ParseCacheFile);
  1382. info.Set("DEP_FILE", this->AutogenTarget.DepFile);
  1383. info.Set("DEP_FILE_RULE_NAME", this->AutogenTarget.DepFileRuleName);
  1384. info.SetArray("HEADER_EXTENSIONS",
  1385. this->Makefile->GetCMakeInstance()->GetHeaderExtensions());
  1386. info.SetArrayArray(
  1387. "HEADERS", headers, [this](Json::Value& jval, MUFile const* muf) {
  1388. jval.resize(3u);
  1389. jval[0u] = muf->FullPath;
  1390. jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm', muf->UicIt ? 'U' : 'u');
  1391. jval[2u] = this->GetMocBuildPath(*muf);
  1392. });
  1393. info.SetArrayArray(
  1394. "SOURCES", sources, [](Json::Value& jval, MUFile const* muf) {
  1395. jval.resize(2u);
  1396. jval[0u] = muf->FullPath;
  1397. jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm', muf->UicIt ? 'U' : 'u');
  1398. });
  1399. // Write moc settings
  1400. if (this->Moc.Enabled) {
  1401. info.SetArray("MOC_SKIP", moc_skip);
  1402. info.SetConfigArray("MOC_DEFINITIONS", this->Moc.Defines);
  1403. info.SetConfigArray("MOC_INCLUDES", this->Moc.Includes);
  1404. info.SetArray("MOC_OPTIONS", this->Moc.Options);
  1405. info.SetBool("MOC_RELAXED_MODE", this->Moc.RelaxedMode);
  1406. info.SetBool("MOC_PATH_PREFIX", this->Moc.PathPrefix);
  1407. info.SetArray("MOC_MACRO_NAMES", this->Moc.MacroNames);
  1408. info.SetArrayArray(
  1409. "MOC_DEPEND_FILTERS", this->Moc.DependFilters,
  1410. [](Json::Value& jval, std::pair<std::string, std::string> const& pair) {
  1411. jval.resize(2u);
  1412. jval[0u] = pair.first;
  1413. jval[1u] = pair.second;
  1414. });
  1415. info.Set("MOC_COMPILATION_FILE", this->Moc.CompilationFile);
  1416. info.SetArray("MOC_PREDEFS_CMD", this->Moc.PredefsCmd);
  1417. info.SetConfig("MOC_PREDEFS_FILE", this->Moc.PredefsFile);
  1418. }
  1419. // Write uic settings
  1420. if (this->Uic.Enabled) {
  1421. // Add skipped .ui files
  1422. uic_skip.insert(this->Uic.SkipUi.begin(), this->Uic.SkipUi.end());
  1423. info.SetArray("UIC_SKIP", uic_skip);
  1424. info.SetArrayArray("UIC_UI_FILES", this->Uic.UiFiles,
  1425. [](Json::Value& jval, UicT::UiFileT const& uiFile) {
  1426. jval.resize(2u);
  1427. jval[0u] = uiFile.first;
  1428. InfoWriter::MakeStringArray(jval[1u], uiFile.second);
  1429. });
  1430. info.SetConfigArray("UIC_OPTIONS", this->Uic.Options);
  1431. info.SetArray("UIC_SEARCH_PATHS", this->Uic.SearchPaths);
  1432. }
  1433. info.Save(this->AutogenTarget.InfoFile);
  1434. return true;
  1435. }
  1436. bool cmQtAutoGenInitializer::SetupWriteRccInfo()
  1437. {
  1438. for (Qrc const& qrc : this->Rcc.Qrcs) {
  1439. // Utility lambdas
  1440. auto MfDef = [this](std::string const& key) {
  1441. return this->Makefile->GetSafeDefinition(key);
  1442. };
  1443. InfoWriter info;
  1444. // General
  1445. info.SetBool("MULTI_CONFIG", this->MultiConfig);
  1446. info.SetUInt("VERBOSITY", this->Verbosity);
  1447. // Files
  1448. info.Set("LOCK_FILE", qrc.LockFile);
  1449. info.SetConfig("SETTINGS_FILE", qrc.SettingsFile);
  1450. // Directories
  1451. info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
  1452. info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
  1453. info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
  1454. info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
  1455. info.Set("BUILD_DIR", this->Dir.Build);
  1456. info.SetConfig("INCLUDE_DIR", this->Dir.Include);
  1457. // rcc executable
  1458. info.Set("RCC_EXECUTABLE", this->Rcc.Executable);
  1459. info.SetArray("RCC_LIST_OPTIONS",
  1460. this->Rcc.ExecutableFeatures->ListOptions);
  1461. // qrc file
  1462. info.Set("SOURCE", qrc.QrcFile);
  1463. info.Set("OUTPUT_CHECKSUM", qrc.QrcPathChecksum);
  1464. info.Set("OUTPUT_NAME", cmSystemTools::GetFilenameName(qrc.OutputFile));
  1465. info.SetArray("OPTIONS", qrc.Options);
  1466. info.SetArray("INPUTS", qrc.Resources);
  1467. info.Save(qrc.InfoFile);
  1468. }
  1469. return true;
  1470. }
  1471. cmSourceFile* cmQtAutoGenInitializer::RegisterGeneratedSource(
  1472. std::string const& filename)
  1473. {
  1474. cmSourceFile* gFile = this->Makefile->GetOrCreateSource(filename, true);
  1475. gFile->SetProperty("GENERATED", "1");
  1476. gFile->SetProperty("SKIP_AUTOGEN", "1");
  1477. return gFile;
  1478. }
  1479. cmSourceFile* cmQtAutoGenInitializer::AddGeneratedSource(
  1480. std::string const& filename, GenVarsT const& genVars, bool prepend)
  1481. {
  1482. // Register source at makefile
  1483. cmSourceFile* gFile = this->RegisterGeneratedSource(filename);
  1484. // Add source file to target
  1485. this->GenTarget->AddSource(filename, prepend);
  1486. // Add source file to source group
  1487. this->AddToSourceGroup(filename, genVars.GenNameUpper);
  1488. return gFile;
  1489. }
  1490. void cmQtAutoGenInitializer::AddToSourceGroup(std::string const& fileName,
  1491. cm::string_view genNameUpper)
  1492. {
  1493. cmSourceGroup* sourceGroup = nullptr;
  1494. // Acquire source group
  1495. {
  1496. std::string property;
  1497. std::string groupName;
  1498. {
  1499. // Prefer generator specific source group name
  1500. std::initializer_list<std::string> const props{
  1501. cmStrCat(genNameUpper, "_SOURCE_GROUP"), "AUTOGEN_SOURCE_GROUP"
  1502. };
  1503. for (std::string const& prop : props) {
  1504. cmProp propName = this->Makefile->GetState()->GetGlobalProperty(prop);
  1505. if (propName && !propName->empty()) {
  1506. groupName = *propName;
  1507. property = prop;
  1508. break;
  1509. }
  1510. }
  1511. }
  1512. // Generate a source group on demand
  1513. if (!groupName.empty()) {
  1514. sourceGroup = this->Makefile->GetOrCreateSourceGroup(groupName);
  1515. if (sourceGroup == nullptr) {
  1516. cmSystemTools::Error(
  1517. cmStrCat(genNameUpper, " error in ", property,
  1518. ": Could not find or create the source group ",
  1519. cmQtAutoGen::Quoted(groupName)));
  1520. }
  1521. }
  1522. }
  1523. if (sourceGroup != nullptr) {
  1524. sourceGroup->AddGroupFile(fileName);
  1525. }
  1526. }
  1527. void cmQtAutoGenInitializer::AddCleanFile(std::string const& fileName)
  1528. {
  1529. this->GenTarget->Target->AppendProperty("ADDITIONAL_CLEAN_FILES", fileName,
  1530. false);
  1531. }
  1532. void cmQtAutoGenInitializer::ConfigFileNames(ConfigString& configString,
  1533. cm::string_view prefix,
  1534. cm::string_view suffix)
  1535. {
  1536. configString.Default = cmStrCat(prefix, suffix);
  1537. if (this->MultiConfig) {
  1538. for (auto const& cfg : this->ConfigsList) {
  1539. configString.Config[cfg] = cmStrCat(prefix, '_', cfg, suffix);
  1540. }
  1541. }
  1542. }
  1543. void cmQtAutoGenInitializer::ConfigFileClean(ConfigString& configString)
  1544. {
  1545. this->AddCleanFile(configString.Default);
  1546. if (this->MultiConfig) {
  1547. for (auto const& pair : configString.Config) {
  1548. this->AddCleanFile(pair.second);
  1549. }
  1550. }
  1551. }
  1552. std::pair<cmQtAutoGen::IntegerVersion, unsigned int>
  1553. cmQtAutoGenInitializer::GetQtVersion(cmGeneratorTarget const* target)
  1554. {
  1555. // Converts a char ptr to an unsigned int value
  1556. auto toUInt = [](const char* const input) -> unsigned int {
  1557. unsigned long tmp = 0;
  1558. if (input != nullptr && cmStrToULong(input, &tmp)) {
  1559. return static_cast<unsigned int>(tmp);
  1560. }
  1561. return 0u;
  1562. };
  1563. auto toUInt2 = [](cmProp input) -> unsigned int {
  1564. unsigned long tmp = 0;
  1565. if (input != nullptr && cmStrToULong(*input, &tmp)) {
  1566. return static_cast<unsigned int>(tmp);
  1567. }
  1568. return 0u;
  1569. };
  1570. // Initialize return value to a default
  1571. std::pair<IntegerVersion, unsigned int> res(
  1572. IntegerVersion(),
  1573. toUInt(target->GetLinkInterfaceDependentStringProperty("QT_MAJOR_VERSION",
  1574. "")));
  1575. // Acquire known Qt versions
  1576. std::vector<cmQtAutoGen::IntegerVersion> knownQtVersions;
  1577. {
  1578. // Qt version variable prefixes
  1579. static std::initializer_list<
  1580. std::pair<cm::string_view, cm::string_view>> const keys{
  1581. { "Qt6Core_VERSION_MAJOR", "Qt6Core_VERSION_MINOR" },
  1582. { "Qt5Core_VERSION_MAJOR", "Qt5Core_VERSION_MINOR" },
  1583. { "QT_VERSION_MAJOR", "QT_VERSION_MINOR" },
  1584. };
  1585. knownQtVersions.reserve(keys.size() * 2);
  1586. // Adds a version to the result (nullptr safe)
  1587. auto addVersion = [&knownQtVersions, &toUInt2](cmProp major,
  1588. cmProp minor) {
  1589. cmQtAutoGen::IntegerVersion ver(toUInt2(major), toUInt2(minor));
  1590. if (ver.Major != 0) {
  1591. knownQtVersions.emplace_back(ver);
  1592. }
  1593. };
  1594. // Read versions from variables
  1595. for (auto const& keyPair : keys) {
  1596. addVersion(target->Makefile->GetDef(std::string(keyPair.first)),
  1597. target->Makefile->GetDef(std::string(keyPair.second)));
  1598. }
  1599. // Read versions from directory properties
  1600. for (auto const& keyPair : keys) {
  1601. addVersion(target->Makefile->GetProperty(std::string(keyPair.first)),
  1602. target->Makefile->GetProperty(std::string(keyPair.second)));
  1603. }
  1604. }
  1605. // Evaluate known Qt versions
  1606. if (!knownQtVersions.empty()) {
  1607. if (res.second == 0) {
  1608. // No specific version was requested by the target:
  1609. // Use highest known Qt version.
  1610. res.first = knownQtVersions.at(0);
  1611. } else {
  1612. // Pick a version from the known versions:
  1613. for (auto it : knownQtVersions) {
  1614. if (it.Major == res.second) {
  1615. res.first = it;
  1616. break;
  1617. }
  1618. }
  1619. }
  1620. }
  1621. return res;
  1622. }
  1623. std::string cmQtAutoGenInitializer::GetMocBuildPath(MUFile const& muf)
  1624. {
  1625. std::string res;
  1626. if (!muf.MocIt) {
  1627. return res;
  1628. }
  1629. std::string basePath =
  1630. cmStrCat(this->PathCheckSum.getPart(muf.FullPath), "/moc_",
  1631. FileNameWithoutLastExtension(muf.FullPath));
  1632. res = cmStrCat(basePath, ".cpp");
  1633. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  1634. return res;
  1635. }
  1636. // File name already emitted.
  1637. // Try appending the header suffix to the base path.
  1638. basePath = cmStrCat(basePath, '_', muf.SF->GetExtension());
  1639. res = cmStrCat(basePath, ".cpp");
  1640. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  1641. return res;
  1642. }
  1643. // File name with header extension already emitted.
  1644. // Try adding a number to the base path.
  1645. constexpr std::size_t number_begin = 2;
  1646. constexpr std::size_t number_end = 256;
  1647. for (std::size_t ii = number_begin; ii != number_end; ++ii) {
  1648. res = cmStrCat(basePath, '_', ii, ".cpp");
  1649. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  1650. return res;
  1651. }
  1652. }
  1653. // Output file name conflict (unlikely, but still...)
  1654. cmSystemTools::Error(
  1655. cmStrCat("moc output file name conflict for ", muf.FullPath));
  1656. return res;
  1657. }
  1658. bool cmQtAutoGenInitializer::GetQtExecutable(GenVarsT& genVars,
  1659. const std::string& executable,
  1660. bool ignoreMissingTarget) const
  1661. {
  1662. auto print_err = [this, &genVars](std::string const& err) {
  1663. cmSystemTools::Error(cmStrCat(genVars.GenNameUpper, " for target ",
  1664. this->GenTarget->GetName(), ": ", err));
  1665. };
  1666. // Custom executable
  1667. {
  1668. std::string const prop = cmStrCat(genVars.GenNameUpper, "_EXECUTABLE");
  1669. std::string const& val = this->GenTarget->Target->GetSafeProperty(prop);
  1670. if (!val.empty()) {
  1671. // Evaluate generator expression
  1672. {
  1673. cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
  1674. cmGeneratorExpression ge(lfbt);
  1675. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(val);
  1676. genVars.Executable = cge->Evaluate(this->LocalGen, "");
  1677. }
  1678. if (genVars.Executable.empty() && !ignoreMissingTarget) {
  1679. print_err(prop + " evaluates to an empty value");
  1680. return false;
  1681. }
  1682. // Create empty compiler features.
  1683. genVars.ExecutableFeatures =
  1684. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  1685. return true;
  1686. }
  1687. }
  1688. // Find executable target
  1689. {
  1690. // Find executable target name
  1691. cm::string_view prefix;
  1692. if (this->QtVersion.Major == 4) {
  1693. prefix = "Qt4::";
  1694. } else if (this->QtVersion.Major == 5) {
  1695. prefix = "Qt5::";
  1696. } else if (this->QtVersion.Major == 6) {
  1697. prefix = "Qt6::";
  1698. }
  1699. std::string const targetName = cmStrCat(prefix, executable);
  1700. // Find target
  1701. cmGeneratorTarget* genTarget =
  1702. this->LocalGen->FindGeneratorTargetToUse(targetName);
  1703. if (genTarget != nullptr) {
  1704. genVars.ExecutableTargetName = targetName;
  1705. genVars.ExecutableTarget = genTarget;
  1706. if (genTarget->IsImported()) {
  1707. genVars.Executable = genTarget->ImportedGetLocation("");
  1708. } else {
  1709. genVars.Executable = genTarget->GetLocation("");
  1710. }
  1711. } else {
  1712. if (ignoreMissingTarget) {
  1713. // Create empty compiler features.
  1714. genVars.ExecutableFeatures =
  1715. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  1716. return true;
  1717. }
  1718. print_err(cmStrCat("Could not find ", executable, " executable target ",
  1719. targetName));
  1720. return false;
  1721. }
  1722. }
  1723. // Get executable features
  1724. {
  1725. std::string err;
  1726. genVars.ExecutableFeatures = this->GlobalInitializer->GetCompilerFeatures(
  1727. executable, genVars.Executable, err);
  1728. if (!genVars.ExecutableFeatures) {
  1729. print_err(err);
  1730. return false;
  1731. }
  1732. }
  1733. return true;
  1734. }