cmQtAutoGenInitializer.cxx 52 KB

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