cmQtAutoGeneratorInitializer.cxx 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091
  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 "cmQtAutoGeneratorInitializer.h"
  5. #include "cmAlgorithms.h"
  6. #include "cmCustomCommand.h"
  7. #include "cmCustomCommandLines.h"
  8. #include "cmFilePathChecksum.h"
  9. #include "cmGeneratorTarget.h"
  10. #include "cmGlobalGenerator.h"
  11. #include "cmLocalGenerator.h"
  12. #include "cmMakefile.h"
  13. #include "cmOutputConverter.h"
  14. #include "cmPolicies.h"
  15. #include "cmSourceFile.h"
  16. #include "cmSourceGroup.h"
  17. #include "cmState.h"
  18. #include "cmSystemTools.h"
  19. #include "cmTarget.h"
  20. #include "cm_sys_stat.h"
  21. #include "cmake.h"
  22. #include "cmsys/FStream.hxx"
  23. #include <algorithm>
  24. #include <array>
  25. #include <map>
  26. #include <set>
  27. #include <sstream>
  28. #include <string>
  29. #include <utility>
  30. #include <vector>
  31. inline static const char* SafeString(const char* value)
  32. {
  33. return (value != nullptr) ? value : "";
  34. }
  35. inline static std::string GetSafeProperty(cmGeneratorTarget const* target,
  36. const char* key)
  37. {
  38. return std::string(SafeString(target->GetProperty(key)));
  39. }
  40. inline static std::string GetSafeProperty(cmSourceFile const* sf,
  41. const char* key)
  42. {
  43. return std::string(SafeString(sf->GetProperty(key)));
  44. }
  45. inline static bool AutogenMultiConfig(cmGlobalGenerator* globalGen)
  46. {
  47. return globalGen->IsMultiConfig();
  48. }
  49. static std::string GetAutogenTargetName(cmGeneratorTarget const* target)
  50. {
  51. std::string autogenTargetName = target->GetName();
  52. autogenTargetName += "_autogen";
  53. return autogenTargetName;
  54. }
  55. static std::string GetAutogenTargetFilesDir(cmGeneratorTarget const* target)
  56. {
  57. cmMakefile* makefile = target->Target->GetMakefile();
  58. std::string targetDir = makefile->GetCurrentBinaryDirectory();
  59. targetDir += makefile->GetCMakeInstance()->GetCMakeFilesDirectory();
  60. targetDir += "/";
  61. targetDir += GetAutogenTargetName(target);
  62. targetDir += ".dir";
  63. return targetDir;
  64. }
  65. static std::string GetAutogenTargetBuildDir(cmGeneratorTarget const* target)
  66. {
  67. std::string targetDir = GetSafeProperty(target, "AUTOGEN_BUILD_DIR");
  68. if (targetDir.empty()) {
  69. cmMakefile* makefile = target->Target->GetMakefile();
  70. targetDir = makefile->GetCurrentBinaryDirectory();
  71. targetDir += "/";
  72. targetDir += GetAutogenTargetName(target);
  73. }
  74. return targetDir;
  75. }
  76. std::string cmQtAutoGeneratorInitializer::GetQtMajorVersion(
  77. cmGeneratorTarget const* target)
  78. {
  79. cmMakefile* makefile = target->Target->GetMakefile();
  80. std::string qtMajor = makefile->GetSafeDefinition("QT_VERSION_MAJOR");
  81. if (qtMajor.empty()) {
  82. qtMajor = makefile->GetSafeDefinition("Qt5Core_VERSION_MAJOR");
  83. }
  84. const char* targetQtVersion =
  85. target->GetLinkInterfaceDependentStringProperty("QT_MAJOR_VERSION", "");
  86. if (targetQtVersion != nullptr) {
  87. qtMajor = targetQtVersion;
  88. }
  89. return qtMajor;
  90. }
  91. std::string cmQtAutoGeneratorInitializer::GetQtMinorVersion(
  92. cmGeneratorTarget const* target, const std::string& qtVersionMajor)
  93. {
  94. cmMakefile* makefile = target->Target->GetMakefile();
  95. std::string qtMinor;
  96. if (qtVersionMajor == "5") {
  97. qtMinor = makefile->GetSafeDefinition("Qt5Core_VERSION_MINOR");
  98. }
  99. if (qtMinor.empty()) {
  100. qtMinor = makefile->GetSafeDefinition("QT_VERSION_MINOR");
  101. }
  102. const char* targetQtVersion =
  103. target->GetLinkInterfaceDependentStringProperty("QT_MINOR_VERSION", "");
  104. if (targetQtVersion != nullptr) {
  105. qtMinor = targetQtVersion;
  106. }
  107. return qtMinor;
  108. }
  109. static bool QtVersionGreaterOrEqual(const std::string& major,
  110. const std::string& minor,
  111. unsigned long requestMajor,
  112. unsigned long requestMinor)
  113. {
  114. unsigned long majorUL(0);
  115. unsigned long minorUL(0);
  116. if (cmSystemTools::StringToULong(major.c_str(), &majorUL) &&
  117. cmSystemTools::StringToULong(minor.c_str(), &minorUL)) {
  118. return (majorUL > requestMajor) ||
  119. (majorUL == requestMajor && minorUL >= requestMinor);
  120. }
  121. return false;
  122. }
  123. static std::vector<std::string> GetConfigurations(
  124. cmMakefile* makefile, std::string* config = nullptr)
  125. {
  126. std::vector<std::string> configs;
  127. {
  128. std::string cfg = makefile->GetConfigurations(configs);
  129. if (config != nullptr) {
  130. *config = cfg;
  131. }
  132. }
  133. // Add empty configuration on demand
  134. if (configs.empty()) {
  135. configs.push_back("");
  136. }
  137. return configs;
  138. }
  139. static std::vector<std::string> GetConfigurationSuffixes(cmMakefile* makefile)
  140. {
  141. std::vector<std::string> suffixes;
  142. if (AutogenMultiConfig(makefile->GetGlobalGenerator())) {
  143. makefile->GetConfigurations(suffixes);
  144. for (std::string& suffix : suffixes) {
  145. suffix.insert(0, "_");
  146. }
  147. }
  148. if (suffixes.empty()) {
  149. suffixes.push_back("");
  150. }
  151. return suffixes;
  152. }
  153. static void AddDefinitionEscaped(cmMakefile* makefile, const char* key,
  154. const std::string& value)
  155. {
  156. makefile->AddDefinition(key,
  157. cmOutputConverter::EscapeForCMake(value).c_str());
  158. }
  159. static void AddDefinitionEscaped(cmMakefile* makefile, const char* key,
  160. const std::vector<std::string>& values)
  161. {
  162. makefile->AddDefinition(
  163. key, cmOutputConverter::EscapeForCMake(cmJoin(values, ";")).c_str());
  164. }
  165. static void AddDefinitionEscaped(cmMakefile* makefile, const char* key,
  166. const std::set<std::string>& values)
  167. {
  168. makefile->AddDefinition(
  169. key, cmOutputConverter::EscapeForCMake(cmJoin(values, ";")).c_str());
  170. }
  171. static void AddDefinitionEscaped(
  172. cmMakefile* makefile, const char* key,
  173. const std::vector<std::vector<std::string>>& lists)
  174. {
  175. std::vector<std::string> seplist;
  176. for (const std::vector<std::string>& list : lists) {
  177. std::string blist = "{";
  178. blist += cmJoin(list, ";");
  179. blist += "}";
  180. seplist.push_back(std::move(blist));
  181. }
  182. makefile->AddDefinition(key, cmOutputConverter::EscapeForCMake(
  183. cmJoin(seplist, cmQtAutoGen::listSep))
  184. .c_str());
  185. }
  186. static bool AddToSourceGroup(cmMakefile* makefile, const std::string& fileName,
  187. cmQtAutoGen::GeneratorType genType)
  188. {
  189. cmSourceGroup* sourceGroup = nullptr;
  190. // Acquire source group
  191. {
  192. std::string property;
  193. std::string groupName;
  194. {
  195. std::array<std::string, 2> props;
  196. // Use generator specific group name
  197. switch (genType) {
  198. case cmQtAutoGen::MOC:
  199. props[0] = "AUTOMOC_SOURCE_GROUP";
  200. break;
  201. case cmQtAutoGen::RCC:
  202. props[0] = "AUTORCC_SOURCE_GROUP";
  203. break;
  204. default:
  205. props[0] = "AUTOGEN_SOURCE_GROUP";
  206. break;
  207. }
  208. props[1] = "AUTOGEN_SOURCE_GROUP";
  209. for (std::string& prop : props) {
  210. const char* propName = makefile->GetState()->GetGlobalProperty(prop);
  211. if ((propName != nullptr) && (*propName != '\0')) {
  212. groupName = propName;
  213. property = std::move(prop);
  214. break;
  215. }
  216. }
  217. }
  218. // Generate a source group on demand
  219. if (!groupName.empty()) {
  220. sourceGroup = makefile->GetOrCreateSourceGroup(groupName);
  221. if (sourceGroup == nullptr) {
  222. std::ostringstream ost;
  223. ost << cmQtAutoGen::GeneratorNameUpper(genType);
  224. ost << ": " << property;
  225. ost << ": Could not find or create the source group ";
  226. ost << cmQtAutoGen::Quoted(groupName);
  227. cmSystemTools::Error(ost.str().c_str());
  228. return false;
  229. }
  230. }
  231. }
  232. if (sourceGroup != nullptr) {
  233. sourceGroup->AddGroupFile(fileName);
  234. }
  235. return true;
  236. }
  237. static void AddCleanFile(cmMakefile* makefile, const std::string& fileName)
  238. {
  239. makefile->AppendProperty("ADDITIONAL_MAKE_CLEAN_FILES", fileName.c_str(),
  240. false);
  241. }
  242. static void AddGeneratedSource(cmGeneratorTarget* target,
  243. const std::string& filename,
  244. cmQtAutoGen::GeneratorType genType)
  245. {
  246. cmMakefile* makefile = target->Target->GetMakefile();
  247. {
  248. cmSourceFile* gFile = makefile->GetOrCreateSource(filename, true);
  249. gFile->SetProperty("GENERATED", "1");
  250. gFile->SetProperty("SKIP_AUTOGEN", "On");
  251. }
  252. target->AddSource(filename);
  253. AddToSourceGroup(makefile, filename, genType);
  254. }
  255. struct cmQtAutoGenSetup
  256. {
  257. std::set<std::string> MocSkip;
  258. std::set<std::string> UicSkip;
  259. std::map<std::string, std::string> ConfigMocIncludes;
  260. std::map<std::string, std::string> ConfigMocDefines;
  261. std::map<std::string, std::string> ConfigUicOptions;
  262. };
  263. static void SetupAcquireSkipFiles(cmQtAutoGenDigest const& digest,
  264. cmQtAutoGenSetup& setup)
  265. {
  266. // Read skip files from makefile sources
  267. {
  268. const std::vector<cmSourceFile*>& allSources =
  269. digest.Target->Makefile->GetSourceFiles();
  270. for (cmSourceFile* sf : allSources) {
  271. // sf->GetExtension() is only valid after sf->GetFullPath() ...
  272. const std::string& fPath = sf->GetFullPath();
  273. const cmSystemTools::FileFormat fileType =
  274. cmSystemTools::GetFileFormat(sf->GetExtension().c_str());
  275. if (!(fileType == cmSystemTools::CXX_FILE_FORMAT) &&
  276. !(fileType == cmSystemTools::HEADER_FILE_FORMAT)) {
  277. continue;
  278. }
  279. const bool skipAll = sf->GetPropertyAsBool("SKIP_AUTOGEN");
  280. const bool mocSkip = digest.MocEnabled &&
  281. (skipAll || sf->GetPropertyAsBool("SKIP_AUTOMOC"));
  282. const bool uicSkip = digest.UicEnabled &&
  283. (skipAll || sf->GetPropertyAsBool("SKIP_AUTOUIC"));
  284. if (mocSkip || uicSkip) {
  285. const std::string absFile = cmSystemTools::GetRealPath(fPath);
  286. if (mocSkip) {
  287. setup.MocSkip.insert(absFile);
  288. }
  289. if (uicSkip) {
  290. setup.UicSkip.insert(absFile);
  291. }
  292. }
  293. }
  294. }
  295. }
  296. static void SetupAutoTargetMoc(const cmQtAutoGenDigest& digest,
  297. std::string const& config,
  298. std::vector<std::string> const& configs,
  299. cmQtAutoGenSetup& setup)
  300. {
  301. cmGeneratorTarget const* target = digest.Target;
  302. cmLocalGenerator* localGen = target->GetLocalGenerator();
  303. cmMakefile* makefile = target->Target->GetMakefile();
  304. AddDefinitionEscaped(makefile, "_moc_skip", setup.MocSkip);
  305. AddDefinitionEscaped(makefile, "_moc_options",
  306. GetSafeProperty(target, "AUTOMOC_MOC_OPTIONS"));
  307. AddDefinitionEscaped(makefile, "_moc_relaxed_mode",
  308. makefile->IsOn("CMAKE_AUTOMOC_RELAXED_MODE") ? "TRUE"
  309. : "FALSE");
  310. AddDefinitionEscaped(makefile, "_moc_macro_names",
  311. GetSafeProperty(target, "AUTOMOC_MACRO_NAMES"));
  312. AddDefinitionEscaped(makefile, "_moc_depend_filters",
  313. GetSafeProperty(target, "AUTOMOC_DEPEND_FILTERS"));
  314. if (QtVersionGreaterOrEqual(digest.QtVersionMajor, digest.QtVersionMinor, 5,
  315. 8)) {
  316. AddDefinitionEscaped(
  317. makefile, "_moc_predefs_cmd",
  318. makefile->GetSafeDefinition("CMAKE_CXX_COMPILER_PREDEFINES_COMMAND"));
  319. }
  320. // Moc includes and compile definitions
  321. {
  322. auto GetCompileDefinitionsAndDirectories = [target, localGen](
  323. const std::string& cfg, std::string& incs, std::string& defs) {
  324. {
  325. std::vector<std::string> includeDirs;
  326. // Get the include dirs for this target, without stripping the implicit
  327. // include dirs off, see
  328. // https://gitlab.kitware.com/cmake/cmake/issues/13667
  329. localGen->GetIncludeDirectories(includeDirs, target, "CXX", cfg,
  330. false);
  331. incs = cmJoin(includeDirs, ";");
  332. }
  333. {
  334. std::set<std::string> defines;
  335. localGen->AddCompileDefinitions(defines, target, cfg, "CXX");
  336. defs += cmJoin(defines, ";");
  337. }
  338. };
  339. // Default settings
  340. std::string incs;
  341. std::string compileDefs;
  342. GetCompileDefinitionsAndDirectories(config, incs, compileDefs);
  343. AddDefinitionEscaped(makefile, "_moc_incs", incs);
  344. AddDefinitionEscaped(makefile, "_moc_compile_defs", compileDefs);
  345. // Configuration specific settings
  346. for (const std::string& cfg : configs) {
  347. std::string configIncs;
  348. std::string configCompileDefs;
  349. GetCompileDefinitionsAndDirectories(cfg, configIncs, configCompileDefs);
  350. if (configIncs != incs) {
  351. setup.ConfigMocIncludes[cfg] = configIncs;
  352. }
  353. if (configCompileDefs != compileDefs) {
  354. setup.ConfigMocDefines[cfg] = configCompileDefs;
  355. }
  356. }
  357. }
  358. // Moc executable
  359. {
  360. std::string mocExec;
  361. std::string err;
  362. if (digest.QtVersionMajor == "5") {
  363. cmGeneratorTarget* tgt = localGen->FindGeneratorTargetToUse("Qt5::moc");
  364. if (tgt != nullptr) {
  365. mocExec = SafeString(tgt->ImportedGetLocation(""));
  366. } else {
  367. err = "AUTOMOC: Qt5::moc target not found";
  368. }
  369. } else if (digest.QtVersionMajor == "4") {
  370. cmGeneratorTarget* tgt = localGen->FindGeneratorTargetToUse("Qt4::moc");
  371. if (tgt != nullptr) {
  372. mocExec = SafeString(tgt->ImportedGetLocation(""));
  373. } else {
  374. err = "AUTOMOC: Qt4::moc target not found";
  375. }
  376. } else {
  377. err = "The AUTOMOC feature supports only Qt 4 and Qt 5";
  378. }
  379. if (err.empty()) {
  380. AddDefinitionEscaped(makefile, "_qt_moc_executable", mocExec);
  381. } else {
  382. err += " (" + target->GetName() + ")";
  383. cmSystemTools::Error(err.c_str());
  384. }
  385. }
  386. }
  387. static void SetupAutoTargetUic(const cmQtAutoGenDigest& digest,
  388. std::string const& config,
  389. std::vector<std::string> const& configs,
  390. cmQtAutoGenSetup& setup)
  391. {
  392. cmGeneratorTarget const* target = digest.Target;
  393. cmMakefile* makefile = target->Target->GetMakefile();
  394. AddDefinitionEscaped(makefile, "_uic_skip", setup.UicSkip);
  395. // Uic search paths
  396. {
  397. std::vector<std::string> uicSearchPaths;
  398. {
  399. const std::string usp = GetSafeProperty(target, "AUTOUIC_SEARCH_PATHS");
  400. if (!usp.empty()) {
  401. cmSystemTools::ExpandListArgument(usp, uicSearchPaths);
  402. const std::string srcDir = makefile->GetCurrentSourceDirectory();
  403. for (std::string& path : uicSearchPaths) {
  404. path = cmSystemTools::CollapseFullPath(path, srcDir);
  405. }
  406. }
  407. }
  408. AddDefinitionEscaped(makefile, "_uic_search_paths", uicSearchPaths);
  409. }
  410. // Uic target options
  411. {
  412. auto UicGetOpts = [target](const std::string& cfg) -> std::string {
  413. std::vector<std::string> opts;
  414. target->GetAutoUicOptions(opts, cfg);
  415. return cmJoin(opts, ";");
  416. };
  417. // Default settings
  418. const std::string uicOpts = UicGetOpts(config);
  419. AddDefinitionEscaped(makefile, "_uic_target_options", uicOpts);
  420. // Configuration specific settings
  421. for (const std::string& cfg : configs) {
  422. const std::string configUicOpts = UicGetOpts(cfg);
  423. if (configUicOpts != uicOpts) {
  424. setup.ConfigUicOptions[cfg] = configUicOpts;
  425. }
  426. }
  427. }
  428. // Uic files options
  429. {
  430. std::vector<std::string> uiFileFiles;
  431. std::vector<std::vector<std::string>> uiFileOptions;
  432. {
  433. const std::string uiExt = "ui";
  434. const std::vector<cmSourceFile*>& srcFiles = makefile->GetSourceFiles();
  435. for (cmSourceFile* sf : srcFiles) {
  436. // sf->GetExtension() is only valid after sf->GetFullPath() ...
  437. const std::string& fPath = sf->GetFullPath();
  438. if (sf->GetExtension() == uiExt) {
  439. // Check if the files has uic options
  440. const std::string uicOpts = GetSafeProperty(sf, "AUTOUIC_OPTIONS");
  441. if (!uicOpts.empty()) {
  442. const std::string absFile = cmSystemTools::GetRealPath(fPath);
  443. // Check if file isn't skipped
  444. if (setup.UicSkip.count(absFile) == 0) {
  445. uiFileFiles.push_back(absFile);
  446. std::vector<std::string> optsVec;
  447. cmSystemTools::ExpandListArgument(uicOpts, optsVec);
  448. uiFileOptions.push_back(std::move(optsVec));
  449. }
  450. }
  451. }
  452. }
  453. }
  454. AddDefinitionEscaped(makefile, "_qt_uic_options_files", uiFileFiles);
  455. AddDefinitionEscaped(makefile, "_qt_uic_options_options", uiFileOptions);
  456. }
  457. // Uic executable
  458. {
  459. std::string err;
  460. std::string uicExec;
  461. cmLocalGenerator* localGen = target->GetLocalGenerator();
  462. if (digest.QtVersionMajor == "5") {
  463. cmGeneratorTarget* tgt = localGen->FindGeneratorTargetToUse("Qt5::uic");
  464. if (tgt != nullptr) {
  465. uicExec = SafeString(tgt->ImportedGetLocation(""));
  466. } else {
  467. // Project does not use Qt5Widgets, but has AUTOUIC ON anyway
  468. }
  469. } else if (digest.QtVersionMajor == "4") {
  470. cmGeneratorTarget* tgt = localGen->FindGeneratorTargetToUse("Qt4::uic");
  471. if (tgt != nullptr) {
  472. uicExec = SafeString(tgt->ImportedGetLocation(""));
  473. } else {
  474. err = "AUTOUIC: Qt4::uic target not found";
  475. }
  476. } else {
  477. err = "The AUTOUIC feature supports only Qt 4 and Qt 5";
  478. }
  479. if (err.empty()) {
  480. AddDefinitionEscaped(makefile, "_qt_uic_executable", uicExec);
  481. } else {
  482. err += " (" + target->GetName() + ")";
  483. cmSystemTools::Error(err.c_str());
  484. }
  485. }
  486. }
  487. static std::string RccGetExecutable(cmGeneratorTarget const* target,
  488. const std::string& qtMajorVersion)
  489. {
  490. std::string rccExec;
  491. std::string err;
  492. cmLocalGenerator* localGen = target->GetLocalGenerator();
  493. if (qtMajorVersion == "5") {
  494. cmGeneratorTarget* tgt = localGen->FindGeneratorTargetToUse("Qt5::rcc");
  495. if (tgt != nullptr) {
  496. rccExec = SafeString(tgt->ImportedGetLocation(""));
  497. } else {
  498. err = "AUTORCC: Qt5::rcc target not found";
  499. }
  500. } else if (qtMajorVersion == "4") {
  501. cmGeneratorTarget* tgt = localGen->FindGeneratorTargetToUse("Qt4::rcc");
  502. if (tgt != nullptr) {
  503. rccExec = SafeString(tgt->ImportedGetLocation(""));
  504. } else {
  505. err = "AUTORCC: Qt4::rcc target not found";
  506. }
  507. } else {
  508. err = "The AUTORCC feature supports only Qt 4 and Qt 5";
  509. }
  510. if (!err.empty()) {
  511. err += " (" + target->GetName() + ")";
  512. cmSystemTools::Error(err.c_str());
  513. }
  514. return rccExec;
  515. }
  516. static void SetupAutoTargetRcc(const cmQtAutoGenDigest& digest)
  517. {
  518. std::vector<std::string> rccFiles;
  519. std::vector<std::string> rccBuilds;
  520. std::vector<std::vector<std::string>> rccOptions;
  521. std::vector<std::vector<std::string>> rccInputs;
  522. for (const cmQtAutoGenDigestQrc& qrcDigest : digest.Qrcs) {
  523. rccFiles.push_back(qrcDigest.QrcFile);
  524. rccBuilds.push_back(qrcDigest.RccFile);
  525. rccOptions.push_back(qrcDigest.Options);
  526. rccInputs.push_back(qrcDigest.Resources);
  527. }
  528. cmMakefile* makefile = digest.Target->Target->GetMakefile();
  529. AddDefinitionEscaped(makefile, "_qt_rcc_executable",
  530. RccGetExecutable(digest.Target, digest.QtVersionMajor));
  531. AddDefinitionEscaped(makefile, "_rcc_files", rccFiles);
  532. AddDefinitionEscaped(makefile, "_rcc_builds", rccBuilds);
  533. AddDefinitionEscaped(makefile, "_rcc_options", rccOptions);
  534. AddDefinitionEscaped(makefile, "_rcc_inputs", rccInputs);
  535. }
  536. void cmQtAutoGeneratorInitializer::InitializeAutogenTarget(
  537. cmQtAutoGenDigest& digest)
  538. {
  539. cmGeneratorTarget* target = digest.Target;
  540. cmMakefile* makefile = target->Target->GetMakefile();
  541. cmLocalGenerator* localGen = target->GetLocalGenerator();
  542. cmGlobalGenerator* globalGen = localGen->GetGlobalGenerator();
  543. // Create a custom target for running generators at buildtime
  544. const bool multiConfig = AutogenMultiConfig(globalGen);
  545. const std::string autogenTargetName = GetAutogenTargetName(target);
  546. const std::string autogenBuildDir = GetAutogenTargetBuildDir(target);
  547. const std::string workingDirectory =
  548. cmSystemTools::CollapseFullPath("", makefile->GetCurrentBinaryDirectory());
  549. const std::vector<std::string> suffixes = GetConfigurationSuffixes(makefile);
  550. std::set<std::string> autogenDependFiles;
  551. std::set<std::string> autogenDependTargets;
  552. std::vector<std::string> autogenProvides;
  553. // Remove build directories on cleanup
  554. AddCleanFile(makefile, autogenBuildDir);
  555. // Remove old settings on cleanup
  556. {
  557. std::string base = GetAutogenTargetFilesDir(target);
  558. base += "/AutogenOldSettings";
  559. for (const std::string& suffix : suffixes) {
  560. AddCleanFile(makefile, (base + suffix).append(".cmake"));
  561. }
  562. }
  563. // Compose command lines
  564. cmCustomCommandLines commandLines;
  565. {
  566. cmCustomCommandLine currentLine;
  567. currentLine.push_back(cmSystemTools::GetCMakeCommand());
  568. currentLine.push_back("-E");
  569. currentLine.push_back("cmake_autogen");
  570. currentLine.push_back(GetAutogenTargetFilesDir(target));
  571. currentLine.push_back("$<CONFIGURATION>");
  572. commandLines.push_back(currentLine);
  573. }
  574. // Compose target comment
  575. std::string autogenComment;
  576. {
  577. std::vector<std::string> toolNames;
  578. if (digest.MocEnabled) {
  579. toolNames.push_back("MOC");
  580. }
  581. if (digest.UicEnabled) {
  582. toolNames.push_back("UIC");
  583. }
  584. if (digest.RccEnabled) {
  585. toolNames.push_back("RCC");
  586. }
  587. std::string tools = toolNames[0];
  588. toolNames.erase(toolNames.begin());
  589. while (toolNames.size() > 1) {
  590. tools += ", " + toolNames[0];
  591. toolNames.erase(toolNames.begin());
  592. }
  593. if (toolNames.size() == 1) {
  594. tools += " and " + toolNames[0];
  595. }
  596. autogenComment = "Automatic " + tools + " for target " + target->GetName();
  597. }
  598. // Add moc compilation to generated files list
  599. if (digest.MocEnabled) {
  600. const std::string mocsComp = autogenBuildDir + "/mocs_compilation.cpp";
  601. AddGeneratedSource(target, mocsComp, cmQtAutoGen::MOC);
  602. autogenProvides.push_back(mocsComp);
  603. }
  604. // Add autogen includes directory to the origin target INCLUDE_DIRECTORIES
  605. if (digest.MocEnabled || digest.UicEnabled) {
  606. std::string includeDir = autogenBuildDir + "/include";
  607. if (multiConfig) {
  608. includeDir += "_$<CONFIG>";
  609. }
  610. target->AddIncludeDirectory(includeDir, true);
  611. }
  612. // Extract relevant source files
  613. std::vector<std::string> generatedSources;
  614. std::vector<std::string> generatedHeaders;
  615. {
  616. const std::string qrcExt = "qrc";
  617. std::vector<cmSourceFile*> srcFiles;
  618. target->GetConfigCommonSourceFiles(srcFiles);
  619. for (cmSourceFile* sf : srcFiles) {
  620. if (sf->GetPropertyAsBool("SKIP_AUTOGEN")) {
  621. continue;
  622. }
  623. // sf->GetExtension() is only valid after sf->GetFullPath() ...
  624. const std::string& fPath = sf->GetFullPath();
  625. const std::string& ext = sf->GetExtension();
  626. // Register generated files that will be scanned by moc or uic
  627. if (digest.MocEnabled || digest.UicEnabled) {
  628. const cmSystemTools::FileFormat fileType =
  629. cmSystemTools::GetFileFormat(ext.c_str());
  630. if ((fileType == cmSystemTools::CXX_FILE_FORMAT) ||
  631. (fileType == cmSystemTools::HEADER_FILE_FORMAT)) {
  632. const std::string absPath = cmSystemTools::GetRealPath(fPath);
  633. if ((digest.MocEnabled && !sf->GetPropertyAsBool("SKIP_AUTOMOC")) ||
  634. (digest.UicEnabled && !sf->GetPropertyAsBool("SKIP_AUTOUIC"))) {
  635. // Register source
  636. const bool generated = sf->GetPropertyAsBool("GENERATED");
  637. if (fileType == cmSystemTools::HEADER_FILE_FORMAT) {
  638. if (generated) {
  639. generatedHeaders.push_back(absPath);
  640. } else {
  641. digest.Headers.push_back(absPath);
  642. }
  643. } else {
  644. if (generated) {
  645. generatedSources.push_back(absPath);
  646. } else {
  647. digest.Sources.push_back(absPath);
  648. }
  649. }
  650. }
  651. }
  652. }
  653. // Register rcc enabled files
  654. if (digest.RccEnabled && (ext == qrcExt) &&
  655. !sf->GetPropertyAsBool("SKIP_AUTORCC")) {
  656. // Register qrc file
  657. {
  658. cmQtAutoGenDigestQrc qrcDigest;
  659. qrcDigest.QrcFile = cmSystemTools::GetRealPath(fPath);
  660. qrcDigest.QrcName =
  661. cmSystemTools::GetFilenameWithoutLastExtension(qrcDigest.QrcFile);
  662. qrcDigest.Generated = sf->GetPropertyAsBool("GENERATED");
  663. // RCC options
  664. {
  665. const std::string opts = GetSafeProperty(sf, "AUTORCC_OPTIONS");
  666. if (!opts.empty()) {
  667. cmSystemTools::ExpandListArgument(opts, qrcDigest.Options);
  668. }
  669. }
  670. digest.Qrcs.push_back(std::move(qrcDigest));
  671. }
  672. }
  673. }
  674. // cmGeneratorTarget::GetConfigCommonSourceFiles computes the target's
  675. // sources meta data cache. Clear it so that OBJECT library targets that
  676. // are AUTOGEN initialized after this target get their added
  677. // mocs_compilation.cpp source acknowledged by this target.
  678. target->ClearSourcesCache();
  679. }
  680. // Process GENERATED sources and headers
  681. if (!generatedSources.empty() || !generatedHeaders.empty()) {
  682. // Check status of policy CMP0071
  683. bool policyAccept = false;
  684. bool policyWarn = false;
  685. const cmPolicies::PolicyStatus CMP0071_status =
  686. target->Makefile->GetPolicyStatus(cmPolicies::CMP0071);
  687. switch (CMP0071_status) {
  688. case cmPolicies::WARN:
  689. policyWarn = true;
  690. CM_FALLTHROUGH;
  691. case cmPolicies::OLD:
  692. // Ignore GENERATED file
  693. break;
  694. case cmPolicies::REQUIRED_IF_USED:
  695. case cmPolicies::REQUIRED_ALWAYS:
  696. case cmPolicies::NEW:
  697. // Process GENERATED file
  698. policyAccept = true;
  699. break;
  700. }
  701. if (policyAccept) {
  702. // Accept GENERATED sources
  703. for (const std::string& absFile : generatedHeaders) {
  704. digest.Headers.push_back(absFile);
  705. autogenDependFiles.insert(absFile);
  706. }
  707. for (const std::string& absFile : generatedSources) {
  708. digest.Sources.push_back(absFile);
  709. autogenDependFiles.insert(absFile);
  710. }
  711. } else {
  712. if (policyWarn) {
  713. std::string msg;
  714. msg += cmPolicies::GetPolicyWarning(cmPolicies::CMP0071);
  715. msg += "\n";
  716. std::string tools;
  717. if (digest.MocEnabled) {
  718. tools += "AUTOMOC";
  719. }
  720. if (digest.UicEnabled) {
  721. if (!tools.empty()) {
  722. tools += ",";
  723. }
  724. tools += "AUTOUIC";
  725. }
  726. if (!generatedHeaders.empty()) {
  727. msg.append(tools).append(": Ignoring GENERATED header file(s):\n");
  728. for (const std::string& absFile : generatedHeaders) {
  729. msg.append(" ").append(cmQtAutoGen::Quoted(absFile)).append("\n");
  730. }
  731. }
  732. if (!generatedSources.empty()) {
  733. msg.append(tools).append(": Ignoring GENERATED source file(s):\n");
  734. for (const std::string& absFile : generatedSources) {
  735. msg.append(" ").append(cmQtAutoGen::Quoted(absFile)).append("\n");
  736. }
  737. }
  738. makefile->IssueMessage(cmake::AUTHOR_WARNING, msg);
  739. }
  740. }
  741. }
  742. // Sort headers and sources
  743. std::sort(digest.Headers.begin(), digest.Headers.end());
  744. std::sort(digest.Sources.begin(), digest.Sources.end());
  745. // Process qrc files
  746. if (!digest.Qrcs.empty()) {
  747. const bool QtV5 = (digest.QtVersionMajor == "5");
  748. const std::string rcc = RccGetExecutable(target, digest.QtVersionMajor);
  749. // Target rcc options
  750. std::vector<std::string> optionsTarget;
  751. cmSystemTools::ExpandListArgument(
  752. GetSafeProperty(target, "AUTORCC_OPTIONS"), optionsTarget);
  753. // Check if file name is unique
  754. for (cmQtAutoGenDigestQrc& qrcDigest : digest.Qrcs) {
  755. qrcDigest.Unique = true;
  756. for (const cmQtAutoGenDigestQrc& qrcDig2 : digest.Qrcs) {
  757. if ((&qrcDigest != &qrcDig2) &&
  758. (qrcDigest.QrcName == qrcDig2.QrcName)) {
  759. qrcDigest.Unique = false;
  760. break;
  761. }
  762. }
  763. }
  764. // Path checksum
  765. {
  766. const cmFilePathChecksum fpathCheckSum(makefile);
  767. for (cmQtAutoGenDigestQrc& qrcDigest : digest.Qrcs) {
  768. qrcDigest.PathChecksum = fpathCheckSum.getPart(qrcDigest.QrcFile);
  769. // RCC output file name
  770. std::string rccFile = autogenBuildDir + "/";
  771. rccFile += qrcDigest.PathChecksum;
  772. rccFile += "/qrc_";
  773. rccFile += qrcDigest.QrcName;
  774. rccFile += ".cpp";
  775. qrcDigest.RccFile = std::move(rccFile);
  776. }
  777. }
  778. // RCC options
  779. for (cmQtAutoGenDigestQrc& qrcDigest : digest.Qrcs) {
  780. // Target options
  781. std::vector<std::string> opts = optionsTarget;
  782. // Merge computed "-name XYZ" option
  783. {
  784. std::string name = qrcDigest.QrcName;
  785. // Replace '-' with '_'. The former is not valid for symbol names.
  786. std::replace(name.begin(), name.end(), '-', '_');
  787. if (!qrcDigest.Unique) {
  788. name += "_";
  789. name += qrcDigest.PathChecksum;
  790. }
  791. std::vector<std::string> nameOpts;
  792. nameOpts.emplace_back("-name");
  793. nameOpts.emplace_back(std::move(name));
  794. cmQtAutoGen::RccMergeOptions(opts, nameOpts, QtV5);
  795. }
  796. // Merge file option
  797. cmQtAutoGen::RccMergeOptions(opts, qrcDigest.Options, QtV5);
  798. qrcDigest.Options = std::move(opts);
  799. }
  800. for (cmQtAutoGenDigestQrc& qrcDigest : digest.Qrcs) {
  801. // Register file at target
  802. AddGeneratedSource(target, qrcDigest.RccFile, cmQtAutoGen::RCC);
  803. autogenProvides.push_back(qrcDigest.RccFile);
  804. // Dependencies
  805. if (qrcDigest.Generated) {
  806. // Add the GENERATED .qrc file to the dependencies
  807. autogenDependFiles.insert(qrcDigest.QrcFile);
  808. } else {
  809. // Add the resource files to the dependencies
  810. {
  811. std::string error;
  812. if (cmQtAutoGen::RccListInputs(digest.QtVersionMajor, rcc,
  813. qrcDigest.QrcFile,
  814. qrcDigest.Resources, &error)) {
  815. for (const std::string& fileName : qrcDigest.Resources) {
  816. autogenDependFiles.insert(fileName);
  817. }
  818. } else {
  819. cmSystemTools::Error(error.c_str());
  820. }
  821. }
  822. // Run cmake again when .qrc file changes
  823. makefile->AddCMakeDependFile(qrcDigest.QrcFile);
  824. }
  825. }
  826. }
  827. // Add user defined autogen target dependencies
  828. {
  829. const std::string deps = GetSafeProperty(target, "AUTOGEN_TARGET_DEPENDS");
  830. if (!deps.empty()) {
  831. std::vector<std::string> extraDeps;
  832. cmSystemTools::ExpandListArgument(deps, extraDeps);
  833. for (const std::string& depName : extraDeps) {
  834. // Allow target and file dependencies
  835. auto* depTarget = makefile->FindTargetToUse(depName);
  836. if (depTarget != nullptr) {
  837. autogenDependTargets.insert(depTarget->GetName());
  838. } else {
  839. autogenDependFiles.insert(depName);
  840. }
  841. }
  842. }
  843. }
  844. // Use PRE_BUILD on demand
  845. bool usePRE_BUILD = false;
  846. if (globalGen->GetName().find("Visual Studio") != std::string::npos) {
  847. // Under VS use a PRE_BUILD event instead of a separate target to
  848. // reduce the number of targets loaded into the IDE.
  849. // This also works around a VS 11 bug that may skip updating the target:
  850. // https://connect.microsoft.com/VisualStudio/feedback/details/769495
  851. usePRE_BUILD = true;
  852. }
  853. // Disable PRE_BUILD in some cases
  854. if (usePRE_BUILD) {
  855. // Cannot use PRE_BUILD with file depends
  856. if (!autogenDependFiles.empty()) {
  857. usePRE_BUILD = false;
  858. }
  859. }
  860. // Create the autogen target/command
  861. if (usePRE_BUILD) {
  862. // Add additional autogen target dependencies to origin target
  863. for (const std::string& depTarget : autogenDependTargets) {
  864. target->Target->AddUtility(depTarget, makefile);
  865. }
  866. // Add the pre-build command directly to bypass the OBJECT_LIBRARY
  867. // rejection in cmMakefile::AddCustomCommandToTarget because we know
  868. // PRE_BUILD will work for an OBJECT_LIBRARY in this specific case.
  869. //
  870. // PRE_BUILD does not support file dependencies!
  871. const std::vector<std::string> no_output;
  872. const std::vector<std::string> no_deps;
  873. cmCustomCommand cc(makefile, no_output, autogenProvides, no_deps,
  874. commandLines, autogenComment.c_str(),
  875. workingDirectory.c_str());
  876. cc.SetEscapeOldStyle(false);
  877. cc.SetEscapeAllowMakeVars(true);
  878. target->Target->AddPreBuildCommand(cc);
  879. } else {
  880. // Add utility target dependencies to the autogen target dependencies
  881. for (const std::string& depTarget : target->Target->GetUtilities()) {
  882. autogenDependTargets.insert(depTarget);
  883. }
  884. // Add link library target dependencies to the autogen target dependencies
  885. for (const auto& item : target->Target->GetOriginalLinkLibraries()) {
  886. if (makefile->FindTargetToUse(item.first) != nullptr) {
  887. autogenDependTargets.insert(item.first);
  888. }
  889. }
  890. // Convert file dependencies std::set to std::vector
  891. const std::vector<std::string> autogenDepends(autogenDependFiles.begin(),
  892. autogenDependFiles.end());
  893. // Create autogen target
  894. cmTarget* autogenTarget = makefile->AddUtilityCommand(
  895. autogenTargetName, true, workingDirectory.c_str(),
  896. /*byproducts=*/autogenProvides, autogenDepends, commandLines, false,
  897. autogenComment.c_str());
  898. // Create autogen generator target
  899. localGen->AddGeneratorTarget(
  900. new cmGeneratorTarget(autogenTarget, localGen));
  901. // Add additional autogen target dependencies to autogen target
  902. for (const std::string& depTarget : autogenDependTargets) {
  903. autogenTarget->AddUtility(depTarget, makefile);
  904. }
  905. // Set FOLDER property in autogen target
  906. {
  907. const char* autogenFolder =
  908. makefile->GetState()->GetGlobalProperty("AUTOMOC_TARGETS_FOLDER");
  909. if (autogenFolder == nullptr) {
  910. autogenFolder =
  911. makefile->GetState()->GetGlobalProperty("AUTOGEN_TARGETS_FOLDER");
  912. }
  913. // Inherit FOLDER property from target (#13688)
  914. if (autogenFolder == nullptr) {
  915. autogenFolder = SafeString(target->Target->GetProperty("FOLDER"));
  916. }
  917. if ((autogenFolder != nullptr) && (*autogenFolder != '\0')) {
  918. autogenTarget->SetProperty("FOLDER", autogenFolder);
  919. }
  920. }
  921. // Add autogen target to the origin target dependencies
  922. target->Target->AddUtility(autogenTargetName, makefile);
  923. }
  924. }
  925. void cmQtAutoGeneratorInitializer::SetupAutoGenerateTarget(
  926. const cmQtAutoGenDigest& digest)
  927. {
  928. cmGeneratorTarget const* target = digest.Target;
  929. cmMakefile* makefile = target->Target->GetMakefile();
  930. // forget the variables added here afterwards again:
  931. cmMakefile::ScopePushPop varScope(makefile);
  932. static_cast<void>(varScope);
  933. // Get configurations
  934. std::string config;
  935. const std::vector<std::string> configs(GetConfigurations(makefile, &config));
  936. // Configuration suffixes
  937. std::map<std::string, std::string> configSuffix;
  938. if (AutogenMultiConfig(target->GetGlobalGenerator())) {
  939. for (const std::string& cfg : configs) {
  940. configSuffix[cfg] = "_" + cfg;
  941. }
  942. }
  943. // Configurations settings buffers
  944. cmQtAutoGenSetup setup;
  945. // Basic setup
  946. AddDefinitionEscaped(makefile, "_build_dir",
  947. GetAutogenTargetBuildDir(target));
  948. AddDefinitionEscaped(makefile, "_qt_version_major", digest.QtVersionMajor);
  949. AddDefinitionEscaped(makefile, "_qt_version_minor", digest.QtVersionMinor);
  950. AddDefinitionEscaped(makefile, "_sources", digest.Sources);
  951. AddDefinitionEscaped(makefile, "_headers", digest.Headers);
  952. {
  953. if (digest.MocEnabled || digest.UicEnabled) {
  954. SetupAcquireSkipFiles(digest, setup);
  955. if (digest.MocEnabled) {
  956. SetupAutoTargetMoc(digest, config, configs, setup);
  957. }
  958. if (digest.UicEnabled) {
  959. SetupAutoTargetUic(digest, config, configs, setup);
  960. }
  961. }
  962. if (digest.RccEnabled) {
  963. SetupAutoTargetRcc(digest);
  964. }
  965. }
  966. // Generate info file
  967. std::string infoFile = GetAutogenTargetFilesDir(target);
  968. infoFile += "/AutogenInfo.cmake";
  969. {
  970. std::string inf = cmSystemTools::GetCMakeRoot();
  971. inf += "/Modules/AutogenInfo.cmake.in";
  972. makefile->ConfigureFile(inf.c_str(), infoFile.c_str(), false, true, false);
  973. }
  974. // Append custom definitions to info file on demand
  975. if (!configSuffix.empty() || !setup.ConfigMocDefines.empty() ||
  976. !setup.ConfigMocIncludes.empty() || !setup.ConfigUicOptions.empty()) {
  977. // Ensure we have write permission in case .in was read-only.
  978. mode_t perm = 0;
  979. #if defined(_WIN32) && !defined(__CYGWIN__)
  980. mode_t mode_write = S_IWRITE;
  981. #else
  982. mode_t mode_write = S_IWUSR;
  983. #endif
  984. cmSystemTools::GetPermissions(infoFile, perm);
  985. if (!(perm & mode_write)) {
  986. cmSystemTools::SetPermissions(infoFile, perm | mode_write);
  987. }
  988. // Open and write file
  989. cmsys::ofstream ofs(infoFile.c_str(), std::ios::app);
  990. if (ofs) {
  991. auto OfsWriteMap = [&ofs](
  992. const char* key, const std::map<std::string, std::string>& map) {
  993. for (const auto& item : map) {
  994. ofs << "set(" << key << "_" << item.first << " "
  995. << cmOutputConverter::EscapeForCMake(item.second) << ")\n";
  996. }
  997. };
  998. ofs << "# Configuration specific options\n";
  999. OfsWriteMap("AM_CONFIG_SUFFIX", configSuffix);
  1000. OfsWriteMap("AM_MOC_DEFINITIONS", setup.ConfigMocDefines);
  1001. OfsWriteMap("AM_MOC_INCLUDES", setup.ConfigMocIncludes);
  1002. OfsWriteMap("AM_UIC_TARGET_OPTIONS", setup.ConfigUicOptions);
  1003. } else {
  1004. // File open error
  1005. std::string error = "Internal CMake error when trying to open file: ";
  1006. error += cmQtAutoGen::Quoted(infoFile);
  1007. error += " for writing.";
  1008. cmSystemTools::Error(error.c_str());
  1009. }
  1010. }
  1011. }