cmQtAutoGeneratorInitializer.cxx 37 KB

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