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->GetDefaultConfiguration();
  286. this->ConfigsList =
  287. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  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 folder =
  308. this->Makefile->GetState()->GetGlobalProperty("AUTOMOC_TARGETS_FOLDER");
  309. if (folder == nullptr) {
  310. folder = this->Makefile->GetState()->GetGlobalProperty(
  311. "AUTOGEN_TARGETS_FOLDER");
  312. }
  313. // Inherit FOLDER property from target (#13688)
  314. if (folder == nullptr) {
  315. folder = this->GenTarget->GetProperty("FOLDER");
  316. }
  317. if (folder != nullptr) {
  318. this->TargetsFolder = *folder;
  319. }
  320. }
  321. // Check status of policy CMP0071 regarding handling of GENERATED files
  322. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0071)) {
  323. case cmPolicies::WARN:
  324. // Ignore GENERATED files but warn
  325. this->CMP0071Warn = true;
  326. CM_FALLTHROUGH;
  327. case cmPolicies::OLD:
  328. // Ignore GENERATED files
  329. break;
  330. case cmPolicies::REQUIRED_IF_USED:
  331. case cmPolicies::REQUIRED_ALWAYS:
  332. case cmPolicies::NEW:
  333. // Process GENERATED files
  334. this->CMP0071Accept = true;
  335. break;
  336. }
  337. // Check status of policy CMP0100 regarding handling of .hh headers
  338. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0100)) {
  339. case cmPolicies::WARN:
  340. // Ignore but .hh files but warn
  341. this->CMP0100Warn = true;
  342. CM_FALLTHROUGH;
  343. case cmPolicies::OLD:
  344. // Ignore .hh files
  345. break;
  346. case cmPolicies::REQUIRED_IF_USED:
  347. case cmPolicies::REQUIRED_ALWAYS:
  348. case cmPolicies::NEW:
  349. // Process .hh file
  350. this->CMP0100Accept = true;
  351. break;
  352. }
  353. // Common directories
  354. {
  355. // Collapsed current binary directory
  356. std::string const cbd = cmSystemTools::CollapseFullPath(
  357. std::string(), this->Makefile->GetCurrentBinaryDirectory());
  358. // Info directory
  359. this->Dir.Info = cmStrCat(cbd, "/CMakeFiles/", this->GenTarget->GetName(),
  360. "_autogen.dir");
  361. cmSystemTools::ConvertToUnixSlashes(this->Dir.Info);
  362. // Build directory
  363. this->Dir.Build = this->GenTarget->GetSafeProperty("AUTOGEN_BUILD_DIR");
  364. if (this->Dir.Build.empty()) {
  365. this->Dir.Build =
  366. cmStrCat(cbd, '/', this->GenTarget->GetName(), "_autogen");
  367. }
  368. cmSystemTools::ConvertToUnixSlashes(this->Dir.Build);
  369. // Cleanup build directory
  370. this->AddCleanFile(this->Dir.Build);
  371. // Working directory
  372. this->Dir.Work = cbd;
  373. cmSystemTools::ConvertToUnixSlashes(this->Dir.Work);
  374. // Include directory
  375. ConfigFileNames(this->Dir.Include, cmStrCat(this->Dir.Build, "/include"),
  376. "");
  377. this->Dir.IncludeGenExp = this->Dir.Include.Default;
  378. if (this->MultiConfig) {
  379. this->Dir.IncludeGenExp += "_$<CONFIG>";
  380. }
  381. }
  382. // Moc, Uic and _autogen target settings
  383. if (this->MocOrUicEnabled()) {
  384. // Init moc specific settings
  385. if (this->Moc.Enabled && !InitMoc()) {
  386. return false;
  387. }
  388. // Init uic specific settings
  389. if (this->Uic.Enabled && !InitUic()) {
  390. return false;
  391. }
  392. // Autogen target name
  393. this->AutogenTarget.Name =
  394. cmStrCat(this->GenTarget->GetName(), "_autogen");
  395. // Autogen target parallel processing
  396. {
  397. std::string const& prop =
  398. this->GenTarget->GetSafeProperty("AUTOGEN_PARALLEL");
  399. if (prop.empty() || (prop == "AUTO")) {
  400. // Autodetect number of CPUs
  401. this->AutogenTarget.Parallel = GetParallelCPUCount();
  402. } else {
  403. this->AutogenTarget.Parallel = 1;
  404. }
  405. }
  406. // Autogen target info and settings files
  407. {
  408. // Info file
  409. this->AutogenTarget.InfoFile =
  410. cmStrCat(this->Dir.Info, "/AutogenInfo.json");
  411. // Used settings file
  412. ConfigFileNames(this->AutogenTarget.SettingsFile,
  413. cmStrCat(this->Dir.Info, "/AutogenUsed"), ".txt");
  414. ConfigFileClean(this->AutogenTarget.SettingsFile);
  415. // Parse cache file
  416. ConfigFileNames(this->AutogenTarget.ParseCacheFile,
  417. cmStrCat(this->Dir.Info, "/ParseCache"), ".txt");
  418. ConfigFileClean(this->AutogenTarget.ParseCacheFile);
  419. }
  420. // Autogen target: Compute user defined dependencies
  421. {
  422. this->AutogenTarget.DependOrigin =
  423. this->GenTarget->GetPropertyAsBool("AUTOGEN_ORIGIN_DEPENDS");
  424. std::string const& deps =
  425. this->GenTarget->GetSafeProperty("AUTOGEN_TARGET_DEPENDS");
  426. if (!deps.empty()) {
  427. for (std::string const& depName : cmExpandedList(deps)) {
  428. // Allow target and file dependencies
  429. auto* depTarget = this->Makefile->FindTargetToUse(depName);
  430. if (depTarget != nullptr) {
  431. this->AutogenTarget.DependTargets.insert(depTarget);
  432. } else {
  433. this->AutogenTarget.DependFiles.insert(depName);
  434. }
  435. }
  436. }
  437. }
  438. if (this->Moc.Enabled) {
  439. // Path prefix
  440. if (cmIsOn(this->GenTarget->GetProperty("AUTOMOC_PATH_PREFIX"))) {
  441. this->Moc.PathPrefix = true;
  442. }
  443. // CMAKE_AUTOMOC_RELAXED_MODE
  444. if (this->Makefile->IsOn("CMAKE_AUTOMOC_RELAXED_MODE")) {
  445. this->Moc.RelaxedMode = true;
  446. this->Makefile->IssueMessage(
  447. MessageType::AUTHOR_WARNING,
  448. cmStrCat("AUTOMOC: CMAKE_AUTOMOC_RELAXED_MODE is "
  449. "deprecated an will be removed in the future. Consider "
  450. "disabling it and converting the target ",
  451. this->GenTarget->GetName(), " to regular mode."));
  452. }
  453. // Options
  454. cmExpandList(this->GenTarget->GetSafeProperty("AUTOMOC_MOC_OPTIONS"),
  455. this->Moc.Options);
  456. // Filters
  457. cmExpandList(this->GenTarget->GetSafeProperty("AUTOMOC_MACRO_NAMES"),
  458. this->Moc.MacroNames);
  459. {
  460. auto filterList = cmExpandedList(
  461. this->GenTarget->GetSafeProperty("AUTOMOC_DEPEND_FILTERS"));
  462. if ((filterList.size() % 2) != 0) {
  463. cmSystemTools::Error(
  464. cmStrCat("AutoMoc: AUTOMOC_DEPEND_FILTERS predefs size ",
  465. filterList.size(), " is not a multiple of 2."));
  466. return false;
  467. }
  468. this->Moc.DependFilters.reserve(1 + (filterList.size() / 2));
  469. this->Moc.DependFilters.emplace_back(
  470. "Q_PLUGIN_METADATA",
  471. "[\n][ \t]*Q_PLUGIN_METADATA[ \t]*\\("
  472. "[^\\)]*FILE[ \t]*\"([^\"]+)\"");
  473. for (std::size_t ii = 0; ii != filterList.size(); ii += 2) {
  474. this->Moc.DependFilters.emplace_back(filterList[ii],
  475. filterList[ii + 1]);
  476. }
  477. }
  478. }
  479. }
  480. // Init rcc specific settings
  481. if (this->Rcc.Enabled && !InitRcc()) {
  482. return false;
  483. }
  484. // Add autogen include directory to the origin target INCLUDE_DIRECTORIES
  485. if (this->MocOrUicEnabled() || (this->Rcc.Enabled && this->MultiConfig)) {
  486. this->GenTarget->AddIncludeDirectory(this->Dir.IncludeGenExp, true);
  487. }
  488. // Scan files
  489. if (!this->InitScanFiles()) {
  490. return false;
  491. }
  492. // Create autogen target
  493. if (this->MocOrUicEnabled() && !this->InitAutogenTarget()) {
  494. return false;
  495. }
  496. // Create rcc targets
  497. if (this->Rcc.Enabled && !this->InitRccTargets()) {
  498. return false;
  499. }
  500. return true;
  501. }
  502. bool cmQtAutoGenInitializer::InitMoc()
  503. {
  504. // Mocs compilation file
  505. this->Moc.CompilationFile =
  506. cmStrCat(this->Dir.Build, "/mocs_compilation.cpp");
  507. // Moc predefs
  508. if (this->GenTarget->GetPropertyAsBool("AUTOMOC_COMPILER_PREDEFINES") &&
  509. (this->QtVersion >= IntegerVersion(5, 8))) {
  510. // Command
  511. this->Makefile->GetDefExpandList("CMAKE_CXX_COMPILER_PREDEFINES_COMMAND",
  512. this->Moc.PredefsCmd);
  513. // Header
  514. if (!this->Moc.PredefsCmd.empty()) {
  515. ConfigFileNames(this->Moc.PredefsFile,
  516. cmStrCat(this->Dir.Build, "/moc_predefs"), ".h");
  517. }
  518. }
  519. // Moc includes
  520. {
  521. SearchPathSanitizer sanitizer(this->Makefile);
  522. auto getDirs =
  523. [this, &sanitizer](std::string const& cfg) -> std::vector<std::string> {
  524. // Get the include dirs for this target, without stripping the implicit
  525. // include dirs off, see issue #13667.
  526. std::vector<std::string> dirs;
  527. bool const appendImplicit = (this->QtVersion.Major >= 5);
  528. this->LocalGen->GetIncludeDirectoriesImplicit(
  529. dirs, this->GenTarget, "CXX", cfg, false, appendImplicit);
  530. return sanitizer(dirs);
  531. };
  532. // Default configuration include directories
  533. this->Moc.Includes.Default = getDirs(this->ConfigDefault);
  534. // Other configuration settings
  535. if (this->MultiConfig) {
  536. for (std::string const& cfg : this->ConfigsList) {
  537. std::vector<std::string> dirs = getDirs(cfg);
  538. if (dirs == this->Moc.Includes.Default) {
  539. continue;
  540. }
  541. this->Moc.Includes.Config[cfg] = std::move(dirs);
  542. }
  543. }
  544. }
  545. // Moc compile definitions
  546. {
  547. auto getDefs = [this](std::string const& cfg) -> std::set<std::string> {
  548. std::set<std::string> defines;
  549. this->LocalGen->GetTargetDefines(this->GenTarget, cfg, "CXX", defines);
  550. #ifdef _WIN32
  551. if (this->Moc.PredefsCmd.empty()) {
  552. // Add WIN32 definition if we don't have a moc_predefs.h
  553. defines.insert("WIN32");
  554. }
  555. #endif
  556. return defines;
  557. };
  558. // Default configuration defines
  559. this->Moc.Defines.Default = getDefs(this->ConfigDefault);
  560. // Other configuration defines
  561. if (this->MultiConfig) {
  562. for (std::string const& cfg : this->ConfigsList) {
  563. std::set<std::string> defines = getDefs(cfg);
  564. if (defines == this->Moc.Defines.Default) {
  565. continue;
  566. }
  567. this->Moc.Defines.Config[cfg] = std::move(defines);
  568. }
  569. }
  570. }
  571. // Moc executable
  572. {
  573. if (!this->GetQtExecutable(this->Moc, "moc", false)) {
  574. return false;
  575. }
  576. // Let the _autogen target depend on the moc executable
  577. if (this->Moc.ExecutableTarget != nullptr) {
  578. this->AutogenTarget.DependTargets.insert(
  579. this->Moc.ExecutableTarget->Target);
  580. }
  581. }
  582. return true;
  583. }
  584. bool cmQtAutoGenInitializer::InitUic()
  585. {
  586. // Uic search paths
  587. {
  588. std::string const& usp =
  589. this->GenTarget->GetSafeProperty("AUTOUIC_SEARCH_PATHS");
  590. if (!usp.empty()) {
  591. this->Uic.SearchPaths =
  592. SearchPathSanitizer(this->Makefile)(cmExpandedList(usp));
  593. }
  594. }
  595. // Uic target options
  596. {
  597. auto getOpts = [this](std::string const& cfg) -> std::vector<std::string> {
  598. std::vector<std::string> opts;
  599. this->GenTarget->GetAutoUicOptions(opts, cfg);
  600. return opts;
  601. };
  602. // Default options
  603. this->Uic.Options.Default = getOpts(this->ConfigDefault);
  604. // Configuration specific options
  605. if (this->MultiConfig) {
  606. for (std::string const& cfg : this->ConfigsList) {
  607. std::vector<std::string> options = getOpts(cfg);
  608. if (options == this->Uic.Options.Default) {
  609. continue;
  610. }
  611. this->Uic.Options.Config[cfg] = std::move(options);
  612. }
  613. }
  614. }
  615. // Uic executable
  616. {
  617. if (!this->GetQtExecutable(this->Uic, "uic", true)) {
  618. return false;
  619. }
  620. // Let the _autogen target depend on the uic executable
  621. if (this->Uic.ExecutableTarget != nullptr) {
  622. this->AutogenTarget.DependTargets.insert(
  623. this->Uic.ExecutableTarget->Target);
  624. }
  625. }
  626. return true;
  627. }
  628. bool cmQtAutoGenInitializer::InitRcc()
  629. {
  630. // Rcc executable
  631. {
  632. if (!this->GetQtExecutable(this->Rcc, "rcc", false)) {
  633. return false;
  634. }
  635. // Evaluate test output on demand
  636. CompilerFeatures& features = *this->Rcc.ExecutableFeatures;
  637. if (!features.Evaluated) {
  638. // Look for list options
  639. if (this->QtVersion.Major == 5 || this->QtVersion.Major == 6) {
  640. if (features.HelpOutput.find("--list") != std::string::npos) {
  641. features.ListOptions.emplace_back("--list");
  642. } else if (features.HelpOutput.find("-list") != std::string::npos) {
  643. features.ListOptions.emplace_back("-list");
  644. }
  645. }
  646. // Evaluation finished
  647. features.Evaluated = true;
  648. }
  649. }
  650. return true;
  651. }
  652. bool cmQtAutoGenInitializer::InitScanFiles()
  653. {
  654. cmake const* cm = this->Makefile->GetCMakeInstance();
  655. auto const& kw = this->GlobalInitializer->kw();
  656. auto makeMUFile = [this, &kw](cmSourceFile* sf, std::string const& fullPath,
  657. bool muIt) -> MUFileHandle {
  658. MUFileHandle muf = cm::make_unique<MUFile>();
  659. muf->FullPath = fullPath;
  660. muf->SF = sf;
  661. muf->Generated = sf->GetIsGenerated();
  662. bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
  663. muf->SkipMoc = this->Moc.Enabled &&
  664. (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOMOC));
  665. muf->SkipUic = this->Uic.Enabled &&
  666. (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
  667. if (muIt) {
  668. muf->MocIt = this->Moc.Enabled && !muf->SkipMoc;
  669. muf->UicIt = this->Uic.Enabled && !muf->SkipUic;
  670. }
  671. return muf;
  672. };
  673. auto addMUHeader = [this](MUFileHandle&& muf, cm::string_view extension) {
  674. cmSourceFile* sf = muf->SF;
  675. const bool muIt = (muf->MocIt || muf->UicIt);
  676. if (this->CMP0100Accept || (extension != "hh")) {
  677. // Accept
  678. if (muIt && muf->Generated) {
  679. this->AutogenTarget.FilesGenerated.emplace_back(muf.get());
  680. }
  681. this->AutogenTarget.Headers.emplace(sf, std::move(muf));
  682. } else if (muIt && this->CMP0100Warn) {
  683. // Store file for warning message
  684. this->AutogenTarget.CMP0100HeadersWarn.push_back(sf);
  685. }
  686. };
  687. auto addMUSource = [this](MUFileHandle&& muf) {
  688. if ((muf->MocIt || muf->UicIt) && muf->Generated) {
  689. this->AutogenTarget.FilesGenerated.emplace_back(muf.get());
  690. }
  691. this->AutogenTarget.Sources.emplace(muf->SF, std::move(muf));
  692. };
  693. // Scan through target files
  694. {
  695. // Scan through target files
  696. std::vector<cmSourceFile*> srcFiles;
  697. this->GenTarget->GetConfigCommonSourceFiles(srcFiles);
  698. for (cmSourceFile* sf : srcFiles) {
  699. // sf->GetExtension() is only valid after sf->ResolveFullPath() ...
  700. // Since we're iterating over source files that might be not in the
  701. // target we need to check for path errors (not existing files).
  702. std::string pathError;
  703. std::string const& fullPath = sf->ResolveFullPath(&pathError);
  704. if (!pathError.empty() || fullPath.empty()) {
  705. continue;
  706. }
  707. std::string const& extLower =
  708. cmSystemTools::LowerCase(sf->GetExtension());
  709. // Register files that will be scanned by moc or uic
  710. if (this->MocOrUicEnabled()) {
  711. if (cm->IsAHeaderExtension(extLower)) {
  712. addMUHeader(makeMUFile(sf, fullPath, true), extLower);
  713. } else if (cm->IsACLikeSourceExtension(extLower)) {
  714. addMUSource(makeMUFile(sf, fullPath, true));
  715. }
  716. }
  717. // Register rcc enabled files
  718. if (this->Rcc.Enabled) {
  719. if ((extLower == kw.qrc) && !sf->GetPropertyAsBool(kw.SKIP_AUTOGEN) &&
  720. !sf->GetPropertyAsBool(kw.SKIP_AUTORCC)) {
  721. // Register qrc file
  722. Qrc qrc;
  723. qrc.QrcFile = fullPath;
  724. qrc.QrcName =
  725. cmSystemTools::GetFilenameWithoutLastExtension(qrc.QrcFile);
  726. qrc.Generated = sf->GetIsGenerated();
  727. // RCC options
  728. {
  729. std::string const opts = sf->GetSafeProperty(kw.AUTORCC_OPTIONS);
  730. if (!opts.empty()) {
  731. cmExpandList(opts, qrc.Options);
  732. }
  733. }
  734. this->Rcc.Qrcs.push_back(std::move(qrc));
  735. }
  736. }
  737. }
  738. }
  739. // cmGeneratorTarget::GetConfigCommonSourceFiles computes the target's
  740. // sources meta data cache. Clear it so that OBJECT library targets that
  741. // are AUTOGEN initialized after this target get their added
  742. // mocs_compilation.cpp source acknowledged by this target.
  743. this->GenTarget->ClearSourcesCache();
  744. // For source files find additional headers and private headers
  745. if (this->MocOrUicEnabled()) {
  746. // Header search suffixes and extensions
  747. static std::initializer_list<cm::string_view> const suffixes{ "", "_p" };
  748. auto const& exts = cm->GetHeaderExtensions();
  749. // Scan through sources
  750. for (auto const& pair : this->AutogenTarget.Sources) {
  751. MUFile const& muf = *pair.second;
  752. if (muf.MocIt || muf.UicIt) {
  753. // Search for the default header file and a private header
  754. std::string const& srcFullPath = muf.SF->ResolveFullPath();
  755. std::string basePath = cmStrCat(
  756. cmQtAutoGen::SubDirPrefix(srcFullPath),
  757. cmSystemTools::GetFilenameWithoutLastExtension(srcFullPath));
  758. for (auto const& suffix : suffixes) {
  759. std::string const suffixedPath = cmStrCat(basePath, suffix);
  760. for (auto const& ext : exts) {
  761. std::string fullPath = cmStrCat(suffixedPath, '.', ext);
  762. auto constexpr locationKind = cmSourceFileLocationKind::Known;
  763. cmSourceFile* sf =
  764. this->Makefile->GetSource(fullPath, locationKind);
  765. if (sf != nullptr) {
  766. // Check if we know about this header already
  767. if (cm::contains(this->AutogenTarget.Headers, sf)) {
  768. continue;
  769. }
  770. // We only accept not-GENERATED files that do exist.
  771. if (!sf->GetIsGenerated() &&
  772. !cmSystemTools::FileExists(fullPath)) {
  773. continue;
  774. }
  775. } else if (cmSystemTools::FileExists(fullPath)) {
  776. // Create a new source file for the existing file
  777. sf = this->Makefile->CreateSource(fullPath, false, locationKind);
  778. }
  779. if (sf != nullptr) {
  780. auto eMuf = makeMUFile(sf, fullPath, true);
  781. // Only process moc/uic when the parent is processed as well
  782. if (!muf.MocIt) {
  783. eMuf->MocIt = false;
  784. }
  785. if (!muf.UicIt) {
  786. eMuf->UicIt = false;
  787. }
  788. addMUHeader(std::move(eMuf), ext);
  789. }
  790. }
  791. }
  792. }
  793. }
  794. }
  795. // Scan through all source files in the makefile to extract moc and uic
  796. // parameters. Historically we support non target source file parameters.
  797. // The reason is that their file names might be discovered from source files
  798. // at generation time.
  799. if (this->MocOrUicEnabled()) {
  800. for (const auto& sf : this->Makefile->GetSourceFiles()) {
  801. // sf->GetExtension() is only valid after sf->ResolveFullPath() ...
  802. // Since we're iterating over source files that might be not in the
  803. // target we need to check for path errors (not existing files).
  804. std::string pathError;
  805. std::string const& fullPath = sf->ResolveFullPath(&pathError);
  806. if (!pathError.empty() || fullPath.empty()) {
  807. continue;
  808. }
  809. std::string const& extLower =
  810. cmSystemTools::LowerCase(sf->GetExtension());
  811. if (cm->IsAHeaderExtension(extLower)) {
  812. if (!cm::contains(this->AutogenTarget.Headers, sf.get())) {
  813. auto muf = makeMUFile(sf.get(), fullPath, false);
  814. if (muf->SkipMoc || muf->SkipUic) {
  815. addMUHeader(std::move(muf), extLower);
  816. }
  817. }
  818. } else if (cm->IsACLikeSourceExtension(extLower)) {
  819. if (!cm::contains(this->AutogenTarget.Sources, sf.get())) {
  820. auto muf = makeMUFile(sf.get(), fullPath, false);
  821. if (muf->SkipMoc || muf->SkipUic) {
  822. addMUSource(std::move(muf));
  823. }
  824. }
  825. } else if (this->Uic.Enabled && (extLower == kw.ui)) {
  826. // .ui file
  827. bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
  828. bool const skipUic =
  829. (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
  830. if (!skipUic) {
  831. // Check if the .ui file has uic options
  832. std::string const uicOpts = sf->GetSafeProperty(kw.AUTOUIC_OPTIONS);
  833. if (!uicOpts.empty()) {
  834. this->Uic.UiFiles.emplace_back(fullPath, cmExpandedList(uicOpts));
  835. }
  836. } else {
  837. // Register skipped .ui file
  838. this->Uic.SkipUi.insert(fullPath);
  839. }
  840. }
  841. }
  842. }
  843. // Process GENERATED sources and headers
  844. if (this->MocOrUicEnabled() && !this->AutogenTarget.FilesGenerated.empty()) {
  845. if (this->CMP0071Accept) {
  846. // Let the autogen target depend on the GENERATED files
  847. for (MUFile* muf : this->AutogenTarget.FilesGenerated) {
  848. this->AutogenTarget.DependFiles.insert(muf->FullPath);
  849. }
  850. } else if (this->CMP0071Warn) {
  851. cm::string_view property;
  852. if (this->Moc.Enabled && this->Uic.Enabled) {
  853. property = "SKIP_AUTOGEN";
  854. } else if (this->Moc.Enabled) {
  855. property = "SKIP_AUTOMOC";
  856. } else if (this->Uic.Enabled) {
  857. property = "SKIP_AUTOUIC";
  858. }
  859. std::string files;
  860. for (MUFile* muf : this->AutogenTarget.FilesGenerated) {
  861. files += cmStrCat(" ", Quoted(muf->FullPath), '\n');
  862. }
  863. this->Makefile->IssueMessage(
  864. MessageType::AUTHOR_WARNING,
  865. cmStrCat(
  866. cmPolicies::GetPolicyWarning(cmPolicies::CMP0071), '\n',
  867. "For compatibility, CMake is excluding the GENERATED source "
  868. "file(s):\n",
  869. files, "from processing by ",
  870. cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
  871. ". If any of the files should be processed, set CMP0071 to NEW. "
  872. "If any of the files should not be processed, "
  873. "explicitly exclude them by setting the source file property ",
  874. property, ":\n set_property(SOURCE file.h PROPERTY ", property,
  875. " ON)\n"));
  876. }
  877. }
  878. // Generate CMP0100 warning
  879. if (this->MocOrUicEnabled() &&
  880. !this->AutogenTarget.CMP0100HeadersWarn.empty()) {
  881. cm::string_view property;
  882. if (this->Moc.Enabled && this->Uic.Enabled) {
  883. property = "SKIP_AUTOGEN";
  884. } else if (this->Moc.Enabled) {
  885. property = "SKIP_AUTOMOC";
  886. } else if (this->Uic.Enabled) {
  887. property = "SKIP_AUTOUIC";
  888. }
  889. std::string files;
  890. for (cmSourceFile* sf : this->AutogenTarget.CMP0100HeadersWarn) {
  891. files += cmStrCat(" ", Quoted(sf->GetFullPath()), '\n');
  892. }
  893. this->Makefile->IssueMessage(
  894. MessageType::AUTHOR_WARNING,
  895. cmStrCat(
  896. cmPolicies::GetPolicyWarning(cmPolicies::CMP0100), '\n',
  897. "For compatibility, CMake is excluding the header file(s):\n", files,
  898. "from processing by ",
  899. cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
  900. ". If any of the files should be processed, set CMP0100 to NEW. "
  901. "If any of the files should not be processed, "
  902. "explicitly exclude them by setting the source file property ",
  903. property, ":\n set_property(SOURCE file.hh PROPERTY ", property,
  904. " ON)\n"));
  905. }
  906. // Process qrc files
  907. if (!this->Rcc.Qrcs.empty()) {
  908. const bool modernQt = (this->QtVersion.Major >= 5);
  909. // Target rcc options
  910. std::vector<std::string> optionsTarget =
  911. cmExpandedList(this->GenTarget->GetSafeProperty(kw.AUTORCC_OPTIONS));
  912. // Check if file name is unique
  913. for (Qrc& qrc : this->Rcc.Qrcs) {
  914. qrc.Unique = true;
  915. for (Qrc const& qrc2 : this->Rcc.Qrcs) {
  916. if ((&qrc != &qrc2) && (qrc.QrcName == qrc2.QrcName)) {
  917. qrc.Unique = false;
  918. break;
  919. }
  920. }
  921. }
  922. // Path checksum and file names
  923. for (Qrc& qrc : this->Rcc.Qrcs) {
  924. // Path checksum
  925. qrc.QrcPathChecksum = this->PathCheckSum.getPart(qrc.QrcFile);
  926. // Output file name
  927. qrc.OutputFile = cmStrCat(this->Dir.Build, '/', qrc.QrcPathChecksum,
  928. "/qrc_", qrc.QrcName, ".cpp");
  929. std::string const base = cmStrCat(this->Dir.Info, "/AutoRcc_",
  930. qrc.QrcName, '_', qrc.QrcPathChecksum);
  931. qrc.LockFile = cmStrCat(base, "_Lock.lock");
  932. qrc.InfoFile = cmStrCat(base, "_Info.json");
  933. ConfigFileNames(qrc.SettingsFile, cmStrCat(base, "_Used"), ".txt");
  934. }
  935. // rcc options
  936. for (Qrc& qrc : this->Rcc.Qrcs) {
  937. // Target options
  938. std::vector<std::string> opts = optionsTarget;
  939. // Merge computed "-name XYZ" option
  940. {
  941. std::string name = qrc.QrcName;
  942. // Replace '-' with '_'. The former is not valid for symbol names.
  943. std::replace(name.begin(), name.end(), '-', '_');
  944. if (!qrc.Unique) {
  945. name += cmStrCat('_', qrc.QrcPathChecksum);
  946. }
  947. std::vector<std::string> nameOpts;
  948. nameOpts.emplace_back("-name");
  949. nameOpts.emplace_back(std::move(name));
  950. RccMergeOptions(opts, nameOpts, modernQt);
  951. }
  952. // Merge file option
  953. RccMergeOptions(opts, qrc.Options, modernQt);
  954. qrc.Options = std::move(opts);
  955. }
  956. // rcc resources
  957. for (Qrc& qrc : this->Rcc.Qrcs) {
  958. if (!qrc.Generated) {
  959. std::string error;
  960. RccLister const lister(this->Rcc.Executable,
  961. this->Rcc.ExecutableFeatures->ListOptions);
  962. if (!lister.list(qrc.QrcFile, qrc.Resources, error)) {
  963. cmSystemTools::Error(error);
  964. return false;
  965. }
  966. }
  967. }
  968. }
  969. return true;
  970. }
  971. bool cmQtAutoGenInitializer::InitAutogenTarget()
  972. {
  973. // Register info file as generated by CMake
  974. this->Makefile->AddCMakeOutputFile(this->AutogenTarget.InfoFile);
  975. // Files provided by the autogen target
  976. std::vector<std::string> autogenProvides;
  977. if (this->Moc.Enabled) {
  978. this->AddGeneratedSource(this->Moc.CompilationFile, this->Moc, true);
  979. autogenProvides.push_back(this->Moc.CompilationFile);
  980. }
  981. // Compose target comment
  982. std::string autogenComment;
  983. {
  984. std::string tools;
  985. if (this->Moc.Enabled) {
  986. tools += "MOC";
  987. }
  988. if (this->Uic.Enabled) {
  989. if (!tools.empty()) {
  990. tools += " and ";
  991. }
  992. tools += "UIC";
  993. }
  994. autogenComment = cmStrCat("Automatic ", tools, " for target ",
  995. this->GenTarget->GetName());
  996. }
  997. // Compose command lines
  998. // TODO: Refactor autogen to output a per-config mocs_compilation.cpp instead
  999. // of fiddling with the include directories
  1000. std::vector<std::string> configs;
  1001. this->GlobalGen->GetQtAutoGenConfigs(configs);
  1002. bool stdPipesUTF8 = true;
  1003. cmCustomCommandLines commandLines;
  1004. for (auto const& config : configs) {
  1005. commandLines.push_back(cmMakeCommandLine(
  1006. { cmSystemTools::GetCMakeCommand(), "-E", "cmake_autogen",
  1007. this->AutogenTarget.InfoFile, config }));
  1008. }
  1009. // Use PRE_BUILD on demand
  1010. bool usePRE_BUILD = false;
  1011. if (this->GlobalGen->GetName().find("Visual Studio") != std::string::npos) {
  1012. // Under VS use a PRE_BUILD event instead of a separate target to
  1013. // reduce the number of targets loaded into the IDE.
  1014. // This also works around a VS 11 bug that may skip updating the target:
  1015. // https://connect.microsoft.com/VisualStudio/feedback/details/769495
  1016. usePRE_BUILD = true;
  1017. }
  1018. // Disable PRE_BUILD in some cases
  1019. if (usePRE_BUILD) {
  1020. // Cannot use PRE_BUILD with file depends
  1021. if (!this->AutogenTarget.DependFiles.empty()) {
  1022. usePRE_BUILD = false;
  1023. }
  1024. // Cannot use PRE_BUILD when a global autogen target is in place
  1025. if (AutogenTarget.GlobalTarget) {
  1026. usePRE_BUILD = false;
  1027. }
  1028. }
  1029. // Create the autogen target/command
  1030. if (usePRE_BUILD) {
  1031. // Add additional autogen target dependencies to origin target
  1032. for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
  1033. this->GenTarget->Target->AddUtility(depTarget->GetName(), false,
  1034. this->Makefile);
  1035. }
  1036. // Add the pre-build command directly to bypass the OBJECT_LIBRARY
  1037. // rejection in cmMakefile::AddCustomCommandToTarget because we know
  1038. // PRE_BUILD will work for an OBJECT_LIBRARY in this specific case.
  1039. //
  1040. // PRE_BUILD does not support file dependencies!
  1041. const std::vector<std::string> no_output;
  1042. const std::vector<std::string> no_deps;
  1043. cmCustomCommand cc(no_output, autogenProvides, no_deps, commandLines,
  1044. this->Makefile->GetBacktrace(), autogenComment.c_str(),
  1045. this->Dir.Work.c_str(), stdPipesUTF8);
  1046. cc.SetEscapeOldStyle(false);
  1047. cc.SetEscapeAllowMakeVars(true);
  1048. this->GenTarget->Target->AddPreBuildCommand(std::move(cc));
  1049. } else {
  1050. // Add link library target dependencies to the autogen target
  1051. // dependencies
  1052. if (this->AutogenTarget.DependOrigin) {
  1053. // add_dependencies/addUtility do not support generator expressions.
  1054. // We depend only on the libraries found in all configs therefore.
  1055. std::map<cmGeneratorTarget const*, std::size_t> commonTargets;
  1056. for (std::string const& config : this->ConfigsList) {
  1057. cmLinkImplementationLibraries const* libs =
  1058. this->GenTarget->GetLinkImplementationLibraries(config);
  1059. if (libs != nullptr) {
  1060. for (cmLinkItem const& item : libs->Libraries) {
  1061. cmGeneratorTarget const* libTarget = item.Target;
  1062. if ((libTarget != nullptr) &&
  1063. !StaticLibraryCycle(this->GenTarget, libTarget, config)) {
  1064. // Increment target config count
  1065. commonTargets[libTarget]++;
  1066. }
  1067. }
  1068. }
  1069. }
  1070. for (auto const& item : commonTargets) {
  1071. if (item.second == this->ConfigsList.size()) {
  1072. this->AutogenTarget.DependTargets.insert(item.first->Target);
  1073. }
  1074. }
  1075. }
  1076. std::vector<std::string> dependencies(
  1077. this->AutogenTarget.DependFiles.begin(),
  1078. this->AutogenTarget.DependFiles.end());
  1079. const bool useNinjaDepfile = this->QtVersion >= IntegerVersion(5, 15) &&
  1080. this->GlobalGen->GetName().find("Ninja") != std::string::npos;
  1081. if (useNinjaDepfile) {
  1082. // Create a custom command that generates a timestamp file and
  1083. // has a depfile assigned. The depfile is created by JobDepFilesMergeT.
  1084. //
  1085. // Also create an additional '_autogen_timestamp_deps' that the custom
  1086. // command will depend on. It will have no sources or commands to
  1087. // execute, but it will have dependencies that would originally be
  1088. // assigned to the pre-Qt 5.15 'autogen' target. These dependencies will
  1089. // serve as a list of order-only dependencies for the custom command,
  1090. // without forcing the custom command to re-execute.
  1091. //
  1092. // The dependency tree would then look like
  1093. // '_autogen_timestamp_deps (order-only)' <- '/timestamp' file <-
  1094. // '_autogen' target.
  1095. const auto timestampTargetName =
  1096. cmStrCat(this->GenTarget->GetName(), "_autogen_timestamp_deps");
  1097. std::vector<std::string> timestampTargetProvides;
  1098. cmCustomCommandLines timestampTargetCommandLines;
  1099. // Add additional autogen target dependencies to
  1100. // '_autogen_timestamp_deps'.
  1101. for (const cmTarget* t : this->AutogenTarget.DependTargets) {
  1102. dependencies.push_back(t->GetName());
  1103. }
  1104. cmTarget* timestampTarget = this->LocalGen->AddUtilityCommand(
  1105. timestampTargetName, true, this->Dir.Work.c_str(),
  1106. /*byproducts=*/timestampTargetProvides,
  1107. /*depends=*/dependencies, timestampTargetCommandLines, false, nullptr);
  1108. this->LocalGen->AddGeneratorTarget(
  1109. cm::make_unique<cmGeneratorTarget>(timestampTarget, this->LocalGen));
  1110. // Set FOLDER property on the timestamp target, so it appears in the
  1111. // appropriate folder in an IDE or in the file api.
  1112. if (!this->TargetsFolder.empty()) {
  1113. timestampTarget->SetProperty("FOLDER", this->TargetsFolder);
  1114. }
  1115. // Make '/timestamp' file depend on '_autogen_timestamp_deps' and on the
  1116. // moc and uic executables (whichever are enabled).
  1117. dependencies.clear();
  1118. dependencies.push_back(timestampTargetName);
  1119. if (this->Moc.ExecutableTarget != nullptr) {
  1120. dependencies.push_back(this->Moc.ExecutableTarget->Target->GetName());
  1121. } else if (!this->Moc.Executable.empty()) {
  1122. dependencies.push_back(this->Moc.Executable);
  1123. }
  1124. if (this->Uic.ExecutableTarget != nullptr) {
  1125. dependencies.push_back(this->Uic.ExecutableTarget->Target->GetName());
  1126. } else if (!this->Uic.Executable.empty()) {
  1127. dependencies.push_back(this->Uic.Executable);
  1128. }
  1129. // Create the custom command that outputs the timestamp file.
  1130. const char timestampFileName[] = "timestamp";
  1131. const std::string outputFile =
  1132. cmStrCat(this->Dir.Build, "/", timestampFileName);
  1133. this->AutogenTarget.DepFile = cmStrCat(this->Dir.Build, "/deps");
  1134. auto relativeBinaryDir = cmSystemTools::RelativePath(
  1135. this->LocalGen->GetBinaryDirectory(),
  1136. this->LocalGen->GetCurrentBinaryDirectory());
  1137. if (!relativeBinaryDir.empty()) {
  1138. relativeBinaryDir = cmStrCat(relativeBinaryDir, "/");
  1139. }
  1140. this->AutogenTarget.DepFileRuleName =
  1141. cmStrCat(relativeBinaryDir, this->GenTarget->GetName(), "_autogen/",
  1142. timestampFileName);
  1143. commandLines.push_back(cmMakeCommandLine(
  1144. { cmSystemTools::GetCMakeCommand(), "-E", "touch", outputFile }));
  1145. this->AddGeneratedSource(outputFile, this->Moc);
  1146. const std::string no_main_dependency;
  1147. this->LocalGen->AddCustomCommandToOutput(
  1148. outputFile, dependencies, no_main_dependency, commandLines,
  1149. autogenComment.c_str(), this->Dir.Work.c_str(), /*replace=*/false,
  1150. /*escapeOldStyle=*/false,
  1151. /*uses_terminal=*/false,
  1152. /*command_expand_lists=*/false, this->AutogenTarget.DepFile, "",
  1153. stdPipesUTF8);
  1154. // Alter variables for the autogen target which now merely wraps the
  1155. // custom command
  1156. dependencies.clear();
  1157. dependencies.push_back(outputFile);
  1158. commandLines.clear();
  1159. autogenComment.clear();
  1160. }
  1161. // Create autogen target
  1162. cmTarget* autogenTarget = this->LocalGen->AddUtilityCommand(
  1163. this->AutogenTarget.Name, true, this->Dir.Work.c_str(),
  1164. /*byproducts=*/autogenProvides,
  1165. /*depends=*/dependencies, commandLines, false, autogenComment.c_str());
  1166. // Create autogen generator target
  1167. this->LocalGen->AddGeneratorTarget(
  1168. cm::make_unique<cmGeneratorTarget>(autogenTarget, this->LocalGen));
  1169. // Forward origin utilities to autogen target
  1170. if (this->AutogenTarget.DependOrigin) {
  1171. for (BT<std::pair<std::string, bool>> const& depName :
  1172. this->GenTarget->GetUtilities()) {
  1173. autogenTarget->AddUtility(depName.Value.first, false, this->Makefile);
  1174. }
  1175. }
  1176. if (!useNinjaDepfile) {
  1177. // Add additional autogen target dependencies to autogen target
  1178. for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
  1179. autogenTarget->AddUtility(depTarget->GetName(), false, this->Makefile);
  1180. }
  1181. }
  1182. // Set FOLDER property in autogen target
  1183. if (!this->TargetsFolder.empty()) {
  1184. autogenTarget->SetProperty("FOLDER", this->TargetsFolder);
  1185. }
  1186. // Add autogen target to the origin target dependencies
  1187. this->GenTarget->Target->AddUtility(this->AutogenTarget.Name, false,
  1188. this->Makefile);
  1189. // Add autogen target to the global autogen target dependencies
  1190. if (this->AutogenTarget.GlobalTarget) {
  1191. this->GlobalInitializer->AddToGlobalAutoGen(this->LocalGen,
  1192. this->AutogenTarget.Name);
  1193. }
  1194. }
  1195. return true;
  1196. }
  1197. bool cmQtAutoGenInitializer::InitRccTargets()
  1198. {
  1199. for (Qrc const& qrc : this->Rcc.Qrcs) {
  1200. // Register info file as generated by CMake
  1201. this->Makefile->AddCMakeOutputFile(qrc.InfoFile);
  1202. // Register file at target
  1203. {
  1204. cmSourceFile* sf = this->AddGeneratedSource(qrc.OutputFile, this->Rcc);
  1205. sf->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "On");
  1206. }
  1207. std::vector<std::string> ccOutput;
  1208. ccOutput.push_back(qrc.OutputFile);
  1209. std::vector<std::string> ccDepends;
  1210. // Add the .qrc and info file to the custom command dependencies
  1211. ccDepends.push_back(qrc.QrcFile);
  1212. ccDepends.push_back(qrc.InfoFile);
  1213. bool stdPipesUTF8 = true;
  1214. cmCustomCommandLines commandLines;
  1215. if (this->MultiConfig) {
  1216. // Build for all configurations
  1217. for (std::string const& config : this->ConfigsList) {
  1218. commandLines.push_back(
  1219. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
  1220. "cmake_autorcc", qrc.InfoFile, config }));
  1221. }
  1222. } else {
  1223. commandLines.push_back(
  1224. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
  1225. "cmake_autorcc", qrc.InfoFile, "$<CONFIG>" }));
  1226. }
  1227. std::string ccComment =
  1228. cmStrCat("Automatic RCC for ",
  1229. FileProjectRelativePath(this->Makefile, qrc.QrcFile));
  1230. if (qrc.Generated || this->Rcc.GlobalTarget) {
  1231. // Create custom rcc target
  1232. std::string ccName;
  1233. {
  1234. ccName = cmStrCat(this->GenTarget->GetName(), "_arcc_", qrc.QrcName);
  1235. if (!qrc.Unique) {
  1236. ccName += cmStrCat('_', qrc.QrcPathChecksum);
  1237. }
  1238. cmTarget* autoRccTarget = this->LocalGen->AddUtilityCommand(
  1239. ccName, true, this->Dir.Work.c_str(), ccOutput, ccDepends,
  1240. commandLines, false, ccComment.c_str(), false, false, "",
  1241. stdPipesUTF8);
  1242. // Create autogen generator target
  1243. this->LocalGen->AddGeneratorTarget(
  1244. cm::make_unique<cmGeneratorTarget>(autoRccTarget, this->LocalGen));
  1245. // Set FOLDER property in autogen target
  1246. if (!this->TargetsFolder.empty()) {
  1247. autoRccTarget->SetProperty("FOLDER", this->TargetsFolder);
  1248. }
  1249. if (!this->Rcc.ExecutableTargetName.empty()) {
  1250. autoRccTarget->AddUtility(this->Rcc.ExecutableTargetName, false,
  1251. this->Makefile);
  1252. }
  1253. }
  1254. // Add autogen target to the origin target dependencies
  1255. this->GenTarget->Target->AddUtility(ccName, false, this->Makefile);
  1256. // Add autogen target to the global autogen target dependencies
  1257. if (this->Rcc.GlobalTarget) {
  1258. this->GlobalInitializer->AddToGlobalAutoRcc(this->LocalGen, ccName);
  1259. }
  1260. } else {
  1261. // Create custom rcc command
  1262. {
  1263. std::vector<std::string> ccByproducts;
  1264. // Add the resource files to the dependencies
  1265. for (std::string const& fileName : qrc.Resources) {
  1266. // Add resource file to the custom command dependencies
  1267. ccDepends.push_back(fileName);
  1268. }
  1269. if (!this->Rcc.ExecutableTargetName.empty()) {
  1270. ccDepends.push_back(this->Rcc.ExecutableTargetName);
  1271. }
  1272. std::string no_main_dependency;
  1273. cmImplicitDependsList no_implicit_depends;
  1274. this->LocalGen->AddCustomCommandToOutput(
  1275. ccOutput, ccByproducts, ccDepends, no_main_dependency,
  1276. no_implicit_depends, commandLines, ccComment.c_str(),
  1277. this->Dir.Work.c_str(), false, true, false, false, "", "",
  1278. stdPipesUTF8);
  1279. }
  1280. // Reconfigure when .qrc file changes
  1281. this->Makefile->AddCMakeDependFile(qrc.QrcFile);
  1282. }
  1283. }
  1284. return true;
  1285. }
  1286. bool cmQtAutoGenInitializer::SetupCustomTargets()
  1287. {
  1288. // Create info directory on demand
  1289. if (!cmSystemTools::MakeDirectory(this->Dir.Info)) {
  1290. cmSystemTools::Error(cmStrCat("AutoGen: Could not create directory: ",
  1291. Quoted(this->Dir.Info)));
  1292. return false;
  1293. }
  1294. // Generate autogen target info file
  1295. if (this->MocOrUicEnabled()) {
  1296. // Write autogen target info files
  1297. if (!this->SetupWriteAutogenInfo()) {
  1298. return false;
  1299. }
  1300. }
  1301. // Write AUTORCC info files
  1302. return !this->Rcc.Enabled || this->SetupWriteRccInfo();
  1303. }
  1304. bool cmQtAutoGenInitializer::SetupWriteAutogenInfo()
  1305. {
  1306. // Utility lambdas
  1307. auto MfDef = [this](std::string const& key) {
  1308. return this->Makefile->GetSafeDefinition(key);
  1309. };
  1310. // Filtered headers and sources
  1311. std::set<std::string> moc_skip;
  1312. std::set<std::string> uic_skip;
  1313. std::vector<MUFile const*> headers;
  1314. std::vector<MUFile const*> sources;
  1315. // Filter headers
  1316. {
  1317. headers.reserve(this->AutogenTarget.Headers.size());
  1318. for (auto const& pair : this->AutogenTarget.Headers) {
  1319. MUFile const* const muf = pair.second.get();
  1320. if (muf->Generated && !this->CMP0071Accept) {
  1321. continue;
  1322. }
  1323. if (muf->SkipMoc) {
  1324. moc_skip.insert(muf->FullPath);
  1325. }
  1326. if (muf->SkipUic) {
  1327. uic_skip.insert(muf->FullPath);
  1328. }
  1329. if (muf->MocIt || muf->UicIt) {
  1330. headers.emplace_back(muf);
  1331. }
  1332. }
  1333. std::sort(headers.begin(), headers.end(),
  1334. [](MUFile const* a, MUFile const* b) {
  1335. return (a->FullPath < b->FullPath);
  1336. });
  1337. }
  1338. // Filter sources
  1339. {
  1340. sources.reserve(this->AutogenTarget.Sources.size());
  1341. for (auto const& pair : this->AutogenTarget.Sources) {
  1342. MUFile const* const muf = pair.second.get();
  1343. if (muf->Generated && !this->CMP0071Accept) {
  1344. continue;
  1345. }
  1346. if (muf->SkipMoc) {
  1347. moc_skip.insert(muf->FullPath);
  1348. }
  1349. if (muf->SkipUic) {
  1350. uic_skip.insert(muf->FullPath);
  1351. }
  1352. if (muf->MocIt || muf->UicIt) {
  1353. sources.emplace_back(muf);
  1354. }
  1355. }
  1356. std::sort(sources.begin(), sources.end(),
  1357. [](MUFile const* a, MUFile const* b) {
  1358. return (a->FullPath < b->FullPath);
  1359. });
  1360. }
  1361. // Info writer
  1362. InfoWriter info;
  1363. // General
  1364. info.SetBool("MULTI_CONFIG", this->MultiConfig);
  1365. info.SetUInt("PARALLEL", this->AutogenTarget.Parallel);
  1366. info.SetUInt("VERBOSITY", this->Verbosity);
  1367. // Directories
  1368. info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
  1369. info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
  1370. info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
  1371. info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
  1372. info.Set("BUILD_DIR", this->Dir.Build);
  1373. info.SetConfig("INCLUDE_DIR", this->Dir.Include);
  1374. info.SetUInt("QT_VERSION_MAJOR", this->QtVersion.Major);
  1375. info.SetUInt("QT_VERSION_MINOR", this->QtVersion.Minor);
  1376. info.Set("QT_MOC_EXECUTABLE", this->Moc.Executable);
  1377. info.Set("QT_UIC_EXECUTABLE", this->Uic.Executable);
  1378. info.Set("CMAKE_EXECUTABLE", cmSystemTools::GetCMakeCommand());
  1379. info.SetConfig("SETTINGS_FILE", this->AutogenTarget.SettingsFile);
  1380. info.SetConfig("PARSE_CACHE_FILE", this->AutogenTarget.ParseCacheFile);
  1381. info.Set("DEP_FILE", this->AutogenTarget.DepFile);
  1382. info.Set("DEP_FILE_RULE_NAME", this->AutogenTarget.DepFileRuleName);
  1383. info.SetArray("CMAKE_LIST_FILES", this->Makefile->GetListFiles());
  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 (cmNonempty(propName)) {
  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->GetDefinition(std::string(keyPair.first)),
  1597. target->Makefile->GetDefinition(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. }