cmQtAutoGenInitializer.cxx 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462
  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 "cmQtAutoGen.h"
  4. #include "cmQtAutoGenInitializer.h"
  5. #include "cmAlgorithms.h"
  6. #include "cmCustomCommand.h"
  7. #include "cmCustomCommandLines.h"
  8. #include "cmDuration.h"
  9. #include "cmFilePathChecksum.h"
  10. #include "cmGeneratorTarget.h"
  11. #include "cmGlobalGenerator.h"
  12. #include "cmLinkItem.h"
  13. #include "cmLocalGenerator.h"
  14. #include "cmMakefile.h"
  15. #include "cmOutputConverter.h"
  16. #include "cmPolicies.h"
  17. #include "cmProcessOutput.h"
  18. #include "cmSourceFile.h"
  19. #include "cmSourceGroup.h"
  20. #include "cmState.h"
  21. #include "cmStateTypes.h"
  22. #include "cmSystemTools.h"
  23. #include "cmTarget.h"
  24. #include "cm_sys_stat.h"
  25. #include "cmake.h"
  26. #include "cmsys/FStream.hxx"
  27. #include "cmsys/SystemInformation.hxx"
  28. #include <algorithm>
  29. #include <array>
  30. #include <deque>
  31. #include <map>
  32. #include <set>
  33. #include <sstream>
  34. #include <string>
  35. #include <utility>
  36. #include <vector>
  37. inline static const char* SafeString(const char* value)
  38. {
  39. return (value != nullptr) ? value : "";
  40. }
  41. inline static std::string GetSafeProperty(cmGeneratorTarget const* target,
  42. const char* key)
  43. {
  44. return std::string(SafeString(target->GetProperty(key)));
  45. }
  46. inline static std::string GetSafeProperty(cmSourceFile const* sf,
  47. const char* key)
  48. {
  49. return std::string(SafeString(sf->GetProperty(key)));
  50. }
  51. static std::size_t GetParallelCPUCount()
  52. {
  53. static std::size_t count = 0;
  54. // Detect only on the first call
  55. if (count == 0) {
  56. cmsys::SystemInformation info;
  57. info.RunCPUCheck();
  58. count = info.GetNumberOfPhysicalCPU();
  59. count = std::max<std::size_t>(count, 1);
  60. count = std::min<std::size_t>(count, cmQtAutoGen::ParallelMax);
  61. }
  62. return count;
  63. }
  64. static void AddDefinitionEscaped(cmMakefile* makefile, const char* key,
  65. std::string const& value)
  66. {
  67. makefile->AddDefinition(key,
  68. cmOutputConverter::EscapeForCMake(value).c_str());
  69. }
  70. static void AddDefinitionEscaped(cmMakefile* makefile, const char* key,
  71. const std::vector<std::string>& values)
  72. {
  73. makefile->AddDefinition(
  74. key, cmOutputConverter::EscapeForCMake(cmJoin(values, ";")).c_str());
  75. }
  76. static void AddDefinitionEscaped(cmMakefile* makefile, const char* key,
  77. const std::set<std::string>& values)
  78. {
  79. makefile->AddDefinition(
  80. key, cmOutputConverter::EscapeForCMake(cmJoin(values, ";")).c_str());
  81. }
  82. static void AddDefinitionEscaped(
  83. cmMakefile* makefile, const char* key,
  84. const std::vector<std::vector<std::string>>& lists)
  85. {
  86. std::vector<std::string> seplist;
  87. for (const std::vector<std::string>& list : lists) {
  88. std::string blist = "{";
  89. blist += cmJoin(list, ";");
  90. blist += "}";
  91. seplist.push_back(std::move(blist));
  92. }
  93. makefile->AddDefinition(key, cmOutputConverter::EscapeForCMake(
  94. cmJoin(seplist, cmQtAutoGen::ListSep))
  95. .c_str());
  96. }
  97. static bool AddToSourceGroup(cmMakefile* makefile, std::string const& fileName,
  98. cmQtAutoGen::GeneratorT genType)
  99. {
  100. cmSourceGroup* sourceGroup = nullptr;
  101. // Acquire source group
  102. {
  103. std::string property;
  104. std::string groupName;
  105. {
  106. std::array<std::string, 2> props;
  107. // Use generator specific group name
  108. switch (genType) {
  109. case cmQtAutoGen::GeneratorT::MOC:
  110. props[0] = "AUTOMOC_SOURCE_GROUP";
  111. break;
  112. case cmQtAutoGen::GeneratorT::RCC:
  113. props[0] = "AUTORCC_SOURCE_GROUP";
  114. break;
  115. default:
  116. props[0] = "AUTOGEN_SOURCE_GROUP";
  117. break;
  118. }
  119. props[1] = "AUTOGEN_SOURCE_GROUP";
  120. for (std::string& prop : props) {
  121. const char* propName = makefile->GetState()->GetGlobalProperty(prop);
  122. if ((propName != nullptr) && (*propName != '\0')) {
  123. groupName = propName;
  124. property = std::move(prop);
  125. break;
  126. }
  127. }
  128. }
  129. // Generate a source group on demand
  130. if (!groupName.empty()) {
  131. sourceGroup = makefile->GetOrCreateSourceGroup(groupName);
  132. if (sourceGroup == nullptr) {
  133. std::ostringstream ost;
  134. ost << cmQtAutoGen::GeneratorNameUpper(genType);
  135. ost << ": " << property;
  136. ost << ": Could not find or create the source group ";
  137. ost << cmQtAutoGen::Quoted(groupName);
  138. cmSystemTools::Error(ost.str().c_str());
  139. return false;
  140. }
  141. }
  142. }
  143. if (sourceGroup != nullptr) {
  144. sourceGroup->AddGroupFile(fileName);
  145. }
  146. return true;
  147. }
  148. static void AddCleanFile(cmMakefile* makefile, std::string const& fileName)
  149. {
  150. makefile->AppendProperty("ADDITIONAL_MAKE_CLEAN_FILES", fileName.c_str(),
  151. false);
  152. }
  153. static std::string FileProjectRelativePath(cmMakefile* makefile,
  154. std::string const& fileName)
  155. {
  156. std::string res;
  157. {
  158. std::string pSource = cmSystemTools::RelativePath(
  159. makefile->GetCurrentSourceDirectory(), fileName.c_str());
  160. std::string pBinary = cmSystemTools::RelativePath(
  161. makefile->GetCurrentBinaryDirectory(), fileName.c_str());
  162. if (pSource.size() < pBinary.size()) {
  163. res = std::move(pSource);
  164. } else if (pBinary.size() < fileName.size()) {
  165. res = std::move(pBinary);
  166. } else {
  167. res = fileName;
  168. }
  169. }
  170. return res;
  171. }
  172. /* @brief Tests if targetDepend is a STATIC_LIBRARY and if any of its
  173. * recursive STATIC_LIBRARY dependencies depends on targetOrigin
  174. * (STATIC_LIBRARY cycle).
  175. */
  176. static bool StaticLibraryCycle(cmGeneratorTarget const* targetOrigin,
  177. cmGeneratorTarget const* targetDepend,
  178. std::string const& config)
  179. {
  180. bool cycle = false;
  181. if ((targetOrigin->GetType() == cmStateEnums::STATIC_LIBRARY) &&
  182. (targetDepend->GetType() == cmStateEnums::STATIC_LIBRARY)) {
  183. std::set<cmGeneratorTarget const*> knownLibs;
  184. std::deque<cmGeneratorTarget const*> testLibs;
  185. // Insert initial static_library dependency
  186. knownLibs.insert(targetDepend);
  187. testLibs.push_back(targetDepend);
  188. while (!testLibs.empty()) {
  189. cmGeneratorTarget const* testTarget = testLibs.front();
  190. testLibs.pop_front();
  191. // Check if the test target is the origin target (cycle)
  192. if (testTarget == targetOrigin) {
  193. cycle = true;
  194. break;
  195. }
  196. // Collect all static_library dependencies from the test target
  197. cmLinkImplementationLibraries const* libs =
  198. testTarget->GetLinkImplementationLibraries(config);
  199. if (libs != nullptr) {
  200. for (cmLinkItem const& item : libs->Libraries) {
  201. cmGeneratorTarget const* depTarget = item.Target;
  202. if ((depTarget != nullptr) &&
  203. (depTarget->GetType() == cmStateEnums::STATIC_LIBRARY) &&
  204. knownLibs.insert(depTarget).second) {
  205. testLibs.push_back(depTarget);
  206. }
  207. }
  208. }
  209. }
  210. }
  211. return cycle;
  212. }
  213. cmQtAutoGenInitializer::cmQtAutoGenInitializer(
  214. cmGeneratorTarget* target, bool mocEnabled, bool uicEnabled, bool rccEnabled,
  215. std::string const& qtVersionMajor)
  216. : Target(target)
  217. , MocEnabled(mocEnabled)
  218. , UicEnabled(uicEnabled)
  219. , RccEnabled(rccEnabled)
  220. , QtVersionMajor(qtVersionMajor)
  221. , MultiConfig(MultiConfigT::WRAPPER)
  222. {
  223. this->QtVersionMinor =
  224. cmQtAutoGenInitializer::GetQtMinorVersion(target, this->QtVersionMajor);
  225. }
  226. void cmQtAutoGenInitializer::InitCustomTargets()
  227. {
  228. cmMakefile* makefile = this->Target->Target->GetMakefile();
  229. cmLocalGenerator* localGen = this->Target->GetLocalGenerator();
  230. cmGlobalGenerator* globalGen = localGen->GetGlobalGenerator();
  231. // Configurations
  232. this->ConfigDefault = makefile->GetConfigurations(this->ConfigsList);
  233. if (this->ConfigsList.empty()) {
  234. this->ConfigsList.push_back(this->ConfigDefault);
  235. }
  236. // Multi configuration
  237. {
  238. if (!globalGen->IsMultiConfig()) {
  239. this->MultiConfig = MultiConfigT::SINGLE;
  240. }
  241. // FIXME: Xcode does not support per-config sources, yet.
  242. // (EXCLUDED_SOURCE_FILE_NAMES)
  243. // if (globalGen->GetName().find("Xcode") != std::string::npos) {
  244. // return MultiConfigT::MULTI;
  245. //}
  246. // FIXME: Visual Studio does not support per-config sources, yet.
  247. // (EXCLUDED_SOURCE_FILE_NAMES)
  248. // if (globalGen->GetName().find("Visual Studio") != std::string::npos) {
  249. // return MultiConfigT::MULTI;
  250. //}
  251. }
  252. // Autogen target name
  253. this->AutogenTargetName = this->Target->GetName();
  254. this->AutogenTargetName += "_autogen";
  255. // Autogen directories
  256. {
  257. // Collapsed current binary directory
  258. std::string const cbd = cmSystemTools::CollapseFullPath(
  259. "", makefile->GetCurrentBinaryDirectory());
  260. // Autogen info dir
  261. this->DirInfo = cbd;
  262. this->DirInfo += makefile->GetCMakeInstance()->GetCMakeFilesDirectory();
  263. this->DirInfo += "/";
  264. this->DirInfo += this->AutogenTargetName;
  265. this->DirInfo += ".dir";
  266. cmSystemTools::ConvertToUnixSlashes(this->DirInfo);
  267. // Autogen build dir
  268. this->DirBuild = GetSafeProperty(this->Target, "AUTOGEN_BUILD_DIR");
  269. if (this->DirBuild.empty()) {
  270. this->DirBuild = cbd;
  271. this->DirBuild += "/";
  272. this->DirBuild += this->AutogenTargetName;
  273. }
  274. cmSystemTools::ConvertToUnixSlashes(this->DirBuild);
  275. // Working directory
  276. this->DirWork = cbd;
  277. cmSystemTools::ConvertToUnixSlashes(this->DirWork);
  278. }
  279. // Autogen files
  280. {
  281. this->AutogenInfoFile = this->DirInfo;
  282. this->AutogenInfoFile += "/AutogenInfo.cmake";
  283. this->AutogenSettingsFile = this->DirInfo;
  284. this->AutogenSettingsFile += "/AutogenOldSettings.txt";
  285. }
  286. // Autogen target FOLDER property
  287. {
  288. const char* folder =
  289. makefile->GetState()->GetGlobalProperty("AUTOMOC_TARGETS_FOLDER");
  290. if (folder == nullptr) {
  291. folder =
  292. makefile->GetState()->GetGlobalProperty("AUTOGEN_TARGETS_FOLDER");
  293. }
  294. // Inherit FOLDER property from target (#13688)
  295. if (folder == nullptr) {
  296. folder = SafeString(this->Target->Target->GetProperty("FOLDER"));
  297. }
  298. if (folder != nullptr) {
  299. this->AutogenFolder = folder;
  300. }
  301. }
  302. std::set<std::string> autogenDependFiles;
  303. std::set<cmTarget*> autogenDependTargets;
  304. std::vector<std::string> autogenProvides;
  305. // Remove build directories on cleanup
  306. AddCleanFile(makefile, this->DirBuild);
  307. // Remove old settings on cleanup
  308. {
  309. std::string base = this->DirInfo;
  310. base += "/AutogenOldSettings";
  311. if (this->MultiConfig == MultiConfigT::SINGLE) {
  312. AddCleanFile(makefile, base.append(".cmake"));
  313. } else {
  314. for (std::string const& cfg : this->ConfigsList) {
  315. std::string filename = base;
  316. filename += "_";
  317. filename += cfg;
  318. filename += ".cmake";
  319. AddCleanFile(makefile, filename);
  320. }
  321. }
  322. }
  323. // Add moc compilation to generated files list
  324. if (this->MocEnabled) {
  325. std::string const mocsComp = this->DirBuild + "/mocs_compilation.cpp";
  326. auto files = this->AddGeneratedSource(mocsComp, GeneratorT::MOC);
  327. for (std::string& file : files) {
  328. autogenProvides.push_back(std::move(file));
  329. }
  330. }
  331. // Add autogen includes directory to the origin target INCLUDE_DIRECTORIES
  332. if (this->MocEnabled || this->UicEnabled) {
  333. std::string includeDir = this->DirBuild + "/include";
  334. if (this->MultiConfig != MultiConfigT::SINGLE) {
  335. includeDir += "_$<CONFIG>";
  336. }
  337. this->Target->AddIncludeDirectory(includeDir, true);
  338. }
  339. // Acquire rcc executable and features
  340. if (this->RccEnabled) {
  341. {
  342. std::string err;
  343. if (this->QtVersionMajor == "5") {
  344. cmGeneratorTarget* tgt =
  345. localGen->FindGeneratorTargetToUse("Qt5::rcc");
  346. if (tgt != nullptr) {
  347. this->RccExecutable = SafeString(tgt->ImportedGetLocation(""));
  348. } else {
  349. err = "AUTORCC: Qt5::rcc target not found";
  350. }
  351. } else if (QtVersionMajor == "4") {
  352. cmGeneratorTarget* tgt =
  353. localGen->FindGeneratorTargetToUse("Qt4::rcc");
  354. if (tgt != nullptr) {
  355. this->RccExecutable = SafeString(tgt->ImportedGetLocation(""));
  356. } else {
  357. err = "AUTORCC: Qt4::rcc target not found";
  358. }
  359. } else {
  360. err = "The AUTORCC feature supports only Qt 4 and Qt 5";
  361. }
  362. if (!err.empty()) {
  363. err += " (";
  364. err += this->Target->GetName();
  365. err += ")";
  366. cmSystemTools::Error(err.c_str());
  367. }
  368. }
  369. // Detect if rcc supports (-)-list
  370. if (!this->RccExecutable.empty() && (this->QtVersionMajor == "5")) {
  371. std::vector<std::string> command;
  372. command.push_back(this->RccExecutable);
  373. command.push_back("--help");
  374. std::string rccStdOut;
  375. std::string rccStdErr;
  376. int retVal = 0;
  377. bool result = cmSystemTools::RunSingleCommand(
  378. command, &rccStdOut, &rccStdErr, &retVal, nullptr,
  379. cmSystemTools::OUTPUT_NONE, cmDuration::zero(), cmProcessOutput::Auto);
  380. if (result && retVal == 0 &&
  381. rccStdOut.find("--list") != std::string::npos) {
  382. this->RccListOptions.push_back("--list");
  383. } else {
  384. this->RccListOptions.push_back("-list");
  385. }
  386. }
  387. }
  388. // Extract relevant source files
  389. std::vector<std::string> generatedSources;
  390. std::vector<std::string> generatedHeaders;
  391. {
  392. std::string const qrcExt = "qrc";
  393. std::vector<cmSourceFile*> srcFiles;
  394. this->Target->GetConfigCommonSourceFiles(srcFiles);
  395. for (cmSourceFile* sf : srcFiles) {
  396. if (sf->GetPropertyAsBool("SKIP_AUTOGEN")) {
  397. continue;
  398. }
  399. // sf->GetExtension() is only valid after sf->GetFullPath() ...
  400. std::string const& fPath = sf->GetFullPath();
  401. std::string const& ext = sf->GetExtension();
  402. // Register generated files that will be scanned by moc or uic
  403. if (this->MocEnabled || this->UicEnabled) {
  404. cmSystemTools::FileFormat const fileType =
  405. cmSystemTools::GetFileFormat(ext.c_str());
  406. if ((fileType == cmSystemTools::CXX_FILE_FORMAT) ||
  407. (fileType == cmSystemTools::HEADER_FILE_FORMAT)) {
  408. std::string const absPath = cmSystemTools::GetRealPath(fPath);
  409. if ((this->MocEnabled && !sf->GetPropertyAsBool("SKIP_AUTOMOC")) ||
  410. (this->UicEnabled && !sf->GetPropertyAsBool("SKIP_AUTOUIC"))) {
  411. // Register source
  412. const bool generated = sf->GetPropertyAsBool("GENERATED");
  413. if (fileType == cmSystemTools::HEADER_FILE_FORMAT) {
  414. if (generated) {
  415. generatedHeaders.push_back(absPath);
  416. } else {
  417. this->Headers.push_back(absPath);
  418. }
  419. } else {
  420. if (generated) {
  421. generatedSources.push_back(absPath);
  422. } else {
  423. this->Sources.push_back(absPath);
  424. }
  425. }
  426. }
  427. }
  428. }
  429. // Register rcc enabled files
  430. if (this->RccEnabled && (ext == qrcExt) &&
  431. !sf->GetPropertyAsBool("SKIP_AUTORCC")) {
  432. // Register qrc file
  433. {
  434. Qrc qrc;
  435. qrc.QrcFile = cmSystemTools::GetRealPath(fPath);
  436. qrc.QrcName =
  437. cmSystemTools::GetFilenameWithoutLastExtension(qrc.QrcFile);
  438. qrc.Generated = sf->GetPropertyAsBool("GENERATED");
  439. // RCC options
  440. {
  441. std::string const opts = GetSafeProperty(sf, "AUTORCC_OPTIONS");
  442. if (!opts.empty()) {
  443. cmSystemTools::ExpandListArgument(opts, qrc.Options);
  444. }
  445. }
  446. this->Qrcs.push_back(std::move(qrc));
  447. }
  448. }
  449. }
  450. // cmGeneratorTarget::GetConfigCommonSourceFiles computes the target's
  451. // sources meta data cache. Clear it so that OBJECT library targets that
  452. // are AUTOGEN initialized after this target get their added
  453. // mocs_compilation.cpp source acknowledged by this target.
  454. this->Target->ClearSourcesCache();
  455. }
  456. // Read skip files from makefile sources
  457. if (this->MocEnabled || this->UicEnabled) {
  458. std::string pathError;
  459. for (cmSourceFile* sf : makefile->GetSourceFiles()) {
  460. // sf->GetExtension() is only valid after sf->GetFullPath() ...
  461. // Since we're iterating over source files that might be not in the
  462. // target we need to check for path errors (not existing files).
  463. std::string const& fPath = sf->GetFullPath(&pathError);
  464. if (!pathError.empty()) {
  465. pathError.clear();
  466. continue;
  467. }
  468. cmSystemTools::FileFormat const fileType =
  469. cmSystemTools::GetFileFormat(sf->GetExtension().c_str());
  470. if (!(fileType == cmSystemTools::CXX_FILE_FORMAT) &&
  471. !(fileType == cmSystemTools::HEADER_FILE_FORMAT)) {
  472. continue;
  473. }
  474. const bool skipAll = sf->GetPropertyAsBool("SKIP_AUTOGEN");
  475. const bool mocSkip =
  476. this->MocEnabled && (skipAll || sf->GetPropertyAsBool("SKIP_AUTOMOC"));
  477. const bool uicSkip =
  478. this->UicEnabled && (skipAll || sf->GetPropertyAsBool("SKIP_AUTOUIC"));
  479. if (mocSkip || uicSkip) {
  480. std::string const absFile = cmSystemTools::GetRealPath(fPath);
  481. if (mocSkip) {
  482. this->MocSkip.insert(absFile);
  483. }
  484. if (uicSkip) {
  485. this->UicSkip.insert(absFile);
  486. }
  487. }
  488. }
  489. }
  490. // Process GENERATED sources and headers
  491. if (!generatedSources.empty() || !generatedHeaders.empty()) {
  492. // Check status of policy CMP0071
  493. bool policyAccept = false;
  494. bool policyWarn = false;
  495. cmPolicies::PolicyStatus const CMP0071_status =
  496. makefile->GetPolicyStatus(cmPolicies::CMP0071);
  497. switch (CMP0071_status) {
  498. case cmPolicies::WARN:
  499. policyWarn = true;
  500. CM_FALLTHROUGH;
  501. case cmPolicies::OLD:
  502. // Ignore GENERATED file
  503. break;
  504. case cmPolicies::REQUIRED_IF_USED:
  505. case cmPolicies::REQUIRED_ALWAYS:
  506. case cmPolicies::NEW:
  507. // Process GENERATED file
  508. policyAccept = true;
  509. break;
  510. }
  511. if (policyAccept) {
  512. // Accept GENERATED sources
  513. for (std::string const& absFile : generatedHeaders) {
  514. this->Headers.push_back(absFile);
  515. autogenDependFiles.insert(absFile);
  516. }
  517. for (std::string const& absFile : generatedSources) {
  518. this->Sources.push_back(absFile);
  519. autogenDependFiles.insert(absFile);
  520. }
  521. } else {
  522. if (policyWarn) {
  523. std::string msg;
  524. msg += cmPolicies::GetPolicyWarning(cmPolicies::CMP0071);
  525. msg += "\n";
  526. std::string tools;
  527. std::string property;
  528. if (this->MocEnabled && this->UicEnabled) {
  529. tools = "AUTOMOC and AUTOUIC";
  530. property = "SKIP_AUTOGEN";
  531. } else if (this->MocEnabled) {
  532. tools = "AUTOMOC";
  533. property = "SKIP_AUTOMOC";
  534. } else if (this->UicEnabled) {
  535. tools = "AUTOUIC";
  536. property = "SKIP_AUTOUIC";
  537. }
  538. msg += "For compatibility, CMake is excluding the GENERATED source "
  539. "file(s):\n";
  540. for (const std::string& absFile : generatedHeaders) {
  541. msg.append(" ").append(Quoted(absFile)).append("\n");
  542. }
  543. for (const std::string& absFile : generatedSources) {
  544. msg.append(" ").append(Quoted(absFile)).append("\n");
  545. }
  546. msg += "from processing by ";
  547. msg += tools;
  548. msg +=
  549. ". If any of the files should be processed, set CMP0071 to NEW. "
  550. "If any of the files should not be processed, "
  551. "explicitly exclude them by setting the source file property ";
  552. msg += property;
  553. msg += ":\n set_property(SOURCE file.h PROPERTY ";
  554. msg += property;
  555. msg += " ON)\n";
  556. makefile->IssueMessage(cmake::AUTHOR_WARNING, msg);
  557. }
  558. }
  559. // Clear lists
  560. generatedSources.clear();
  561. generatedHeaders.clear();
  562. }
  563. // Sort headers and sources
  564. if (this->MocEnabled || this->UicEnabled) {
  565. std::sort(this->Headers.begin(), this->Headers.end());
  566. std::sort(this->Sources.begin(), this->Sources.end());
  567. }
  568. // Process qrc files
  569. if (!this->Qrcs.empty()) {
  570. const bool QtV5 = (this->QtVersionMajor == "5");
  571. // Target rcc options
  572. std::vector<std::string> optionsTarget;
  573. cmSystemTools::ExpandListArgument(
  574. GetSafeProperty(this->Target, "AUTORCC_OPTIONS"), optionsTarget);
  575. // Check if file name is unique
  576. for (Qrc& qrc : this->Qrcs) {
  577. qrc.Unique = true;
  578. for (Qrc const& qrc2 : this->Qrcs) {
  579. if ((&qrc != &qrc2) && (qrc.QrcName == qrc2.QrcName)) {
  580. qrc.Unique = false;
  581. break;
  582. }
  583. }
  584. }
  585. // Path checksum and file names
  586. {
  587. cmFilePathChecksum const fpathCheckSum(makefile);
  588. for (Qrc& qrc : this->Qrcs) {
  589. qrc.PathChecksum = fpathCheckSum.getPart(qrc.QrcFile);
  590. // RCC output file name
  591. {
  592. std::string rccFile = this->DirBuild + "/";
  593. rccFile += qrc.PathChecksum;
  594. rccFile += "/qrc_";
  595. rccFile += qrc.QrcName;
  596. rccFile += ".cpp";
  597. qrc.RccFile = std::move(rccFile);
  598. }
  599. {
  600. std::string base = this->DirInfo;
  601. base += "/RCC";
  602. base += qrc.QrcName;
  603. if (!qrc.Unique) {
  604. base += qrc.PathChecksum;
  605. }
  606. qrc.InfoFile = base;
  607. qrc.InfoFile += "Info.cmake";
  608. qrc.SettingsFile = base;
  609. qrc.SettingsFile += "Settings.txt";
  610. }
  611. }
  612. }
  613. // RCC options
  614. for (Qrc& qrc : this->Qrcs) {
  615. // Target options
  616. std::vector<std::string> opts = optionsTarget;
  617. // Merge computed "-name XYZ" option
  618. {
  619. std::string name = qrc.QrcName;
  620. // Replace '-' with '_'. The former is not valid for symbol names.
  621. std::replace(name.begin(), name.end(), '-', '_');
  622. if (!qrc.Unique) {
  623. name += "_";
  624. name += qrc.PathChecksum;
  625. }
  626. std::vector<std::string> nameOpts;
  627. nameOpts.emplace_back("-name");
  628. nameOpts.emplace_back(std::move(name));
  629. RccMergeOptions(opts, nameOpts, QtV5);
  630. }
  631. // Merge file option
  632. RccMergeOptions(opts, qrc.Options, QtV5);
  633. qrc.Options = std::move(opts);
  634. }
  635. for (Qrc& qrc : this->Qrcs) {
  636. // Register file at target
  637. std::vector<std::string> const ccOutput =
  638. this->AddGeneratedSource(qrc.RccFile, GeneratorT::RCC);
  639. cmCustomCommandLines commandLines;
  640. {
  641. cmCustomCommandLine currentLine;
  642. currentLine.push_back(cmSystemTools::GetCMakeCommand());
  643. currentLine.push_back("-E");
  644. currentLine.push_back("cmake_autorcc");
  645. currentLine.push_back(qrc.InfoFile);
  646. currentLine.push_back("$<CONFIGURATION>");
  647. commandLines.push_back(std::move(currentLine));
  648. }
  649. std::string ccComment = "Automatic RCC for ";
  650. ccComment += FileProjectRelativePath(makefile, qrc.QrcFile);
  651. if (qrc.Generated) {
  652. // Create custom rcc target
  653. std::string ccName;
  654. {
  655. ccName = this->Target->GetName();
  656. ccName += "_arcc_";
  657. ccName += qrc.QrcName;
  658. if (!qrc.Unique) {
  659. ccName += "_";
  660. ccName += qrc.PathChecksum;
  661. }
  662. std::vector<std::string> ccDepends;
  663. // Add the .qrc and info file to the custom target dependencies
  664. ccDepends.push_back(qrc.QrcFile);
  665. ccDepends.push_back(qrc.InfoFile);
  666. cmTarget* autoRccTarget = makefile->AddUtilityCommand(
  667. ccName, cmMakefile::TargetOrigin::Generator, true,
  668. this->DirWork.c_str(), ccOutput, ccDepends, commandLines, false,
  669. ccComment.c_str());
  670. // Create autogen generator target
  671. localGen->AddGeneratorTarget(
  672. new cmGeneratorTarget(autoRccTarget, localGen));
  673. // Set FOLDER property in autogen target
  674. if (!this->AutogenFolder.empty()) {
  675. autoRccTarget->SetProperty("FOLDER", this->AutogenFolder.c_str());
  676. }
  677. }
  678. // Add autogen target to the origin target dependencies
  679. this->Target->Target->AddUtility(ccName, makefile);
  680. } else {
  681. // Create custom rcc command
  682. {
  683. std::vector<std::string> ccByproducts;
  684. std::vector<std::string> ccDepends;
  685. // Add the .qrc and info file to the custom command dependencies
  686. ccDepends.push_back(qrc.QrcFile);
  687. ccDepends.push_back(qrc.InfoFile);
  688. // Add the resource files to the dependencies
  689. {
  690. std::string error;
  691. if (RccListInputs(qrc.QrcFile, qrc.Resources, error)) {
  692. for (std::string const& fileName : qrc.Resources) {
  693. // Add resource file to the custom command dependencies
  694. ccDepends.push_back(fileName);
  695. }
  696. } else {
  697. cmSystemTools::Error(error.c_str());
  698. }
  699. }
  700. makefile->AddCustomCommandToOutput(ccOutput, ccByproducts, ccDepends,
  701. /*main_dependency*/ std::string(),
  702. commandLines, ccComment.c_str(),
  703. this->DirWork.c_str());
  704. }
  705. // Reconfigure when .qrc file changes
  706. makefile->AddCMakeDependFile(qrc.QrcFile);
  707. }
  708. }
  709. }
  710. // Create _autogen target
  711. if (this->MocEnabled || this->UicEnabled) {
  712. // Add user defined autogen target dependencies
  713. {
  714. std::string const deps =
  715. GetSafeProperty(this->Target, "AUTOGEN_TARGET_DEPENDS");
  716. if (!deps.empty()) {
  717. std::vector<std::string> extraDeps;
  718. cmSystemTools::ExpandListArgument(deps, extraDeps);
  719. for (std::string const& depName : extraDeps) {
  720. // Allow target and file dependencies
  721. auto* depTarget = makefile->FindTargetToUse(depName);
  722. if (depTarget != nullptr) {
  723. autogenDependTargets.insert(depTarget);
  724. } else {
  725. autogenDependFiles.insert(depName);
  726. }
  727. }
  728. }
  729. }
  730. // Compose target comment
  731. std::string autogenComment;
  732. {
  733. std::string tools;
  734. if (this->MocEnabled) {
  735. tools += "MOC";
  736. }
  737. if (this->UicEnabled) {
  738. if (!tools.empty()) {
  739. tools += " and ";
  740. }
  741. tools += "UIC";
  742. }
  743. autogenComment = "Automatic ";
  744. autogenComment += tools;
  745. autogenComment += " for target ";
  746. autogenComment += this->Target->GetName();
  747. }
  748. // Compose command lines
  749. cmCustomCommandLines commandLines;
  750. {
  751. cmCustomCommandLine currentLine;
  752. currentLine.push_back(cmSystemTools::GetCMakeCommand());
  753. currentLine.push_back("-E");
  754. currentLine.push_back("cmake_autogen");
  755. currentLine.push_back(this->AutogenInfoFile);
  756. currentLine.push_back("$<CONFIGURATION>");
  757. commandLines.push_back(std::move(currentLine));
  758. }
  759. // Use PRE_BUILD on demand
  760. bool usePRE_BUILD = false;
  761. if (globalGen->GetName().find("Visual Studio") != std::string::npos) {
  762. // Under VS use a PRE_BUILD event instead of a separate target to
  763. // reduce the number of targets loaded into the IDE.
  764. // This also works around a VS 11 bug that may skip updating the target:
  765. // https://connect.microsoft.com/VisualStudio/feedback/details/769495
  766. usePRE_BUILD = true;
  767. }
  768. // Disable PRE_BUILD in some cases
  769. if (usePRE_BUILD) {
  770. // Cannot use PRE_BUILD with file depends
  771. if (!autogenDependFiles.empty()) {
  772. usePRE_BUILD = false;
  773. }
  774. }
  775. // Create the autogen target/command
  776. if (usePRE_BUILD) {
  777. // Add additional autogen target dependencies to origin target
  778. for (cmTarget* depTarget : autogenDependTargets) {
  779. this->Target->Target->AddUtility(depTarget->GetName(), makefile);
  780. }
  781. // Add the pre-build command directly to bypass the OBJECT_LIBRARY
  782. // rejection in cmMakefile::AddCustomCommandToTarget because we know
  783. // PRE_BUILD will work for an OBJECT_LIBRARY in this specific case.
  784. //
  785. // PRE_BUILD does not support file dependencies!
  786. const std::vector<std::string> no_output;
  787. const std::vector<std::string> no_deps;
  788. cmCustomCommand cc(makefile, no_output, autogenProvides, no_deps,
  789. commandLines, autogenComment.c_str(),
  790. this->DirWork.c_str());
  791. cc.SetEscapeOldStyle(false);
  792. cc.SetEscapeAllowMakeVars(true);
  793. this->Target->Target->AddPreBuildCommand(cc);
  794. } else {
  795. // Add link library target dependencies to the autogen target
  796. // dependencies
  797. {
  798. // add_dependencies/addUtility do not support generator expressions.
  799. // We depend only on the libraries found in all configs therefore.
  800. std::map<cmGeneratorTarget const*, std::size_t> commonTargets;
  801. for (std::string const& config : this->ConfigsList) {
  802. cmLinkImplementationLibraries const* libs =
  803. this->Target->GetLinkImplementationLibraries(config);
  804. if (libs != nullptr) {
  805. for (cmLinkItem const& item : libs->Libraries) {
  806. cmGeneratorTarget const* libTarget = item.Target;
  807. if ((libTarget != nullptr) &&
  808. !StaticLibraryCycle(this->Target, libTarget, config)) {
  809. // Increment target config count
  810. commonTargets[libTarget]++;
  811. }
  812. }
  813. }
  814. }
  815. for (auto const& item : commonTargets) {
  816. if (item.second == this->ConfigsList.size()) {
  817. autogenDependTargets.insert(item.first->Target);
  818. }
  819. }
  820. }
  821. // Create autogen target
  822. cmTarget* autogenTarget = makefile->AddUtilityCommand(
  823. this->AutogenTargetName, cmMakefile::TargetOrigin::Generator, true,
  824. this->DirWork.c_str(), /*byproducts=*/autogenProvides,
  825. std::vector<std::string>(autogenDependFiles.begin(),
  826. autogenDependFiles.end()),
  827. commandLines, false, autogenComment.c_str());
  828. // Create autogen generator target
  829. localGen->AddGeneratorTarget(
  830. new cmGeneratorTarget(autogenTarget, localGen));
  831. // Forward origin utilities to autogen target
  832. for (std::string const& depName : this->Target->Target->GetUtilities()) {
  833. autogenTarget->AddUtility(depName, makefile);
  834. }
  835. // Add additional autogen target dependencies to autogen target
  836. for (cmTarget* depTarget : autogenDependTargets) {
  837. autogenTarget->AddUtility(depTarget->GetName(), makefile);
  838. }
  839. // Set FOLDER property in autogen target
  840. if (!this->AutogenFolder.empty()) {
  841. autogenTarget->SetProperty("FOLDER", this->AutogenFolder.c_str());
  842. }
  843. // Add autogen target to the origin target dependencies
  844. this->Target->Target->AddUtility(this->AutogenTargetName, makefile);
  845. }
  846. }
  847. }
  848. void cmQtAutoGenInitializer::SetupCustomTargets()
  849. {
  850. cmMakefile* makefile = this->Target->Target->GetMakefile();
  851. // forget the variables added here afterwards again:
  852. cmMakefile::ScopePushPop varScope(makefile);
  853. static_cast<void>(varScope);
  854. // Configuration suffixes
  855. std::map<std::string, std::string> configSuffixes;
  856. for (std::string const& cfg : this->ConfigsList) {
  857. std::string& suffix = configSuffixes[cfg];
  858. suffix = "_";
  859. suffix += cfg;
  860. }
  861. // Basic setup
  862. AddDefinitionEscaped(makefile, "_multi_config",
  863. MultiConfigName(this->MultiConfig));
  864. AddDefinitionEscaped(makefile, "_build_dir", this->DirBuild);
  865. {
  866. std::string parallel = GetSafeProperty(this->Target, "AUTOGEN_PARALLEL");
  867. // Autodetect number of CPUs
  868. if (parallel.empty() || (parallel == "AUTO")) {
  869. parallel = std::to_string(GetParallelCPUCount());
  870. }
  871. AddDefinitionEscaped(makefile, "_parallel", parallel);
  872. }
  873. if (this->MocEnabled || this->UicEnabled) {
  874. AddDefinitionEscaped(makefile, "_qt_version_major", this->QtVersionMajor);
  875. AddDefinitionEscaped(makefile, "_settings_file",
  876. this->AutogenSettingsFile);
  877. AddDefinitionEscaped(makefile, "_sources", this->Sources);
  878. AddDefinitionEscaped(makefile, "_headers", this->Headers);
  879. if (this->MocEnabled) {
  880. this->SetupCustomTargetsMoc();
  881. }
  882. if (this->UicEnabled) {
  883. this->SetupCustomTargetsUic();
  884. }
  885. }
  886. if (this->RccEnabled) {
  887. AddDefinitionEscaped(makefile, "_qt_rcc_executable", this->RccExecutable);
  888. AddDefinitionEscaped(makefile, "_qt_rcc_list_options",
  889. this->RccListOptions);
  890. }
  891. // Create info directory on demand
  892. if (!cmSystemTools::MakeDirectory(this->DirInfo)) {
  893. std::string emsg = ("Could not create directory: ");
  894. emsg += Quoted(this->DirInfo);
  895. cmSystemTools::Error(emsg.c_str());
  896. }
  897. auto ReOpenInfoFile = [](cmsys::ofstream& ofs,
  898. std::string const& fileName) -> bool {
  899. // Ensure we have write permission
  900. mode_t perm = 0;
  901. #if defined(_WIN32) && !defined(__CYGWIN__)
  902. mode_t mode_write = S_IWRITE;
  903. #else
  904. mode_t mode_write = S_IWUSR;
  905. #endif
  906. cmSystemTools::GetPermissions(fileName, perm);
  907. if (!(perm & mode_write)) {
  908. cmSystemTools::SetPermissions(fileName, perm | mode_write);
  909. }
  910. ofs.open(fileName.c_str(), std::ios::app);
  911. if (!ofs) {
  912. // File open error
  913. std::string error = "Internal CMake error when trying to open file: ";
  914. error += Quoted(fileName);
  915. error += " for writing.";
  916. cmSystemTools::Error(error.c_str());
  917. }
  918. return static_cast<bool>(ofs);
  919. };
  920. // Generate autogen target info file
  921. if (this->MocEnabled || this->UicEnabled) {
  922. {
  923. std::string infoFileIn = cmSystemTools::GetCMakeRoot();
  924. infoFileIn += "/Modules/AutogenInfo.cmake.in";
  925. makefile->ConfigureFile(
  926. infoFileIn.c_str(), this->AutogenInfoFile.c_str(), false, true, false);
  927. }
  928. // Append custom definitions to info file
  929. // --------------------------------------
  930. cmsys::ofstream ofs;
  931. if (ReOpenInfoFile(ofs, this->AutogenInfoFile)) {
  932. auto OfsWriteMap = [&ofs](
  933. const char* key, std::map<std::string, std::string> const& map) {
  934. for (auto const& item : map) {
  935. ofs << "set(" << key << "_" << item.first << " "
  936. << cmOutputConverter::EscapeForCMake(item.second) << ")\n";
  937. }
  938. };
  939. ofs << "# Configurations options\n";
  940. OfsWriteMap("AM_CONFIG_SUFFIX", configSuffixes);
  941. OfsWriteMap("AM_MOC_DEFINITIONS", this->ConfigMocDefines);
  942. OfsWriteMap("AM_MOC_INCLUDES", this->ConfigMocIncludes);
  943. OfsWriteMap("AM_UIC_TARGET_OPTIONS", this->ConfigUicOptions);
  944. // Settings files (only require for multi configuration generators)
  945. if (this->MultiConfig != MultiConfigT::SINGLE) {
  946. std::map<std::string, std::string> settingsFiles;
  947. for (std::string const& cfg : this->ConfigsList) {
  948. settingsFiles[cfg] =
  949. AppendFilenameSuffix(this->AutogenSettingsFile, "_" + cfg);
  950. }
  951. OfsWriteMap("AM_SETTINGS_FILE", settingsFiles);
  952. }
  953. }
  954. }
  955. // Generate auto RCC info files
  956. if (this->RccEnabled) {
  957. std::string infoFileIn = cmSystemTools::GetCMakeRoot();
  958. infoFileIn += "/Modules/AutoRccInfo.cmake.in";
  959. for (Qrc const& qrc : this->Qrcs) {
  960. // Configure info file
  961. makefile->ConfigureFile(infoFileIn.c_str(), qrc.InfoFile.c_str(), false,
  962. true, false);
  963. // Append custom definitions to info file
  964. // --------------------------------------
  965. cmsys::ofstream ofs;
  966. if (ReOpenInfoFile(ofs, qrc.InfoFile)) {
  967. {
  968. ofs << "# Job\n";
  969. auto OfsWrite = [&ofs](const char* key, std::string const& value) {
  970. ofs << "set(" << key << " "
  971. << cmOutputConverter::EscapeForCMake(value) << ")\n";
  972. };
  973. OfsWrite("ARCC_SETTINGS_FILE", qrc.SettingsFile);
  974. OfsWrite("ARCC_SOURCE", qrc.QrcFile);
  975. OfsWrite("ARCC_OUTPUT", qrc.RccFile);
  976. OfsWrite("ARCC_OPTIONS", cmJoin(qrc.Options, ";"));
  977. OfsWrite("ARCC_INPUTS", cmJoin(qrc.Resources, ";"));
  978. }
  979. {
  980. ofs << "# Configurations options\n";
  981. auto OfsWriteMap = [&ofs](
  982. const char* key, std::map<std::string, std::string> const& map) {
  983. for (auto const& item : map) {
  984. ofs << "set(" << key << "_" << item.first << " "
  985. << cmOutputConverter::EscapeForCMake(item.second) << ")\n";
  986. }
  987. };
  988. OfsWriteMap("ARCC_CONFIG_SUFFIX", configSuffixes);
  989. // Settings files (only require for multi configuration generators)
  990. if (this->MultiConfig != MultiConfigT::SINGLE) {
  991. std::map<std::string, std::string> settingsFiles;
  992. for (std::string const& cfg : this->ConfigsList) {
  993. settingsFiles[cfg] =
  994. AppendFilenameSuffix(qrc.SettingsFile, "_" + cfg);
  995. }
  996. OfsWriteMap("ARCC_SETTINGS_FILE", settingsFiles);
  997. }
  998. }
  999. } else {
  1000. break;
  1001. }
  1002. }
  1003. }
  1004. }
  1005. void cmQtAutoGenInitializer::SetupCustomTargetsMoc()
  1006. {
  1007. cmLocalGenerator* localGen = this->Target->GetLocalGenerator();
  1008. cmMakefile* makefile = this->Target->Target->GetMakefile();
  1009. AddDefinitionEscaped(makefile, "_moc_skip", this->MocSkip);
  1010. AddDefinitionEscaped(makefile, "_moc_options",
  1011. GetSafeProperty(this->Target, "AUTOMOC_MOC_OPTIONS"));
  1012. AddDefinitionEscaped(makefile, "_moc_relaxed_mode",
  1013. makefile->IsOn("CMAKE_AUTOMOC_RELAXED_MODE") ? "TRUE"
  1014. : "FALSE");
  1015. AddDefinitionEscaped(makefile, "_moc_macro_names",
  1016. GetSafeProperty(this->Target, "AUTOMOC_MACRO_NAMES"));
  1017. AddDefinitionEscaped(
  1018. makefile, "_moc_depend_filters",
  1019. GetSafeProperty(this->Target, "AUTOMOC_DEPEND_FILTERS"));
  1020. // Compiler predefines
  1021. if (this->Target->GetPropertyAsBool("AUTOMOC_COMPILER_PREDEFINES") &&
  1022. this->QtVersionGreaterOrEqual(5, 8)) {
  1023. AddDefinitionEscaped(
  1024. makefile, "_moc_predefs_cmd",
  1025. makefile->GetSafeDefinition("CMAKE_CXX_COMPILER_PREDEFINES_COMMAND"));
  1026. }
  1027. // Moc includes and compile definitions
  1028. {
  1029. auto GetIncludeDirs = [this,
  1030. localGen](std::string const& cfg) -> std::string {
  1031. // Get the include dirs for this target, without stripping the implicit
  1032. // include dirs off, see
  1033. // https://gitlab.kitware.com/cmake/cmake/issues/13667
  1034. std::vector<std::string> includeDirs;
  1035. localGen->GetIncludeDirectories(includeDirs, this->Target, "CXX", cfg,
  1036. false);
  1037. return cmJoin(includeDirs, ";");
  1038. };
  1039. auto GetCompileDefinitions =
  1040. [this, localGen](std::string const& cfg) -> std::string {
  1041. std::set<std::string> defines;
  1042. localGen->AddCompileDefinitions(defines, this->Target, cfg, "CXX");
  1043. return cmJoin(defines, ";");
  1044. };
  1045. // Default configuration settings
  1046. std::string const includeDirs = GetIncludeDirs(this->ConfigDefault);
  1047. std::string const compileDefs = GetCompileDefinitions(this->ConfigDefault);
  1048. // Other configuration settings
  1049. for (std::string const& cfg : this->ConfigsList) {
  1050. {
  1051. std::string const configIncludeDirs = GetIncludeDirs(cfg);
  1052. if (configIncludeDirs != includeDirs) {
  1053. this->ConfigMocIncludes[cfg] = configIncludeDirs;
  1054. }
  1055. }
  1056. {
  1057. std::string const configCompileDefs = GetCompileDefinitions(cfg);
  1058. if (configCompileDefs != compileDefs) {
  1059. this->ConfigMocDefines[cfg] = configCompileDefs;
  1060. }
  1061. }
  1062. }
  1063. AddDefinitionEscaped(makefile, "_moc_include_dirs", includeDirs);
  1064. AddDefinitionEscaped(makefile, "_moc_compile_defs", compileDefs);
  1065. }
  1066. // Moc executable
  1067. {
  1068. std::string mocExec;
  1069. std::string err;
  1070. if (this->QtVersionMajor == "5") {
  1071. cmGeneratorTarget* tgt = localGen->FindGeneratorTargetToUse("Qt5::moc");
  1072. if (tgt != nullptr) {
  1073. mocExec = SafeString(tgt->ImportedGetLocation(""));
  1074. } else {
  1075. err = "AUTOMOC: Qt5::moc target not found";
  1076. }
  1077. } else if (this->QtVersionMajor == "4") {
  1078. cmGeneratorTarget* tgt = localGen->FindGeneratorTargetToUse("Qt4::moc");
  1079. if (tgt != nullptr) {
  1080. mocExec = SafeString(tgt->ImportedGetLocation(""));
  1081. } else {
  1082. err = "AUTOMOC: Qt4::moc target not found";
  1083. }
  1084. } else {
  1085. err = "The AUTOMOC feature supports only Qt 4 and Qt 5";
  1086. }
  1087. if (err.empty()) {
  1088. AddDefinitionEscaped(makefile, "_qt_moc_executable", mocExec);
  1089. } else {
  1090. err += " (";
  1091. err += this->Target->GetName();
  1092. err += ")";
  1093. cmSystemTools::Error(err.c_str());
  1094. }
  1095. }
  1096. }
  1097. void cmQtAutoGenInitializer::SetupCustomTargetsUic()
  1098. {
  1099. cmMakefile* makefile = this->Target->Target->GetMakefile();
  1100. // Uic search paths
  1101. {
  1102. std::vector<std::string> uicSearchPaths;
  1103. {
  1104. std::string const usp =
  1105. GetSafeProperty(this->Target, "AUTOUIC_SEARCH_PATHS");
  1106. if (!usp.empty()) {
  1107. cmSystemTools::ExpandListArgument(usp, uicSearchPaths);
  1108. std::string const srcDir = makefile->GetCurrentSourceDirectory();
  1109. for (std::string& path : uicSearchPaths) {
  1110. path = cmSystemTools::CollapseFullPath(path, srcDir);
  1111. }
  1112. }
  1113. }
  1114. AddDefinitionEscaped(makefile, "_uic_search_paths", uicSearchPaths);
  1115. }
  1116. // Uic target options
  1117. {
  1118. auto UicGetOpts = [this](std::string const& cfg) -> std::string {
  1119. std::vector<std::string> opts;
  1120. this->Target->GetAutoUicOptions(opts, cfg);
  1121. return cmJoin(opts, ";");
  1122. };
  1123. // Default settings
  1124. std::string const uicOpts = UicGetOpts(this->ConfigDefault);
  1125. AddDefinitionEscaped(makefile, "_uic_target_options", uicOpts);
  1126. // Configuration specific settings
  1127. for (std::string const& cfg : this->ConfigsList) {
  1128. std::string const configUicOpts = UicGetOpts(cfg);
  1129. if (configUicOpts != uicOpts) {
  1130. this->ConfigUicOptions[cfg] = configUicOpts;
  1131. }
  1132. }
  1133. }
  1134. // .ui files skip and options
  1135. {
  1136. std::vector<std::string> uiFileFiles;
  1137. std::vector<std::vector<std::string>> uiFileOptions;
  1138. {
  1139. std::string const uiExt = "ui";
  1140. std::string pathError;
  1141. for (cmSourceFile* sf : makefile->GetSourceFiles()) {
  1142. // sf->GetExtension() is only valid after sf->GetFullPath() ...
  1143. // Since we're iterating over source files that might be not in the
  1144. // target we need to check for path errors (not existing files).
  1145. std::string const& fPath = sf->GetFullPath(&pathError);
  1146. if (!pathError.empty()) {
  1147. pathError.clear();
  1148. continue;
  1149. }
  1150. if (sf->GetExtension() == uiExt) {
  1151. std::string const absFile = cmSystemTools::GetRealPath(fPath);
  1152. // Check if the .ui file should be skipped
  1153. if (sf->GetPropertyAsBool("SKIP_AUTOUIC") ||
  1154. sf->GetPropertyAsBool("SKIP_AUTOGEN")) {
  1155. this->UicSkip.insert(absFile);
  1156. }
  1157. // Check if the .ui file has uic options
  1158. std::string const uicOpts = GetSafeProperty(sf, "AUTOUIC_OPTIONS");
  1159. if (!uicOpts.empty()) {
  1160. // Check if file isn't skipped
  1161. if (this->UicSkip.count(absFile) == 0) {
  1162. uiFileFiles.push_back(absFile);
  1163. std::vector<std::string> optsVec;
  1164. cmSystemTools::ExpandListArgument(uicOpts, optsVec);
  1165. uiFileOptions.push_back(std::move(optsVec));
  1166. }
  1167. }
  1168. }
  1169. }
  1170. }
  1171. AddDefinitionEscaped(makefile, "_qt_uic_options_files", uiFileFiles);
  1172. AddDefinitionEscaped(makefile, "_qt_uic_options_options", uiFileOptions);
  1173. }
  1174. AddDefinitionEscaped(makefile, "_uic_skip", this->UicSkip);
  1175. // Uic executable
  1176. {
  1177. std::string err;
  1178. std::string uicExec;
  1179. cmLocalGenerator* localGen = this->Target->GetLocalGenerator();
  1180. if (this->QtVersionMajor == "5") {
  1181. cmGeneratorTarget* tgt = localGen->FindGeneratorTargetToUse("Qt5::uic");
  1182. if (tgt != nullptr) {
  1183. uicExec = SafeString(tgt->ImportedGetLocation(""));
  1184. } else {
  1185. // Project does not use Qt5Widgets, but has AUTOUIC ON anyway
  1186. }
  1187. } else if (this->QtVersionMajor == "4") {
  1188. cmGeneratorTarget* tgt = localGen->FindGeneratorTargetToUse("Qt4::uic");
  1189. if (tgt != nullptr) {
  1190. uicExec = SafeString(tgt->ImportedGetLocation(""));
  1191. } else {
  1192. err = "AUTOUIC: Qt4::uic target not found";
  1193. }
  1194. } else {
  1195. err = "The AUTOUIC feature supports only Qt 4 and Qt 5";
  1196. }
  1197. if (err.empty()) {
  1198. AddDefinitionEscaped(makefile, "_qt_uic_executable", uicExec);
  1199. } else {
  1200. err += " (";
  1201. err += this->Target->GetName();
  1202. err += ")";
  1203. cmSystemTools::Error(err.c_str());
  1204. }
  1205. }
  1206. }
  1207. std::vector<std::string> cmQtAutoGenInitializer::AddGeneratedSource(
  1208. std::string const& filename, GeneratorT genType)
  1209. {
  1210. std::vector<std::string> genFiles;
  1211. // Register source file in makefile and source group
  1212. if (this->MultiConfig != MultiConfigT::MULTI) {
  1213. genFiles.push_back(filename);
  1214. } else {
  1215. for (std::string const& cfg : this->ConfigsList) {
  1216. genFiles.push_back(AppendFilenameSuffix(filename, "_" + cfg));
  1217. }
  1218. }
  1219. {
  1220. cmMakefile* makefile = this->Target->Target->GetMakefile();
  1221. for (std::string const& genFile : genFiles) {
  1222. {
  1223. cmSourceFile* gFile = makefile->GetOrCreateSource(genFile, true);
  1224. gFile->SetProperty("GENERATED", "1");
  1225. gFile->SetProperty("SKIP_AUTOGEN", "On");
  1226. }
  1227. AddToSourceGroup(makefile, genFile, genType);
  1228. }
  1229. }
  1230. // Add source file to target
  1231. if (this->MultiConfig != MultiConfigT::MULTI) {
  1232. this->Target->AddSource(filename);
  1233. } else {
  1234. for (std::string const& cfg : this->ConfigsList) {
  1235. std::string src = "$<$<CONFIG:";
  1236. src += cfg;
  1237. src += ">:";
  1238. src += AppendFilenameSuffix(filename, "_" + cfg);
  1239. src += ">";
  1240. this->Target->AddSource(src);
  1241. }
  1242. }
  1243. return genFiles;
  1244. }
  1245. std::string cmQtAutoGenInitializer::GetQtMajorVersion(
  1246. cmGeneratorTarget const* target)
  1247. {
  1248. cmMakefile* makefile = target->Target->GetMakefile();
  1249. std::string qtMajor = makefile->GetSafeDefinition("QT_VERSION_MAJOR");
  1250. if (qtMajor.empty()) {
  1251. qtMajor = makefile->GetSafeDefinition("Qt5Core_VERSION_MAJOR");
  1252. }
  1253. const char* targetQtVersion =
  1254. target->GetLinkInterfaceDependentStringProperty("QT_MAJOR_VERSION", "");
  1255. if (targetQtVersion != nullptr) {
  1256. qtMajor = targetQtVersion;
  1257. }
  1258. return qtMajor;
  1259. }
  1260. std::string cmQtAutoGenInitializer::GetQtMinorVersion(
  1261. cmGeneratorTarget const* target, std::string const& qtVersionMajor)
  1262. {
  1263. cmMakefile* makefile = target->Target->GetMakefile();
  1264. std::string qtMinor;
  1265. if (qtVersionMajor == "5") {
  1266. qtMinor = makefile->GetSafeDefinition("Qt5Core_VERSION_MINOR");
  1267. }
  1268. if (qtMinor.empty()) {
  1269. qtMinor = makefile->GetSafeDefinition("QT_VERSION_MINOR");
  1270. }
  1271. const char* targetQtVersion =
  1272. target->GetLinkInterfaceDependentStringProperty("QT_MINOR_VERSION", "");
  1273. if (targetQtVersion != nullptr) {
  1274. qtMinor = targetQtVersion;
  1275. }
  1276. return qtMinor;
  1277. }
  1278. bool cmQtAutoGenInitializer::QtVersionGreaterOrEqual(
  1279. unsigned long requestMajor, unsigned long requestMinor) const
  1280. {
  1281. unsigned long majorUL(0);
  1282. unsigned long minorUL(0);
  1283. if (cmSystemTools::StringToULong(this->QtVersionMajor.c_str(), &majorUL) &&
  1284. cmSystemTools::StringToULong(this->QtVersionMinor.c_str(), &minorUL)) {
  1285. return (majorUL > requestMajor) ||
  1286. (majorUL == requestMajor && minorUL >= requestMinor);
  1287. }
  1288. return false;
  1289. }
  1290. /// @brief Reads the resource files list from from a .qrc file
  1291. /// @arg fileName Must be the absolute path of the .qrc file
  1292. /// @return True if the rcc file was successfully read
  1293. bool cmQtAutoGenInitializer::RccListInputs(std::string const& fileName,
  1294. std::vector<std::string>& files,
  1295. std::string& error)
  1296. {
  1297. if (!cmSystemTools::FileExists(fileName.c_str())) {
  1298. error = "rcc resource file does not exist:\n ";
  1299. error += Quoted(fileName);
  1300. error += "\n";
  1301. return false;
  1302. }
  1303. if (!RccListOptions.empty()) {
  1304. // Use rcc for file listing
  1305. if (RccExecutable.empty()) {
  1306. error = "rcc executable not available";
  1307. return false;
  1308. }
  1309. // Run rcc list command in the directory of the qrc file with the pathless
  1310. // qrc file name argument. This way rcc prints relative paths.
  1311. // This avoids issues on Windows when the qrc file is in a path that
  1312. // contains non-ASCII characters.
  1313. std::string const fileDir = cmSystemTools::GetFilenamePath(fileName);
  1314. std::string const fileNameName = cmSystemTools::GetFilenameName(fileName);
  1315. bool result = false;
  1316. int retVal = 0;
  1317. std::string rccStdOut;
  1318. std::string rccStdErr;
  1319. {
  1320. std::vector<std::string> cmd;
  1321. cmd.push_back(RccExecutable);
  1322. cmd.insert(cmd.end(), RccListOptions.begin(), RccListOptions.end());
  1323. cmd.push_back(fileNameName);
  1324. result = cmSystemTools::RunSingleCommand(
  1325. cmd, &rccStdOut, &rccStdErr, &retVal, fileDir.c_str(),
  1326. cmSystemTools::OUTPUT_NONE, cmDuration::zero(), cmProcessOutput::Auto);
  1327. }
  1328. if (!result || retVal) {
  1329. error = "rcc list process failed for:\n ";
  1330. error += Quoted(fileName);
  1331. error += "\n";
  1332. error += rccStdOut;
  1333. error += "\n";
  1334. error += rccStdErr;
  1335. error += "\n";
  1336. return false;
  1337. }
  1338. if (!RccListParseOutput(rccStdOut, rccStdErr, files, error)) {
  1339. return false;
  1340. }
  1341. } else {
  1342. // We can't use rcc for the file listing.
  1343. // Read the qrc file content into string and parse it.
  1344. {
  1345. std::string qrcContents;
  1346. {
  1347. cmsys::ifstream ifs(fileName.c_str());
  1348. if (ifs) {
  1349. std::ostringstream osst;
  1350. osst << ifs.rdbuf();
  1351. qrcContents = osst.str();
  1352. } else {
  1353. error = "rcc file not readable:\n ";
  1354. error += Quoted(fileName);
  1355. error += "\n";
  1356. return false;
  1357. }
  1358. }
  1359. // Parse string content
  1360. RccListParseContent(qrcContents, files);
  1361. }
  1362. }
  1363. // Convert relative paths to absolute paths
  1364. RccListConvertFullPath(cmSystemTools::GetFilenamePath(fileName), files);
  1365. return true;
  1366. }