cmQtAutoGenInitializer.cxx 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642
  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 "cmQtAutoGen.h"
  5. #include "cmQtAutoGenGlobalInitializer.h"
  6. #include "cmAlgorithms.h"
  7. #include "cmCustomCommand.h"
  8. #include "cmCustomCommandLines.h"
  9. #include "cmDuration.h"
  10. #include "cmFilePathChecksum.h"
  11. #include "cmGeneratorExpression.h"
  12. #include "cmGeneratorTarget.h"
  13. #include "cmGlobalGenerator.h"
  14. #include "cmLinkItem.h"
  15. #include "cmListFileCache.h"
  16. #include "cmLocalGenerator.h"
  17. #include "cmMakefile.h"
  18. #include "cmMessageType.h"
  19. #include "cmOutputConverter.h"
  20. #include "cmPolicies.h"
  21. #include "cmProcessOutput.h"
  22. #include "cmSourceFile.h"
  23. #include "cmSourceGroup.h"
  24. #include "cmState.h"
  25. #include "cmStateTypes.h"
  26. #include "cmSystemTools.h"
  27. #include "cmTarget.h"
  28. #include "cmsys/FStream.hxx"
  29. #include "cmsys/SystemInformation.hxx"
  30. #include <algorithm>
  31. #include <array>
  32. #include <deque>
  33. #include <map>
  34. #include <set>
  35. #include <sstream>
  36. #include <string>
  37. #include <type_traits>
  38. #include <utility>
  39. #include <vector>
  40. std::string GetQtExecutableTargetName(
  41. const cmQtAutoGen::IntegerVersion& qtVersion, std::string const& executable)
  42. {
  43. if (qtVersion.Major == 6) {
  44. return ("Qt6::" + executable);
  45. }
  46. if (qtVersion.Major == 5) {
  47. return ("Qt5::" + executable);
  48. }
  49. if (qtVersion.Major == 4) {
  50. return ("Qt4::" + executable);
  51. }
  52. return ("");
  53. }
  54. static std::size_t GetParallelCPUCount()
  55. {
  56. static std::size_t count = 0;
  57. // Detect only on the first call
  58. if (count == 0) {
  59. cmsys::SystemInformation info;
  60. info.RunCPUCheck();
  61. count = info.GetNumberOfPhysicalCPU();
  62. count = std::max<std::size_t>(count, 1);
  63. count = std::min<std::size_t>(count, cmQtAutoGen::ParallelMax);
  64. }
  65. return count;
  66. }
  67. static bool AddToSourceGroup(cmMakefile* makefile, std::string const& fileName,
  68. cmQtAutoGen::GeneratorT genType)
  69. {
  70. cmSourceGroup* sourceGroup = nullptr;
  71. // Acquire source group
  72. {
  73. std::string property;
  74. std::string groupName;
  75. {
  76. std::array<std::string, 2> props;
  77. // Use generator specific group name
  78. switch (genType) {
  79. case cmQtAutoGen::GeneratorT::MOC:
  80. props[0] = "AUTOMOC_SOURCE_GROUP";
  81. break;
  82. case cmQtAutoGen::GeneratorT::RCC:
  83. props[0] = "AUTORCC_SOURCE_GROUP";
  84. break;
  85. default:
  86. props[0] = "AUTOGEN_SOURCE_GROUP";
  87. break;
  88. }
  89. props[1] = "AUTOGEN_SOURCE_GROUP";
  90. for (std::string& prop : props) {
  91. const char* propName = makefile->GetState()->GetGlobalProperty(prop);
  92. if ((propName != nullptr) && (*propName != '\0')) {
  93. groupName = propName;
  94. property = std::move(prop);
  95. break;
  96. }
  97. }
  98. }
  99. // Generate a source group on demand
  100. if (!groupName.empty()) {
  101. sourceGroup = makefile->GetOrCreateSourceGroup(groupName);
  102. if (sourceGroup == nullptr) {
  103. std::ostringstream ost;
  104. ost << cmQtAutoGen::GeneratorNameUpper(genType);
  105. ost << ": " << property;
  106. ost << ": Could not find or create the source group ";
  107. ost << cmQtAutoGen::Quoted(groupName);
  108. cmSystemTools::Error(ost.str());
  109. return false;
  110. }
  111. }
  112. }
  113. if (sourceGroup != nullptr) {
  114. sourceGroup->AddGroupFile(fileName);
  115. }
  116. return true;
  117. }
  118. static void AddCleanFile(cmMakefile* makefile, std::string const& fileName)
  119. {
  120. makefile->AppendProperty("ADDITIONAL_MAKE_CLEAN_FILES", fileName.c_str(),
  121. false);
  122. }
  123. static std::string FileProjectRelativePath(cmMakefile* makefile,
  124. std::string const& fileName)
  125. {
  126. std::string res;
  127. {
  128. std::string pSource = cmSystemTools::RelativePath(
  129. makefile->GetCurrentSourceDirectory(), fileName);
  130. std::string pBinary = cmSystemTools::RelativePath(
  131. makefile->GetCurrentBinaryDirectory(), fileName);
  132. if (pSource.size() < pBinary.size()) {
  133. res = std::move(pSource);
  134. } else if (pBinary.size() < fileName.size()) {
  135. res = std::move(pBinary);
  136. } else {
  137. res = fileName;
  138. }
  139. }
  140. return res;
  141. }
  142. /* @brief Tests if targetDepend is a STATIC_LIBRARY and if any of its
  143. * recursive STATIC_LIBRARY dependencies depends on targetOrigin
  144. * (STATIC_LIBRARY cycle).
  145. */
  146. static bool StaticLibraryCycle(cmGeneratorTarget const* targetOrigin,
  147. cmGeneratorTarget const* targetDepend,
  148. std::string const& config)
  149. {
  150. bool cycle = false;
  151. if ((targetOrigin->GetType() == cmStateEnums::STATIC_LIBRARY) &&
  152. (targetDepend->GetType() == cmStateEnums::STATIC_LIBRARY)) {
  153. std::set<cmGeneratorTarget const*> knownLibs;
  154. std::deque<cmGeneratorTarget const*> testLibs;
  155. // Insert initial static_library dependency
  156. knownLibs.insert(targetDepend);
  157. testLibs.push_back(targetDepend);
  158. while (!testLibs.empty()) {
  159. cmGeneratorTarget const* testTarget = testLibs.front();
  160. testLibs.pop_front();
  161. // Check if the test target is the origin target (cycle)
  162. if (testTarget == targetOrigin) {
  163. cycle = true;
  164. break;
  165. }
  166. // Collect all static_library dependencies from the test target
  167. cmLinkImplementationLibraries const* libs =
  168. testTarget->GetLinkImplementationLibraries(config);
  169. if (libs != nullptr) {
  170. for (cmLinkItem const& item : libs->Libraries) {
  171. cmGeneratorTarget const* depTarget = item.Target;
  172. if ((depTarget != nullptr) &&
  173. (depTarget->GetType() == cmStateEnums::STATIC_LIBRARY) &&
  174. knownLibs.insert(depTarget).second) {
  175. testLibs.push_back(depTarget);
  176. }
  177. }
  178. }
  179. }
  180. }
  181. return cycle;
  182. }
  183. cmQtAutoGenInitializer::InfoWriter::InfoWriter(std::string const& filename)
  184. {
  185. Ofs_.SetCopyIfDifferent(true);
  186. Ofs_.Open(filename, false, true);
  187. }
  188. template <class IT>
  189. std::string cmQtAutoGenInitializer::InfoWriter::ListJoin(IT it_begin,
  190. IT it_end)
  191. {
  192. std::string res;
  193. for (IT it = it_begin; it != it_end; ++it) {
  194. if (it != it_begin) {
  195. res += ';';
  196. }
  197. for (const char* c = it->c_str(); *c; ++c) {
  198. if (*c == '"') {
  199. // Escape the double quote to avoid ending the argument.
  200. res += "\\\"";
  201. } else if (*c == '$') {
  202. // Escape the dollar to avoid expanding variables.
  203. res += "\\$";
  204. } else if (*c == '\\') {
  205. // Escape the backslash to avoid other escapes.
  206. res += "\\\\";
  207. } else if (*c == ';') {
  208. // Escape the semicolon to avoid list expansion.
  209. res += "\\;";
  210. } else {
  211. // Other characters will be parsed correctly.
  212. res += *c;
  213. }
  214. }
  215. }
  216. return res;
  217. }
  218. std::string cmQtAutoGenInitializer::InfoWriter::ConfigKey(
  219. const char* key, std::string const& config)
  220. {
  221. std::string ckey = key;
  222. ckey += '_';
  223. ckey += config;
  224. return ckey;
  225. }
  226. void cmQtAutoGenInitializer::InfoWriter::Write(const char* key,
  227. std::string const& value)
  228. {
  229. Ofs_ << "set(" << key << " " << cmOutputConverter::EscapeForCMake(value)
  230. << ")\n";
  231. };
  232. void cmQtAutoGenInitializer::InfoWriter::WriteUInt(const char* key,
  233. unsigned int value)
  234. {
  235. Ofs_ << "set(" << key << " " << value << ")\n";
  236. };
  237. template <class C>
  238. void cmQtAutoGenInitializer::InfoWriter::WriteStrings(const char* key,
  239. C const& container)
  240. {
  241. Ofs_ << "set(" << key << " \""
  242. << ListJoin(container.begin(), container.end()) << "\")\n";
  243. }
  244. void cmQtAutoGenInitializer::InfoWriter::WriteConfig(
  245. const char* key, std::map<std::string, std::string> const& map)
  246. {
  247. for (auto const& item : map) {
  248. Write(ConfigKey(key, item.first).c_str(), item.second);
  249. }
  250. };
  251. template <class C>
  252. void cmQtAutoGenInitializer::InfoWriter::WriteConfigStrings(
  253. const char* key, std::map<std::string, C> const& map)
  254. {
  255. for (auto const& item : map) {
  256. WriteStrings(ConfigKey(key, item.first).c_str(), item.second);
  257. }
  258. }
  259. void cmQtAutoGenInitializer::InfoWriter::WriteNestedLists(
  260. const char* key, std::vector<std::vector<std::string>> const& lists)
  261. {
  262. std::vector<std::string> seplist;
  263. for (const std::vector<std::string>& list : lists) {
  264. std::string blist = "{";
  265. blist += ListJoin(list.begin(), list.end());
  266. blist += "}";
  267. seplist.push_back(std::move(blist));
  268. }
  269. Write(key, cmJoin(seplist, cmQtAutoGen::ListSep));
  270. };
  271. cmQtAutoGenInitializer::cmQtAutoGenInitializer(
  272. cmQtAutoGenGlobalInitializer* globalInitializer, cmGeneratorTarget* target,
  273. IntegerVersion const& qtVersion, bool mocEnabled, bool uicEnabled,
  274. bool rccEnabled, bool globalAutogenTarget, bool globalAutoRccTarget)
  275. : GlobalInitializer(globalInitializer)
  276. , Target(target)
  277. , QtVersion(qtVersion)
  278. {
  279. AutogenTarget.GlobalTarget = globalAutogenTarget;
  280. Moc.Enabled = mocEnabled;
  281. Uic.Enabled = uicEnabled;
  282. Rcc.Enabled = rccEnabled;
  283. Rcc.GlobalTarget = globalAutoRccTarget;
  284. }
  285. bool cmQtAutoGenInitializer::InitCustomTargets()
  286. {
  287. cmMakefile* makefile = this->Target->Target->GetMakefile();
  288. cmLocalGenerator* localGen = this->Target->GetLocalGenerator();
  289. cmGlobalGenerator* globalGen = localGen->GetGlobalGenerator();
  290. // Configurations
  291. this->MultiConfig = globalGen->IsMultiConfig();
  292. this->ConfigDefault = makefile->GetConfigurations(this->ConfigsList);
  293. if (this->ConfigsList.empty()) {
  294. this->ConfigsList.push_back(this->ConfigDefault);
  295. }
  296. // Verbosity
  297. this->Verbosity = makefile->GetSafeDefinition("CMAKE_AUTOGEN_VERBOSE");
  298. if (!this->Verbosity.empty()) {
  299. unsigned long iVerb = 0;
  300. if (!cmSystemTools::StringToULong(this->Verbosity.c_str(), &iVerb)) {
  301. // Non numeric verbosity
  302. this->Verbosity = cmSystemTools::IsOn(this->Verbosity) ? "1" : "0";
  303. }
  304. }
  305. // Targets FOLDER
  306. {
  307. const char* folder =
  308. makefile->GetState()->GetGlobalProperty("AUTOMOC_TARGETS_FOLDER");
  309. if (folder == nullptr) {
  310. folder =
  311. makefile->GetState()->GetGlobalProperty("AUTOGEN_TARGETS_FOLDER");
  312. }
  313. // Inherit FOLDER property from target (#13688)
  314. if (folder == nullptr) {
  315. folder = this->Target->GetProperty("FOLDER");
  316. }
  317. if (folder != nullptr) {
  318. this->TargetsFolder = folder;
  319. }
  320. }
  321. // Common directories
  322. {
  323. // Collapsed current binary directory
  324. std::string const cbd = cmSystemTools::CollapseFullPath(
  325. std::string(), makefile->GetCurrentBinaryDirectory());
  326. // Info directory
  327. this->Dir.Info = cbd;
  328. this->Dir.Info += "/CMakeFiles";
  329. this->Dir.Info += '/';
  330. this->Dir.Info += this->Target->GetName();
  331. this->Dir.Info += "_autogen";
  332. this->Dir.Info += ".dir";
  333. cmSystemTools::ConvertToUnixSlashes(this->Dir.Info);
  334. // Build directory
  335. this->Dir.Build = this->Target->GetSafeProperty("AUTOGEN_BUILD_DIR");
  336. if (this->Dir.Build.empty()) {
  337. this->Dir.Build = cbd;
  338. this->Dir.Build += '/';
  339. this->Dir.Build += this->Target->GetName();
  340. this->Dir.Build += "_autogen";
  341. }
  342. cmSystemTools::ConvertToUnixSlashes(this->Dir.Build);
  343. // Cleanup build directory
  344. AddCleanFile(makefile, this->Dir.Build);
  345. // Working directory
  346. this->Dir.Work = cbd;
  347. cmSystemTools::ConvertToUnixSlashes(this->Dir.Work);
  348. // Include directory
  349. this->Dir.Include = this->Dir.Build;
  350. this->Dir.Include += "/include";
  351. if (this->MultiConfig) {
  352. this->Dir.Include += "_$<CONFIG>";
  353. }
  354. // Per config include directories
  355. if (this->MultiConfig) {
  356. for (std::string const& cfg : this->ConfigsList) {
  357. std::string& dir = this->Dir.ConfigInclude[cfg];
  358. dir = this->Dir.Build;
  359. dir += "/include_";
  360. dir += cfg;
  361. }
  362. }
  363. }
  364. // Moc, Uic and _autogen target settings
  365. if (this->Moc.Enabled || this->Uic.Enabled) {
  366. // Init moc specific settings
  367. if (this->Moc.Enabled && !InitMoc()) {
  368. return false;
  369. }
  370. // Init uic specific settings
  371. if (this->Uic.Enabled) {
  372. if (InitUic()) {
  373. auto* uicTarget = makefile->FindTargetToUse(
  374. GetQtExecutableTargetName(this->QtVersion, "uic"));
  375. if (uicTarget != nullptr) {
  376. this->AutogenTarget.DependTargets.insert(uicTarget);
  377. }
  378. } else {
  379. return false;
  380. }
  381. }
  382. // Autogen target name
  383. this->AutogenTarget.Name = this->Target->GetName();
  384. this->AutogenTarget.Name += "_autogen";
  385. // Autogen target parallel processing
  386. this->AutogenTarget.Parallel =
  387. this->Target->GetSafeProperty("AUTOGEN_PARALLEL");
  388. if (this->AutogenTarget.Parallel.empty() ||
  389. (this->AutogenTarget.Parallel == "AUTO")) {
  390. // Autodetect number of CPUs
  391. this->AutogenTarget.Parallel = std::to_string(GetParallelCPUCount());
  392. }
  393. // Autogen target info and settings files
  394. {
  395. this->AutogenTarget.InfoFile = this->Dir.Info;
  396. this->AutogenTarget.InfoFile += "/AutogenInfo.cmake";
  397. this->AutogenTarget.SettingsFile = this->Dir.Info;
  398. this->AutogenTarget.SettingsFile += "/AutogenOldSettings.txt";
  399. if (this->MultiConfig) {
  400. for (std::string const& cfg : this->ConfigsList) {
  401. std::string& filename = this->AutogenTarget.ConfigSettingsFile[cfg];
  402. filename =
  403. AppendFilenameSuffix(this->AutogenTarget.SettingsFile, "_" + cfg);
  404. AddCleanFile(makefile, filename);
  405. }
  406. } else {
  407. AddCleanFile(makefile, this->AutogenTarget.SettingsFile);
  408. }
  409. }
  410. // Autogen target: Compute user defined dependencies
  411. {
  412. this->AutogenTarget.DependOrigin =
  413. this->Target->GetPropertyAsBool("AUTOGEN_ORIGIN_DEPENDS");
  414. auto* mocTarget = makefile->FindTargetToUse(
  415. GetQtExecutableTargetName(this->QtVersion, "moc"));
  416. if (mocTarget != nullptr) {
  417. this->AutogenTarget.DependTargets.insert(mocTarget);
  418. }
  419. std::string const deps =
  420. this->Target->GetSafeProperty("AUTOGEN_TARGET_DEPENDS");
  421. if (!deps.empty()) {
  422. std::vector<std::string> extraDeps;
  423. cmSystemTools::ExpandListArgument(deps, extraDeps);
  424. for (std::string const& depName : extraDeps) {
  425. // Allow target and file dependencies
  426. auto* depTarget = makefile->FindTargetToUse(depName);
  427. if (depTarget != nullptr) {
  428. this->AutogenTarget.DependTargets.insert(depTarget);
  429. } else {
  430. this->AutogenTarget.DependFiles.insert(depName);
  431. }
  432. }
  433. }
  434. }
  435. }
  436. // Init rcc specific settings
  437. if (this->Rcc.Enabled && !InitRcc()) {
  438. return false;
  439. }
  440. // Add autogen include directory to the origin target INCLUDE_DIRECTORIES
  441. if (this->Moc.Enabled || this->Uic.Enabled ||
  442. (this->Rcc.Enabled && this->MultiConfig)) {
  443. this->Target->AddIncludeDirectory(this->Dir.Include, true);
  444. }
  445. // Scan files
  446. if (!this->InitScanFiles()) {
  447. return false;
  448. }
  449. // Create autogen target
  450. if ((this->Moc.Enabled || this->Uic.Enabled) && !this->InitAutogenTarget()) {
  451. return false;
  452. }
  453. // Create rcc targets
  454. if (this->Rcc.Enabled && !this->InitRccTargets()) {
  455. return false;
  456. }
  457. return true;
  458. }
  459. bool cmQtAutoGenInitializer::InitMoc()
  460. {
  461. cmMakefile* makefile = this->Target->Target->GetMakefile();
  462. cmLocalGenerator* localGen = this->Target->GetLocalGenerator();
  463. // Mocs compilation file
  464. this->Moc.MocsCompilation = this->Dir.Build;
  465. this->Moc.MocsCompilation += "/mocs_compilation.cpp";
  466. // Moc predefs command
  467. if (this->Target->GetPropertyAsBool("AUTOMOC_COMPILER_PREDEFINES") &&
  468. (this->QtVersion >= IntegerVersion(5, 8))) {
  469. this->Moc.PredefsCmd =
  470. makefile->GetSafeDefinition("CMAKE_CXX_COMPILER_PREDEFINES_COMMAND");
  471. }
  472. // Moc includes
  473. {
  474. bool const appendImplicit = (this->QtVersion.Major >= 5);
  475. auto GetIncludeDirs =
  476. [this, localGen,
  477. appendImplicit](std::string const& cfg) -> std::vector<std::string> {
  478. // Get the include dirs for this target, without stripping the implicit
  479. // include dirs off, see
  480. // https://gitlab.kitware.com/cmake/cmake/issues/13667
  481. std::vector<std::string> dirs;
  482. localGen->GetIncludeDirectoriesImplicit(dirs, this->Target, "CXX", cfg,
  483. false, appendImplicit);
  484. return dirs;
  485. };
  486. // Default configuration include directories
  487. this->Moc.Includes = GetIncludeDirs(this->ConfigDefault);
  488. // Other configuration settings
  489. if (this->MultiConfig) {
  490. for (std::string const& cfg : this->ConfigsList) {
  491. std::vector<std::string> dirs = GetIncludeDirs(cfg);
  492. if (dirs != this->Moc.Includes) {
  493. this->Moc.ConfigIncludes[cfg] = std::move(dirs);
  494. }
  495. }
  496. }
  497. }
  498. // Moc compile definitions
  499. {
  500. auto GetCompileDefinitions =
  501. [this, localGen](std::string const& cfg) -> std::set<std::string> {
  502. std::set<std::string> defines;
  503. localGen->GetTargetDefines(this->Target, cfg, "CXX", defines);
  504. #ifdef _WIN32
  505. if (this->Moc.PredefsCmd.empty()) {
  506. // Add WIN32 definition if we don't have a moc_predefs.h
  507. defines.insert("WIN32");
  508. }
  509. #endif
  510. return defines;
  511. };
  512. // Default configuration defines
  513. this->Moc.Defines = GetCompileDefinitions(this->ConfigDefault);
  514. // Other configuration defines
  515. if (this->MultiConfig) {
  516. for (std::string const& cfg : this->ConfigsList) {
  517. std::set<std::string> defines = GetCompileDefinitions(cfg);
  518. if (defines != this->Moc.Defines) {
  519. this->Moc.ConfigDefines[cfg] = std::move(defines);
  520. }
  521. }
  522. }
  523. }
  524. // Moc executable
  525. return GetMocExecutable();
  526. }
  527. bool cmQtAutoGenInitializer::InitUic()
  528. {
  529. cmMakefile* makefile = this->Target->Target->GetMakefile();
  530. // Uic search paths
  531. {
  532. std::string const usp =
  533. this->Target->GetSafeProperty("AUTOUIC_SEARCH_PATHS");
  534. if (!usp.empty()) {
  535. cmSystemTools::ExpandListArgument(usp, this->Uic.SearchPaths);
  536. std::string const& srcDir = makefile->GetCurrentSourceDirectory();
  537. for (std::string& path : this->Uic.SearchPaths) {
  538. path = cmSystemTools::CollapseFullPath(path, srcDir);
  539. }
  540. }
  541. }
  542. // Uic target options
  543. {
  544. auto UicGetOpts =
  545. [this](std::string const& cfg) -> std::vector<std::string> {
  546. std::vector<std::string> opts;
  547. this->Target->GetAutoUicOptions(opts, cfg);
  548. return opts;
  549. };
  550. // Default settings
  551. this->Uic.Options = UicGetOpts(this->ConfigDefault);
  552. // Configuration specific settings
  553. if (this->MultiConfig) {
  554. for (std::string const& cfg : this->ConfigsList) {
  555. std::vector<std::string> options = UicGetOpts(cfg);
  556. if (options != this->Uic.Options) {
  557. this->Uic.ConfigOptions[cfg] = std::move(options);
  558. }
  559. }
  560. }
  561. }
  562. // .ui files skip and options
  563. {
  564. std::string const uiExt = "ui";
  565. std::string pathError;
  566. for (cmSourceFile* sf : makefile->GetSourceFiles()) {
  567. // sf->GetExtension() is only valid after sf->GetFullPath() ...
  568. // Since we're iterating over source files that might be not in the
  569. // target we need to check for path errors (not existing files).
  570. std::string const& fPath = sf->GetFullPath(&pathError);
  571. if (!pathError.empty()) {
  572. pathError.clear();
  573. continue;
  574. }
  575. if (sf->GetExtension() == uiExt) {
  576. std::string const absFile = cmSystemTools::GetRealPath(fPath);
  577. // Check if the .ui file should be skipped
  578. if (sf->GetPropertyAsBool("SKIP_AUTOUIC") ||
  579. sf->GetPropertyAsBool("SKIP_AUTOGEN")) {
  580. this->Uic.Skip.insert(absFile);
  581. }
  582. // Check if the .ui file has uic options
  583. std::string const uicOpts = sf->GetSafeProperty("AUTOUIC_OPTIONS");
  584. if (!uicOpts.empty()) {
  585. // Check if file isn't skipped
  586. if (this->Uic.Skip.count(absFile) == 0) {
  587. this->Uic.FileFiles.push_back(absFile);
  588. std::vector<std::string> optsVec;
  589. cmSystemTools::ExpandListArgument(uicOpts, optsVec);
  590. this->Uic.FileOptions.push_back(std::move(optsVec));
  591. }
  592. }
  593. }
  594. }
  595. }
  596. // Uic executable
  597. return GetUicExecutable();
  598. }
  599. bool cmQtAutoGenInitializer::InitRcc()
  600. {
  601. return GetRccExecutable();
  602. }
  603. bool cmQtAutoGenInitializer::InitScanFiles()
  604. {
  605. cmMakefile* makefile = this->Target->Target->GetMakefile();
  606. // Scan through target files
  607. {
  608. std::string const qrcExt = "qrc";
  609. std::vector<cmSourceFile*> srcFiles;
  610. this->Target->GetConfigCommonSourceFiles(srcFiles);
  611. for (cmSourceFile* sf : srcFiles) {
  612. if (sf->GetPropertyAsBool("SKIP_AUTOGEN")) {
  613. continue;
  614. }
  615. // sf->GetExtension() is only valid after sf->GetFullPath() ...
  616. std::string const& fPath = sf->GetFullPath();
  617. std::string const& ext = sf->GetExtension();
  618. // Register generated files that will be scanned by moc or uic
  619. if (this->Moc.Enabled || this->Uic.Enabled) {
  620. cmSystemTools::FileFormat const fileType =
  621. cmSystemTools::GetFileFormat(ext.c_str());
  622. if ((fileType == cmSystemTools::CXX_FILE_FORMAT) ||
  623. (fileType == cmSystemTools::HEADER_FILE_FORMAT)) {
  624. std::string const absPath = cmSystemTools::GetRealPath(fPath);
  625. if ((this->Moc.Enabled && !sf->GetPropertyAsBool("SKIP_AUTOMOC")) ||
  626. (this->Uic.Enabled && !sf->GetPropertyAsBool("SKIP_AUTOUIC"))) {
  627. // Register source
  628. const bool generated = sf->GetIsGenerated();
  629. if (fileType == cmSystemTools::HEADER_FILE_FORMAT) {
  630. if (generated) {
  631. this->AutogenTarget.HeadersGenerated.push_back(absPath);
  632. } else {
  633. this->AutogenTarget.Headers.push_back(absPath);
  634. }
  635. } else {
  636. if (generated) {
  637. this->AutogenTarget.SourcesGenerated.push_back(absPath);
  638. } else {
  639. this->AutogenTarget.Sources.push_back(absPath);
  640. }
  641. }
  642. }
  643. }
  644. }
  645. // Register rcc enabled files
  646. if (this->Rcc.Enabled && (ext == qrcExt) &&
  647. !sf->GetPropertyAsBool("SKIP_AUTORCC")) {
  648. // Register qrc file
  649. {
  650. Qrc qrc;
  651. qrc.QrcFile = cmSystemTools::GetRealPath(fPath);
  652. qrc.QrcName =
  653. cmSystemTools::GetFilenameWithoutLastExtension(qrc.QrcFile);
  654. qrc.Generated = sf->GetIsGenerated();
  655. // RCC options
  656. {
  657. std::string const opts = sf->GetSafeProperty("AUTORCC_OPTIONS");
  658. if (!opts.empty()) {
  659. cmSystemTools::ExpandListArgument(opts, qrc.Options);
  660. }
  661. }
  662. this->Rcc.Qrcs.push_back(std::move(qrc));
  663. }
  664. }
  665. }
  666. }
  667. // cmGeneratorTarget::GetConfigCommonSourceFiles computes the target's
  668. // sources meta data cache. Clear it so that OBJECT library targets that
  669. // are AUTOGEN initialized after this target get their added
  670. // mocs_compilation.cpp source acknowledged by this target.
  671. this->Target->ClearSourcesCache();
  672. if (this->Moc.Enabled || this->Uic.Enabled) {
  673. // Read skip files from makefile sources
  674. {
  675. std::string pathError;
  676. for (cmSourceFile* sf : makefile->GetSourceFiles()) {
  677. // sf->GetExtension() is only valid after sf->GetFullPath() ...
  678. // Since we're iterating over source files that might be not in the
  679. // target we need to check for path errors (not existing files).
  680. std::string const& fPath = sf->GetFullPath(&pathError);
  681. if (!pathError.empty()) {
  682. pathError.clear();
  683. continue;
  684. }
  685. cmSystemTools::FileFormat const fileType =
  686. cmSystemTools::GetFileFormat(sf->GetExtension().c_str());
  687. if (!(fileType == cmSystemTools::CXX_FILE_FORMAT) &&
  688. !(fileType == cmSystemTools::HEADER_FILE_FORMAT)) {
  689. continue;
  690. }
  691. const bool skipAll = sf->GetPropertyAsBool("SKIP_AUTOGEN");
  692. const bool mocSkip = this->Moc.Enabled &&
  693. (skipAll || sf->GetPropertyAsBool("SKIP_AUTOMOC"));
  694. const bool uicSkip = this->Uic.Enabled &&
  695. (skipAll || sf->GetPropertyAsBool("SKIP_AUTOUIC"));
  696. if (mocSkip || uicSkip) {
  697. std::string const absFile = cmSystemTools::GetRealPath(fPath);
  698. if (mocSkip) {
  699. this->Moc.Skip.insert(absFile);
  700. }
  701. if (uicSkip) {
  702. this->Uic.Skip.insert(absFile);
  703. }
  704. }
  705. }
  706. }
  707. // Process GENERATED sources and headers
  708. if (!this->AutogenTarget.SourcesGenerated.empty() ||
  709. !this->AutogenTarget.HeadersGenerated.empty()) {
  710. // Check status of policy CMP0071
  711. bool policyAccept = false;
  712. bool policyWarn = false;
  713. cmPolicies::PolicyStatus const CMP0071_status =
  714. makefile->GetPolicyStatus(cmPolicies::CMP0071);
  715. switch (CMP0071_status) {
  716. case cmPolicies::WARN:
  717. policyWarn = true;
  718. CM_FALLTHROUGH;
  719. case cmPolicies::OLD:
  720. // Ignore GENERATED file
  721. break;
  722. case cmPolicies::REQUIRED_IF_USED:
  723. case cmPolicies::REQUIRED_ALWAYS:
  724. case cmPolicies::NEW:
  725. // Process GENERATED file
  726. policyAccept = true;
  727. break;
  728. }
  729. if (policyAccept) {
  730. // Accept GENERATED sources
  731. for (std::string const& absFile :
  732. this->AutogenTarget.HeadersGenerated) {
  733. this->AutogenTarget.Headers.push_back(absFile);
  734. this->AutogenTarget.DependFiles.insert(absFile);
  735. }
  736. for (std::string const& absFile :
  737. this->AutogenTarget.SourcesGenerated) {
  738. this->AutogenTarget.Sources.push_back(absFile);
  739. this->AutogenTarget.DependFiles.insert(absFile);
  740. }
  741. } else {
  742. if (policyWarn) {
  743. std::string msg;
  744. msg += cmPolicies::GetPolicyWarning(cmPolicies::CMP0071);
  745. msg += "\n";
  746. std::string tools;
  747. std::string property;
  748. if (this->Moc.Enabled && this->Uic.Enabled) {
  749. tools = "AUTOMOC and AUTOUIC";
  750. property = "SKIP_AUTOGEN";
  751. } else if (this->Moc.Enabled) {
  752. tools = "AUTOMOC";
  753. property = "SKIP_AUTOMOC";
  754. } else if (this->Uic.Enabled) {
  755. tools = "AUTOUIC";
  756. property = "SKIP_AUTOUIC";
  757. }
  758. msg += "For compatibility, CMake is excluding the GENERATED source "
  759. "file(s):\n";
  760. for (const std::string& absFile :
  761. this->AutogenTarget.HeadersGenerated) {
  762. msg.append(" ").append(Quoted(absFile)).append("\n");
  763. }
  764. for (const std::string& absFile :
  765. this->AutogenTarget.SourcesGenerated) {
  766. msg.append(" ").append(Quoted(absFile)).append("\n");
  767. }
  768. msg += "from processing by ";
  769. msg += tools;
  770. msg +=
  771. ". If any of the files should be processed, set CMP0071 to NEW. "
  772. "If any of the files should not be processed, "
  773. "explicitly exclude them by setting the source file property ";
  774. msg += property;
  775. msg += ":\n set_property(SOURCE file.h PROPERTY ";
  776. msg += property;
  777. msg += " ON)\n";
  778. makefile->IssueMessage(MessageType::AUTHOR_WARNING, msg);
  779. }
  780. }
  781. }
  782. // Sort headers and sources
  783. if (this->Moc.Enabled || this->Uic.Enabled) {
  784. std::sort(this->AutogenTarget.Headers.begin(),
  785. this->AutogenTarget.Headers.end());
  786. std::sort(this->AutogenTarget.Sources.begin(),
  787. this->AutogenTarget.Sources.end());
  788. }
  789. }
  790. // Process qrc files
  791. if (!this->Rcc.Qrcs.empty()) {
  792. const bool modernQt = (this->QtVersion.Major >= 5);
  793. // Target rcc options
  794. std::vector<std::string> optionsTarget;
  795. cmSystemTools::ExpandListArgument(
  796. this->Target->GetSafeProperty("AUTORCC_OPTIONS"), optionsTarget);
  797. // Check if file name is unique
  798. for (Qrc& qrc : this->Rcc.Qrcs) {
  799. qrc.Unique = true;
  800. for (Qrc const& qrc2 : this->Rcc.Qrcs) {
  801. if ((&qrc != &qrc2) && (qrc.QrcName == qrc2.QrcName)) {
  802. qrc.Unique = false;
  803. break;
  804. }
  805. }
  806. }
  807. // Path checksum and file names
  808. {
  809. cmFilePathChecksum const fpathCheckSum(makefile);
  810. for (Qrc& qrc : this->Rcc.Qrcs) {
  811. qrc.PathChecksum = fpathCheckSum.getPart(qrc.QrcFile);
  812. // RCC output file name
  813. {
  814. std::string rccFile = this->Dir.Build + "/";
  815. rccFile += qrc.PathChecksum;
  816. rccFile += "/qrc_";
  817. rccFile += qrc.QrcName;
  818. rccFile += ".cpp";
  819. qrc.RccFile = std::move(rccFile);
  820. }
  821. {
  822. std::string base = this->Dir.Info;
  823. base += "/RCC";
  824. base += qrc.QrcName;
  825. if (!qrc.Unique) {
  826. base += qrc.PathChecksum;
  827. }
  828. qrc.LockFile = base;
  829. qrc.LockFile += ".lock";
  830. qrc.InfoFile = base;
  831. qrc.InfoFile += "Info.cmake";
  832. qrc.SettingsFile = base;
  833. qrc.SettingsFile += "Settings.txt";
  834. if (this->MultiConfig) {
  835. for (std::string const& cfg : this->ConfigsList) {
  836. qrc.ConfigSettingsFile[cfg] =
  837. AppendFilenameSuffix(qrc.SettingsFile, "_" + cfg);
  838. }
  839. }
  840. }
  841. }
  842. }
  843. // RCC options
  844. for (Qrc& qrc : this->Rcc.Qrcs) {
  845. // Target options
  846. std::vector<std::string> opts = optionsTarget;
  847. // Merge computed "-name XYZ" option
  848. {
  849. std::string name = qrc.QrcName;
  850. // Replace '-' with '_'. The former is not valid for symbol names.
  851. std::replace(name.begin(), name.end(), '-', '_');
  852. if (!qrc.Unique) {
  853. name += "_";
  854. name += qrc.PathChecksum;
  855. }
  856. std::vector<std::string> nameOpts;
  857. nameOpts.emplace_back("-name");
  858. nameOpts.emplace_back(std::move(name));
  859. RccMergeOptions(opts, nameOpts, modernQt);
  860. }
  861. // Merge file option
  862. RccMergeOptions(opts, qrc.Options, modernQt);
  863. qrc.Options = std::move(opts);
  864. }
  865. // RCC resources
  866. for (Qrc& qrc : this->Rcc.Qrcs) {
  867. if (!qrc.Generated) {
  868. std::string error;
  869. if (!RccListInputs(qrc.QrcFile, qrc.Resources, error)) {
  870. cmSystemTools::Error(error);
  871. return false;
  872. }
  873. }
  874. }
  875. }
  876. return true;
  877. }
  878. bool cmQtAutoGenInitializer::InitAutogenTarget()
  879. {
  880. cmMakefile* makefile = this->Target->Target->GetMakefile();
  881. cmLocalGenerator* localGen = this->Target->GetLocalGenerator();
  882. cmGlobalGenerator* globalGen = localGen->GetGlobalGenerator();
  883. // Register info file as generated by CMake
  884. makefile->AddCMakeOutputFile(this->AutogenTarget.InfoFile);
  885. // Files provided by the autogen target
  886. std::vector<std::string> autogenProvides;
  887. if (this->Moc.Enabled) {
  888. this->AddGeneratedSource(this->Moc.MocsCompilation, GeneratorT::MOC, true);
  889. autogenProvides.push_back(this->Moc.MocsCompilation);
  890. }
  891. // Compose target comment
  892. std::string autogenComment;
  893. {
  894. std::string tools;
  895. if (this->Moc.Enabled) {
  896. tools += "MOC";
  897. }
  898. if (this->Uic.Enabled) {
  899. if (!tools.empty()) {
  900. tools += " and ";
  901. }
  902. tools += "UIC";
  903. }
  904. autogenComment = "Automatic ";
  905. autogenComment += tools;
  906. autogenComment += " for target ";
  907. autogenComment += this->Target->GetName();
  908. }
  909. // Compose command lines
  910. cmCustomCommandLines commandLines;
  911. {
  912. cmCustomCommandLine currentLine;
  913. currentLine.push_back(cmSystemTools::GetCMakeCommand());
  914. currentLine.push_back("-E");
  915. currentLine.push_back("cmake_autogen");
  916. currentLine.push_back(this->AutogenTarget.InfoFile);
  917. currentLine.push_back("$<CONFIGURATION>");
  918. commandLines.push_back(std::move(currentLine));
  919. }
  920. // Use PRE_BUILD on demand
  921. bool usePRE_BUILD = false;
  922. if (globalGen->GetName().find("Visual Studio") != std::string::npos) {
  923. // Under VS use a PRE_BUILD event instead of a separate target to
  924. // reduce the number of targets loaded into the IDE.
  925. // This also works around a VS 11 bug that may skip updating the target:
  926. // https://connect.microsoft.com/VisualStudio/feedback/details/769495
  927. usePRE_BUILD = true;
  928. }
  929. // Disable PRE_BUILD in some cases
  930. if (usePRE_BUILD) {
  931. // Cannot use PRE_BUILD with file depends
  932. if (!this->AutogenTarget.DependFiles.empty()) {
  933. usePRE_BUILD = false;
  934. }
  935. // Cannot use PRE_BUILD when a global autogen target is in place
  936. if (AutogenTarget.GlobalTarget) {
  937. usePRE_BUILD = false;
  938. }
  939. }
  940. // Create the autogen target/command
  941. if (usePRE_BUILD) {
  942. // Add additional autogen target dependencies to origin target
  943. for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
  944. this->Target->Target->AddUtility(depTarget->GetName(), makefile);
  945. }
  946. // Add the pre-build command directly to bypass the OBJECT_LIBRARY
  947. // rejection in cmMakefile::AddCustomCommandToTarget because we know
  948. // PRE_BUILD will work for an OBJECT_LIBRARY in this specific case.
  949. //
  950. // PRE_BUILD does not support file dependencies!
  951. const std::vector<std::string> no_output;
  952. const std::vector<std::string> no_deps;
  953. cmCustomCommand cc(makefile, no_output, autogenProvides, no_deps,
  954. commandLines, autogenComment.c_str(),
  955. this->Dir.Work.c_str());
  956. cc.SetEscapeOldStyle(false);
  957. cc.SetEscapeAllowMakeVars(true);
  958. this->Target->Target->AddPreBuildCommand(cc);
  959. } else {
  960. // Add link library target dependencies to the autogen target
  961. // dependencies
  962. if (this->AutogenTarget.DependOrigin) {
  963. // add_dependencies/addUtility do not support generator expressions.
  964. // We depend only on the libraries found in all configs therefore.
  965. std::map<cmGeneratorTarget const*, std::size_t> commonTargets;
  966. for (std::string const& config : this->ConfigsList) {
  967. cmLinkImplementationLibraries const* libs =
  968. this->Target->GetLinkImplementationLibraries(config);
  969. if (libs != nullptr) {
  970. for (cmLinkItem const& item : libs->Libraries) {
  971. cmGeneratorTarget const* libTarget = item.Target;
  972. if ((libTarget != nullptr) &&
  973. !StaticLibraryCycle(this->Target, libTarget, config)) {
  974. // Increment target config count
  975. commonTargets[libTarget]++;
  976. }
  977. }
  978. }
  979. }
  980. for (auto const& item : commonTargets) {
  981. if (item.second == this->ConfigsList.size()) {
  982. this->AutogenTarget.DependTargets.insert(item.first->Target);
  983. }
  984. }
  985. }
  986. // Create autogen target
  987. cmTarget* autogenTarget = makefile->AddUtilityCommand(
  988. this->AutogenTarget.Name, cmMakefile::TargetOrigin::Generator, true,
  989. this->Dir.Work.c_str(), /*byproducts=*/autogenProvides,
  990. std::vector<std::string>(this->AutogenTarget.DependFiles.begin(),
  991. this->AutogenTarget.DependFiles.end()),
  992. commandLines, false, autogenComment.c_str());
  993. // Create autogen generator target
  994. localGen->AddGeneratorTarget(
  995. new cmGeneratorTarget(autogenTarget, localGen));
  996. // Forward origin utilities to autogen target
  997. if (this->AutogenTarget.DependOrigin) {
  998. for (BT<std::string> const& depName : this->Target->GetUtilities()) {
  999. autogenTarget->AddUtility(depName.Value, makefile);
  1000. }
  1001. }
  1002. // Add additional autogen target dependencies to autogen target
  1003. for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
  1004. autogenTarget->AddUtility(depTarget->GetName(), makefile);
  1005. }
  1006. // Set FOLDER property in autogen target
  1007. if (!this->TargetsFolder.empty()) {
  1008. autogenTarget->SetProperty("FOLDER", this->TargetsFolder.c_str());
  1009. }
  1010. // Add autogen target to the origin target dependencies
  1011. this->Target->Target->AddUtility(this->AutogenTarget.Name, makefile);
  1012. // Add autogen target to the global autogen target dependencies
  1013. if (this->AutogenTarget.GlobalTarget) {
  1014. this->GlobalInitializer->AddToGlobalAutoGen(localGen,
  1015. this->AutogenTarget.Name);
  1016. }
  1017. }
  1018. return true;
  1019. }
  1020. bool cmQtAutoGenInitializer::InitRccTargets()
  1021. {
  1022. cmMakefile* makefile = this->Target->Target->GetMakefile();
  1023. cmLocalGenerator* localGen = this->Target->GetLocalGenerator();
  1024. auto rccTargetName = GetQtExecutableTargetName(this->QtVersion, "rcc");
  1025. for (Qrc const& qrc : this->Rcc.Qrcs) {
  1026. // Register info file as generated by CMake
  1027. makefile->AddCMakeOutputFile(qrc.InfoFile);
  1028. // Register file at target
  1029. this->AddGeneratedSource(qrc.RccFile, GeneratorT::RCC);
  1030. std::vector<std::string> ccOutput;
  1031. ccOutput.push_back(qrc.RccFile);
  1032. std::vector<std::string> ccDepends;
  1033. // Add the .qrc and info file to the custom command dependencies
  1034. ccDepends.push_back(qrc.QrcFile);
  1035. ccDepends.push_back(qrc.InfoFile);
  1036. cmCustomCommandLines commandLines;
  1037. if (this->MultiConfig) {
  1038. // Build for all configurations
  1039. for (std::string const& config : this->ConfigsList) {
  1040. cmCustomCommandLine currentLine;
  1041. currentLine.push_back(cmSystemTools::GetCMakeCommand());
  1042. currentLine.push_back("-E");
  1043. currentLine.push_back("cmake_autorcc");
  1044. currentLine.push_back(qrc.InfoFile);
  1045. currentLine.push_back(config);
  1046. commandLines.push_back(std::move(currentLine));
  1047. }
  1048. } else {
  1049. cmCustomCommandLine currentLine;
  1050. currentLine.push_back(cmSystemTools::GetCMakeCommand());
  1051. currentLine.push_back("-E");
  1052. currentLine.push_back("cmake_autorcc");
  1053. currentLine.push_back(qrc.InfoFile);
  1054. currentLine.push_back("$<CONFIG>");
  1055. commandLines.push_back(std::move(currentLine));
  1056. }
  1057. std::string ccComment = "Automatic RCC for ";
  1058. ccComment += FileProjectRelativePath(makefile, qrc.QrcFile);
  1059. if (qrc.Generated || this->Rcc.GlobalTarget) {
  1060. // Create custom rcc target
  1061. std::string ccName;
  1062. {
  1063. ccName = this->Target->GetName();
  1064. ccName += "_arcc_";
  1065. ccName += qrc.QrcName;
  1066. if (!qrc.Unique) {
  1067. ccName += "_";
  1068. ccName += qrc.PathChecksum;
  1069. }
  1070. cmTarget* autoRccTarget = makefile->AddUtilityCommand(
  1071. ccName, cmMakefile::TargetOrigin::Generator, true,
  1072. this->Dir.Work.c_str(), ccOutput, ccDepends, commandLines, false,
  1073. ccComment.c_str());
  1074. // Create autogen generator target
  1075. localGen->AddGeneratorTarget(
  1076. new cmGeneratorTarget(autoRccTarget, localGen));
  1077. // Set FOLDER property in autogen target
  1078. if (!this->TargetsFolder.empty()) {
  1079. autoRccTarget->SetProperty("FOLDER", this->TargetsFolder.c_str());
  1080. }
  1081. if (!rccTargetName.empty()) {
  1082. autoRccTarget->AddUtility(rccTargetName, makefile);
  1083. }
  1084. }
  1085. // Add autogen target to the origin target dependencies
  1086. this->Target->Target->AddUtility(ccName, makefile);
  1087. // Add autogen target to the global autogen target dependencies
  1088. if (this->Rcc.GlobalTarget) {
  1089. this->GlobalInitializer->AddToGlobalAutoRcc(localGen, ccName);
  1090. }
  1091. } else {
  1092. // Create custom rcc command
  1093. {
  1094. std::vector<std::string> ccByproducts;
  1095. // Add the resource files to the dependencies
  1096. for (std::string const& fileName : qrc.Resources) {
  1097. // Add resource file to the custom command dependencies
  1098. ccDepends.push_back(fileName);
  1099. }
  1100. if (!rccTargetName.empty()) {
  1101. ccDepends.push_back(rccTargetName);
  1102. }
  1103. makefile->AddCustomCommandToOutput(ccOutput, ccByproducts, ccDepends,
  1104. /*main_dependency*/ std::string(),
  1105. commandLines, ccComment.c_str(),
  1106. this->Dir.Work.c_str());
  1107. }
  1108. // Reconfigure when .qrc file changes
  1109. makefile->AddCMakeDependFile(qrc.QrcFile);
  1110. }
  1111. }
  1112. return true;
  1113. }
  1114. bool cmQtAutoGenInitializer::SetupCustomTargets()
  1115. {
  1116. // Create info directory on demand
  1117. if (!cmSystemTools::MakeDirectory(this->Dir.Info)) {
  1118. std::string emsg = ("AutoGen: Could not create directory: ");
  1119. emsg += Quoted(this->Dir.Info);
  1120. cmSystemTools::Error(emsg);
  1121. return false;
  1122. }
  1123. // Generate autogen target info file
  1124. if (this->Moc.Enabled || this->Uic.Enabled) {
  1125. // Write autogen target info files
  1126. if (!this->SetupWriteAutogenInfo()) {
  1127. return false;
  1128. }
  1129. }
  1130. // Write AUTORCC info files
  1131. return !this->Rcc.Enabled || this->SetupWriteRccInfo();
  1132. }
  1133. bool cmQtAutoGenInitializer::SetupWriteAutogenInfo()
  1134. {
  1135. InfoWriter ofs(this->AutogenTarget.InfoFile);
  1136. if (ofs) {
  1137. // Utility lambdas
  1138. cmMakefile* makefile = this->Target->Target->GetMakefile();
  1139. auto MfDef = [makefile](const char* key) {
  1140. return makefile->GetSafeDefinition(key);
  1141. };
  1142. // Write common settings
  1143. ofs.Write("# Meta\n");
  1144. ofs.Write("AM_MULTI_CONFIG", this->MultiConfig ? "TRUE" : "FALSE");
  1145. ofs.Write("AM_PARALLEL", this->AutogenTarget.Parallel);
  1146. ofs.Write("AM_VERBOSITY", this->Verbosity);
  1147. ofs.Write("# Directories\n");
  1148. ofs.Write("AM_CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
  1149. ofs.Write("AM_CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
  1150. ofs.Write("AM_CMAKE_CURRENT_SOURCE_DIR",
  1151. MfDef("CMAKE_CURRENT_SOURCE_DIR"));
  1152. ofs.Write("AM_CMAKE_CURRENT_BINARY_DIR",
  1153. MfDef("CMAKE_CURRENT_BINARY_DIR"));
  1154. ofs.Write("AM_CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE",
  1155. MfDef("CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE"));
  1156. ofs.Write("AM_BUILD_DIR", this->Dir.Build);
  1157. ofs.Write("AM_INCLUDE_DIR", this->Dir.Include);
  1158. ofs.WriteConfig("AM_INCLUDE_DIR", this->Dir.ConfigInclude);
  1159. ofs.Write("# Files\n");
  1160. ofs.WriteStrings("AM_SOURCES", this->AutogenTarget.Sources);
  1161. ofs.WriteStrings("AM_HEADERS", this->AutogenTarget.Headers);
  1162. ofs.Write("AM_SETTINGS_FILE", this->AutogenTarget.SettingsFile);
  1163. ofs.WriteConfig("AM_SETTINGS_FILE",
  1164. this->AutogenTarget.ConfigSettingsFile);
  1165. ofs.Write("# Qt\n");
  1166. ofs.WriteUInt("AM_QT_VERSION_MAJOR", this->QtVersion.Major);
  1167. ofs.Write("AM_QT_MOC_EXECUTABLE", this->Moc.Executable);
  1168. ofs.Write("AM_QT_UIC_EXECUTABLE", this->Uic.Executable);
  1169. // Write moc settings
  1170. if (this->Moc.Enabled) {
  1171. ofs.Write("# MOC settings\n");
  1172. ofs.WriteStrings("AM_MOC_SKIP", this->Moc.Skip);
  1173. ofs.WriteStrings("AM_MOC_DEFINITIONS", this->Moc.Defines);
  1174. ofs.WriteConfigStrings("AM_MOC_DEFINITIONS", this->Moc.ConfigDefines);
  1175. ofs.WriteStrings("AM_MOC_INCLUDES", this->Moc.Includes);
  1176. ofs.WriteConfigStrings("AM_MOC_INCLUDES", this->Moc.ConfigIncludes);
  1177. ofs.Write("AM_MOC_OPTIONS",
  1178. this->Target->GetSafeProperty("AUTOMOC_MOC_OPTIONS"));
  1179. ofs.Write("AM_MOC_RELAXED_MODE", MfDef("CMAKE_AUTOMOC_RELAXED_MODE"));
  1180. ofs.Write("AM_MOC_MACRO_NAMES",
  1181. this->Target->GetSafeProperty("AUTOMOC_MACRO_NAMES"));
  1182. ofs.Write("AM_MOC_DEPEND_FILTERS",
  1183. this->Target->GetSafeProperty("AUTOMOC_DEPEND_FILTERS"));
  1184. ofs.Write("AM_MOC_PREDEFS_CMD", this->Moc.PredefsCmd);
  1185. }
  1186. // Write uic settings
  1187. if (this->Uic.Enabled) {
  1188. ofs.Write("# UIC settings\n");
  1189. ofs.WriteStrings("AM_UIC_SKIP", this->Uic.Skip);
  1190. ofs.WriteStrings("AM_UIC_TARGET_OPTIONS", this->Uic.Options);
  1191. ofs.WriteConfigStrings("AM_UIC_TARGET_OPTIONS", this->Uic.ConfigOptions);
  1192. ofs.WriteStrings("AM_UIC_OPTIONS_FILES", this->Uic.FileFiles);
  1193. ofs.WriteNestedLists("AM_UIC_OPTIONS_OPTIONS", this->Uic.FileOptions);
  1194. ofs.WriteStrings("AM_UIC_SEARCH_PATHS", this->Uic.SearchPaths);
  1195. }
  1196. } else {
  1197. std::string err = "AutoGen: Could not write file ";
  1198. err += this->AutogenTarget.InfoFile;
  1199. cmSystemTools::Error(err);
  1200. return false;
  1201. }
  1202. return true;
  1203. }
  1204. bool cmQtAutoGenInitializer::SetupWriteRccInfo()
  1205. {
  1206. for (Qrc const& qrc : this->Rcc.Qrcs) {
  1207. InfoWriter ofs(qrc.InfoFile);
  1208. if (ofs) {
  1209. // Write
  1210. ofs.Write("# Configurations\n");
  1211. ofs.Write("ARCC_MULTI_CONFIG", this->MultiConfig ? "TRUE" : "FALSE");
  1212. ofs.Write("ARCC_VERBOSITY", this->Verbosity);
  1213. ofs.Write("# Settings file\n");
  1214. ofs.Write("ARCC_SETTINGS_FILE", qrc.SettingsFile);
  1215. ofs.WriteConfig("ARCC_SETTINGS_FILE", qrc.ConfigSettingsFile);
  1216. ofs.Write("# Directories\n");
  1217. ofs.Write("ARCC_BUILD_DIR", this->Dir.Build);
  1218. ofs.Write("ARCC_INCLUDE_DIR", this->Dir.Include);
  1219. ofs.WriteConfig("ARCC_INCLUDE_DIR", this->Dir.ConfigInclude);
  1220. ofs.Write("# Rcc executable\n");
  1221. ofs.Write("ARCC_RCC_EXECUTABLE", this->Rcc.Executable);
  1222. ofs.WriteStrings("ARCC_RCC_LIST_OPTIONS", this->Rcc.ListOptions);
  1223. ofs.Write("# Rcc job\n");
  1224. ofs.Write("ARCC_LOCK_FILE", qrc.LockFile);
  1225. ofs.Write("ARCC_SOURCE", qrc.QrcFile);
  1226. ofs.Write("ARCC_OUTPUT_CHECKSUM", qrc.PathChecksum);
  1227. ofs.Write("ARCC_OUTPUT_NAME",
  1228. cmSystemTools::GetFilenameName(qrc.RccFile));
  1229. ofs.WriteStrings("ARCC_OPTIONS", qrc.Options);
  1230. ofs.WriteStrings("ARCC_INPUTS", qrc.Resources);
  1231. } else {
  1232. std::string err = "AutoRcc: Could not write file ";
  1233. err += qrc.InfoFile;
  1234. cmSystemTools::Error(err);
  1235. return false;
  1236. }
  1237. }
  1238. return true;
  1239. }
  1240. void cmQtAutoGenInitializer::AddGeneratedSource(std::string const& filename,
  1241. GeneratorT genType,
  1242. bool prepend)
  1243. {
  1244. // Register source file in makefile
  1245. cmMakefile* makefile = this->Target->Target->GetMakefile();
  1246. {
  1247. cmSourceFile* gFile = makefile->GetOrCreateSource(filename, true);
  1248. gFile->SetProperty("GENERATED", "1");
  1249. gFile->SetProperty("SKIP_AUTOGEN", "On");
  1250. }
  1251. // Add source file to source group
  1252. AddToSourceGroup(makefile, filename, genType);
  1253. // Add source file to target
  1254. this->Target->AddSource(filename, prepend);
  1255. }
  1256. static unsigned int CharPtrToUInt(const char* const input)
  1257. {
  1258. unsigned long tmp = 0;
  1259. if (input != nullptr && cmSystemTools::StringToULong(input, &tmp)) {
  1260. return static_cast<unsigned int>(tmp);
  1261. }
  1262. return 0;
  1263. }
  1264. static std::vector<cmQtAutoGen::IntegerVersion> GetKnownQtVersions(
  1265. cmGeneratorTarget const* target)
  1266. {
  1267. cmMakefile* makefile = target->Target->GetMakefile();
  1268. std::vector<cmQtAutoGen::IntegerVersion> result;
  1269. // Adds a version to the result (nullptr safe)
  1270. auto addVersion = [&result](const char* major, const char* minor) {
  1271. cmQtAutoGen::IntegerVersion ver(CharPtrToUInt(major),
  1272. CharPtrToUInt(minor));
  1273. if (ver.Major != 0) {
  1274. result.emplace_back(ver);
  1275. }
  1276. };
  1277. // Qt version variable prefixes
  1278. std::array<std::string, 3> const prefixes{ { "Qt6Core", "Qt5Core", "QT" } };
  1279. // Read versions from variables
  1280. for (const std::string& prefix : prefixes) {
  1281. addVersion(makefile->GetDefinition(prefix + "_VERSION_MAJOR"),
  1282. makefile->GetDefinition(prefix + "_VERSION_MINOR"));
  1283. }
  1284. // Read versions from directory properties
  1285. for (const std::string& prefix : prefixes) {
  1286. addVersion(makefile->GetProperty(prefix + "_VERSION_MAJOR"),
  1287. makefile->GetProperty(prefix + "_VERSION_MINOR"));
  1288. }
  1289. return result;
  1290. }
  1291. std::pair<cmQtAutoGen::IntegerVersion, unsigned int>
  1292. cmQtAutoGenInitializer::GetQtVersion(cmGeneratorTarget const* target)
  1293. {
  1294. std::pair<IntegerVersion, unsigned int> res(
  1295. IntegerVersion(),
  1296. CharPtrToUInt(target->GetLinkInterfaceDependentStringProperty(
  1297. "QT_MAJOR_VERSION", "")));
  1298. auto knownQtVersions = GetKnownQtVersions(target);
  1299. if (!knownQtVersions.empty()) {
  1300. if (res.second == 0) {
  1301. // No specific version was requested by the target:
  1302. // Use highest known Qt version.
  1303. res.first = knownQtVersions.at(0);
  1304. } else {
  1305. // Pick a version from the known versions:
  1306. for (auto it : knownQtVersions) {
  1307. if (it.Major == res.second) {
  1308. res.first = it;
  1309. break;
  1310. }
  1311. }
  1312. }
  1313. }
  1314. return res;
  1315. }
  1316. std::pair<bool, std::string> GetQtExecutable(
  1317. const cmQtAutoGen::IntegerVersion& qtVersion, cmGeneratorTarget* target,
  1318. const std::string& executable, bool ignoreMissingTarget, std::string* output)
  1319. {
  1320. const std::string upperExecutable = cmSystemTools::UpperCase(executable);
  1321. std::string result =
  1322. target->Target->GetSafeProperty("AUTO" + upperExecutable + "_EXECUTABLE");
  1323. if (!result.empty()) {
  1324. cmListFileBacktrace lfbt = target->Target->GetMakefile()->GetBacktrace();
  1325. cmGeneratorExpression ge(lfbt);
  1326. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(result);
  1327. result = cge->Evaluate(target->GetLocalGenerator(), "");
  1328. return std::make_pair(true, result);
  1329. }
  1330. std::string err;
  1331. // Find executable
  1332. {
  1333. const std::string targetName =
  1334. GetQtExecutableTargetName(qtVersion, executable);
  1335. if (targetName.empty()) {
  1336. err = "The AUTO" + upperExecutable + " feature ";
  1337. err += "supports only Qt 4, Qt 5 and Qt 6.";
  1338. } else {
  1339. cmLocalGenerator* localGen = target->GetLocalGenerator();
  1340. cmGeneratorTarget* tgt = localGen->FindGeneratorTargetToUse(targetName);
  1341. if (tgt != nullptr) {
  1342. if (tgt->IsImported()) {
  1343. result = tgt->ImportedGetLocation("");
  1344. } else {
  1345. result = tgt->GetLocation("");
  1346. }
  1347. } else {
  1348. if (ignoreMissingTarget) {
  1349. return std::make_pair(true, "");
  1350. }
  1351. err = "Could not find target " + targetName;
  1352. }
  1353. }
  1354. }
  1355. // Test executable
  1356. if (err.empty()) {
  1357. if (cmSystemTools::FileExists(result, true)) {
  1358. std::vector<std::string> command;
  1359. command.push_back(result);
  1360. command.emplace_back("-h");
  1361. std::string stdOut;
  1362. std::string stdErr;
  1363. int retVal = 0;
  1364. const bool runResult = cmSystemTools::RunSingleCommand(
  1365. command, &stdOut, &stdErr, &retVal, nullptr,
  1366. cmSystemTools::OUTPUT_NONE, cmDuration::zero(), cmProcessOutput::Auto);
  1367. if (!runResult) {
  1368. err = "Test of \"" + executable + "\" binary ";
  1369. err += cmQtAutoGen::Quoted(result) + " failed: ";
  1370. err += cmQtAutoGen::QuotedCommand(command);
  1371. } else {
  1372. if (output != nullptr) {
  1373. *output = stdOut;
  1374. }
  1375. }
  1376. } else {
  1377. err = "The \"" + executable + "\" binary ";
  1378. err += cmQtAutoGen::Quoted(result);
  1379. err += " does not exist";
  1380. }
  1381. }
  1382. // Print error
  1383. if (!err.empty()) {
  1384. std::string msg = "AutoGen (";
  1385. msg += target->GetName();
  1386. msg += "): ";
  1387. msg += err;
  1388. cmSystemTools::Error(msg);
  1389. return std::make_pair(false, "");
  1390. }
  1391. return std::make_pair(true, result);
  1392. }
  1393. bool cmQtAutoGenInitializer::GetMocExecutable()
  1394. {
  1395. const auto result =
  1396. GetQtExecutable(this->QtVersion, this->Target, "moc", false, nullptr);
  1397. this->Moc.Executable = result.second;
  1398. return result.first;
  1399. }
  1400. bool cmQtAutoGenInitializer::GetUicExecutable()
  1401. {
  1402. const auto result =
  1403. GetQtExecutable(this->QtVersion, this->Target, "uic", true, nullptr);
  1404. this->Uic.Executable = result.second;
  1405. return result.first;
  1406. }
  1407. bool cmQtAutoGenInitializer::GetRccExecutable()
  1408. {
  1409. std::string stdOut;
  1410. const auto result =
  1411. GetQtExecutable(this->QtVersion, this->Target, "rcc", false, &stdOut);
  1412. this->Rcc.Executable = result.second;
  1413. if (!result.first) {
  1414. return false;
  1415. }
  1416. if (this->QtVersion.Major == 5 || this->QtVersion.Major == 6) {
  1417. if (stdOut.find("--list") != std::string::npos) {
  1418. this->Rcc.ListOptions.emplace_back("--list");
  1419. } else {
  1420. this->Rcc.ListOptions.emplace_back("-list");
  1421. }
  1422. }
  1423. return true;
  1424. }
  1425. /// @brief Reads the resource files list from from a .qrc file
  1426. /// @arg fileName Must be the absolute path of the .qrc file
  1427. /// @return True if the rcc file was successfully read
  1428. bool cmQtAutoGenInitializer::RccListInputs(std::string const& fileName,
  1429. std::vector<std::string>& files,
  1430. std::string& error)
  1431. {
  1432. if (!cmSystemTools::FileExists(fileName)) {
  1433. error = "rcc resource file does not exist:\n ";
  1434. error += Quoted(fileName);
  1435. error += "\n";
  1436. return false;
  1437. }
  1438. if (!this->Rcc.ListOptions.empty()) {
  1439. // Use rcc for file listing
  1440. if (this->Rcc.Executable.empty()) {
  1441. error = "rcc executable not available";
  1442. return false;
  1443. }
  1444. // Run rcc list command in the directory of the qrc file with the
  1445. // pathless
  1446. // qrc file name argument. This way rcc prints relative paths.
  1447. // This avoids issues on Windows when the qrc file is in a path that
  1448. // contains non-ASCII characters.
  1449. std::string const fileDir = cmSystemTools::GetFilenamePath(fileName);
  1450. std::string const fileNameName = cmSystemTools::GetFilenameName(fileName);
  1451. bool result = false;
  1452. int retVal = 0;
  1453. std::string rccStdOut;
  1454. std::string rccStdErr;
  1455. {
  1456. std::vector<std::string> cmd;
  1457. cmd.push_back(this->Rcc.Executable);
  1458. cmd.insert(cmd.end(), this->Rcc.ListOptions.begin(),
  1459. this->Rcc.ListOptions.end());
  1460. cmd.push_back(fileNameName);
  1461. result = cmSystemTools::RunSingleCommand(
  1462. cmd, &rccStdOut, &rccStdErr, &retVal, fileDir.c_str(),
  1463. cmSystemTools::OUTPUT_NONE, cmDuration::zero(), cmProcessOutput::Auto);
  1464. }
  1465. if (!result || retVal) {
  1466. error = "rcc list process failed for:\n ";
  1467. error += Quoted(fileName);
  1468. error += "\n";
  1469. error += rccStdOut;
  1470. error += "\n";
  1471. error += rccStdErr;
  1472. error += "\n";
  1473. return false;
  1474. }
  1475. if (!RccListParseOutput(rccStdOut, rccStdErr, files, error)) {
  1476. return false;
  1477. }
  1478. } else {
  1479. // We can't use rcc for the file listing.
  1480. // Read the qrc file content into string and parse it.
  1481. {
  1482. std::string qrcContents;
  1483. {
  1484. cmsys::ifstream ifs(fileName.c_str());
  1485. if (ifs) {
  1486. std::ostringstream osst;
  1487. osst << ifs.rdbuf();
  1488. qrcContents = osst.str();
  1489. } else {
  1490. error = "rcc file not readable:\n ";
  1491. error += Quoted(fileName);
  1492. error += "\n";
  1493. return false;
  1494. }
  1495. }
  1496. // Parse string content
  1497. RccListParseContent(qrcContents, files);
  1498. }
  1499. }
  1500. // Convert relative paths to absolute paths
  1501. RccListConvertFullPath(cmSystemTools::GetFilenamePath(fileName), files);
  1502. return true;
  1503. }