cmQtAutoGenInitializer.cxx 53 KB

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