cmQtAutoGenInitializer.cxx 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128
  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 <cstddef>
  5. #include <deque>
  6. #include <initializer_list>
  7. #include <map>
  8. #include <set>
  9. #include <sstream> // for basic_ios, istringstream
  10. #include <string>
  11. #include <unordered_set>
  12. #include <utility>
  13. #include <vector>
  14. #include <cm/algorithm>
  15. #include <cm/iterator>
  16. #include <cm/memory>
  17. #include <cmext/algorithm>
  18. #include <cmext/string_view>
  19. #include <cm3p/json/value.h>
  20. #include <cm3p/json/writer.h>
  21. #include "cmsys/SystemInformation.hxx"
  22. #include "cmCustomCommand.h"
  23. #include "cmCustomCommandLines.h"
  24. #include "cmGeneratedFileStream.h"
  25. #include "cmGeneratorExpression.h"
  26. #include "cmGeneratorTarget.h"
  27. #include "cmGlobalGenerator.h"
  28. #include "cmLinkItem.h"
  29. #include "cmListFileCache.h"
  30. #include "cmLocalGenerator.h"
  31. #include "cmMakefile.h"
  32. #include "cmMessageType.h"
  33. #include "cmPolicies.h"
  34. #include "cmProperty.h"
  35. #include "cmQtAutoGen.h"
  36. #include "cmQtAutoGenGlobalInitializer.h"
  37. #include "cmSourceFile.h"
  38. #include "cmSourceFileLocationKind.h"
  39. #include "cmSourceGroup.h"
  40. #include "cmState.h"
  41. #include "cmStateTypes.h"
  42. #include "cmStringAlgorithms.h"
  43. #include "cmSystemTools.h"
  44. #include "cmTarget.h"
  45. #include "cmake.h"
  46. namespace {
  47. unsigned int GetParallelCPUCount()
  48. {
  49. static unsigned int count = 0;
  50. // Detect only on the first call
  51. if (count == 0) {
  52. cmsys::SystemInformation info;
  53. info.RunCPUCheck();
  54. count =
  55. cm::clamp(info.GetNumberOfPhysicalCPU(), 1u, cmQtAutoGen::ParallelMax);
  56. }
  57. return count;
  58. }
  59. std::string FileProjectRelativePath(cmMakefile* makefile,
  60. std::string const& fileName)
  61. {
  62. std::string res;
  63. {
  64. std::string pSource = cmSystemTools::RelativePath(
  65. makefile->GetCurrentSourceDirectory(), fileName);
  66. std::string pBinary = cmSystemTools::RelativePath(
  67. makefile->GetCurrentBinaryDirectory(), fileName);
  68. if (pSource.size() < pBinary.size()) {
  69. res = std::move(pSource);
  70. } else if (pBinary.size() < fileName.size()) {
  71. res = std::move(pBinary);
  72. } else {
  73. res = fileName;
  74. }
  75. }
  76. return res;
  77. }
  78. /**
  79. * Tests if targetDepend is a STATIC_LIBRARY and if any of its
  80. * recursive STATIC_LIBRARY dependencies depends on targetOrigin
  81. * (STATIC_LIBRARY cycle).
  82. */
  83. bool StaticLibraryCycle(cmGeneratorTarget const* targetOrigin,
  84. cmGeneratorTarget const* targetDepend,
  85. std::string const& config)
  86. {
  87. bool cycle = false;
  88. if ((targetOrigin->GetType() == cmStateEnums::STATIC_LIBRARY) &&
  89. (targetDepend->GetType() == cmStateEnums::STATIC_LIBRARY)) {
  90. std::set<cmGeneratorTarget const*> knownLibs;
  91. std::deque<cmGeneratorTarget const*> testLibs;
  92. // Insert initial static_library dependency
  93. knownLibs.insert(targetDepend);
  94. testLibs.push_back(targetDepend);
  95. while (!testLibs.empty()) {
  96. cmGeneratorTarget const* testTarget = testLibs.front();
  97. testLibs.pop_front();
  98. // Check if the test target is the origin target (cycle)
  99. if (testTarget == targetOrigin) {
  100. cycle = true;
  101. break;
  102. }
  103. // Collect all static_library dependencies from the test target
  104. cmLinkImplementationLibraries const* libs =
  105. testTarget->GetLinkImplementationLibraries(config);
  106. if (libs) {
  107. for (cmLinkItem const& item : libs->Libraries) {
  108. cmGeneratorTarget const* depTarget = item.Target;
  109. if (depTarget &&
  110. (depTarget->GetType() == cmStateEnums::STATIC_LIBRARY) &&
  111. knownLibs.insert(depTarget).second) {
  112. testLibs.push_back(depTarget);
  113. }
  114. }
  115. }
  116. }
  117. }
  118. return cycle;
  119. }
  120. /** Sanitizes file search paths. */
  121. class SearchPathSanitizer
  122. {
  123. public:
  124. SearchPathSanitizer(cmMakefile* makefile)
  125. : SourcePath_(makefile->GetCurrentSourceDirectory())
  126. {
  127. }
  128. std::vector<std::string> operator()(
  129. std::vector<std::string> const& paths) const;
  130. private:
  131. std::string SourcePath_;
  132. };
  133. std::vector<std::string> SearchPathSanitizer::operator()(
  134. std::vector<std::string> const& paths) const
  135. {
  136. std::vector<std::string> res;
  137. res.reserve(paths.size());
  138. for (std::string const& srcPath : paths) {
  139. // Collapse relative paths
  140. std::string path =
  141. cmSystemTools::CollapseFullPath(srcPath, this->SourcePath_);
  142. // Remove suffix slashes
  143. while (cmHasSuffix(path, '/')) {
  144. path.pop_back();
  145. }
  146. // Accept only non empty paths
  147. if (!path.empty()) {
  148. res.emplace_back(std::move(path));
  149. }
  150. }
  151. return res;
  152. }
  153. /** @brief Writes a CMake info file. */
  154. class InfoWriter
  155. {
  156. public:
  157. // -- Single value
  158. void Set(std::string const& key, std::string const& value)
  159. {
  160. this->Value_[key] = value;
  161. }
  162. void SetConfig(std::string const& key,
  163. cmQtAutoGenInitializer::ConfigString const& cfgStr);
  164. void SetBool(std::string const& key, bool value)
  165. {
  166. this->Value_[key] = value;
  167. }
  168. void SetUInt(std::string const& key, unsigned int value)
  169. {
  170. this->Value_[key] = value;
  171. }
  172. // -- Array utility
  173. template <typename CONT>
  174. static bool MakeArray(Json::Value& jval, CONT const& container);
  175. template <typename CONT>
  176. static void MakeStringArray(Json::Value& jval, CONT const& container);
  177. // -- Array value
  178. template <typename CONT>
  179. void SetArray(std::string const& key, CONT const& container);
  180. template <typename CONT>
  181. void SetConfigArray(
  182. std::string const& key,
  183. cmQtAutoGenInitializer::ConfigStrings<CONT> const& cfgStr);
  184. // -- Array of arrays
  185. template <typename CONT, typename FUNC>
  186. void SetArrayArray(std::string const& key, CONT const& container, FUNC func);
  187. // -- Save to json file
  188. bool Save(std::string const& filename);
  189. private:
  190. Json::Value Value_;
  191. };
  192. void InfoWriter::SetConfig(std::string const& key,
  193. cmQtAutoGenInitializer::ConfigString const& cfgStr)
  194. {
  195. this->Set(key, cfgStr.Default);
  196. for (auto const& item : cfgStr.Config) {
  197. this->Set(cmStrCat(key, '_', item.first), item.second);
  198. }
  199. }
  200. template <typename CONT>
  201. bool InfoWriter::MakeArray(Json::Value& jval, CONT const& container)
  202. {
  203. jval = Json::arrayValue;
  204. std::size_t const listSize = cm::size(container);
  205. if (listSize == 0) {
  206. return false;
  207. }
  208. jval.resize(static_cast<unsigned int>(listSize));
  209. return true;
  210. }
  211. template <typename CONT>
  212. void InfoWriter::MakeStringArray(Json::Value& jval, CONT const& container)
  213. {
  214. if (MakeArray(jval, container)) {
  215. Json::ArrayIndex ii = 0;
  216. for (std::string const& item : container) {
  217. jval[ii++] = item;
  218. }
  219. }
  220. }
  221. template <typename CONT>
  222. void InfoWriter::SetArray(std::string const& key, CONT const& container)
  223. {
  224. MakeStringArray(this->Value_[key], container);
  225. }
  226. template <typename CONT, typename FUNC>
  227. void InfoWriter::SetArrayArray(std::string const& key, CONT const& container,
  228. FUNC func)
  229. {
  230. Json::Value& jval = this->Value_[key];
  231. if (MakeArray(jval, container)) {
  232. Json::ArrayIndex ii = 0;
  233. for (auto const& citem : container) {
  234. Json::Value& aval = jval[ii++];
  235. aval = Json::arrayValue;
  236. func(aval, citem);
  237. }
  238. }
  239. }
  240. template <typename CONT>
  241. void InfoWriter::SetConfigArray(
  242. std::string const& key,
  243. cmQtAutoGenInitializer::ConfigStrings<CONT> const& cfgStr)
  244. {
  245. this->SetArray(key, cfgStr.Default);
  246. for (auto const& item : cfgStr.Config) {
  247. this->SetArray(cmStrCat(key, '_', item.first), item.second);
  248. }
  249. }
  250. bool InfoWriter::Save(std::string const& filename)
  251. {
  252. cmGeneratedFileStream fileStream;
  253. fileStream.SetCopyIfDifferent(true);
  254. fileStream.Open(filename, false, true);
  255. if (!fileStream) {
  256. return false;
  257. }
  258. Json::StyledStreamWriter jsonWriter;
  259. try {
  260. jsonWriter.write(fileStream, this->Value_);
  261. } catch (...) {
  262. return false;
  263. }
  264. return fileStream.Close();
  265. }
  266. void AddAutogenExecutableToDependencies(
  267. cmQtAutoGenInitializer::GenVarsT const& genVars,
  268. std::vector<std::string>& dependencies)
  269. {
  270. if (genVars.ExecutableTarget != nullptr) {
  271. dependencies.push_back(genVars.ExecutableTarget->Target->GetName());
  272. } else if (!genVars.Executable.empty()) {
  273. dependencies.push_back(genVars.Executable);
  274. }
  275. }
  276. } // End of unnamed namespace
  277. cmQtAutoGenInitializer::cmQtAutoGenInitializer(
  278. cmQtAutoGenGlobalInitializer* globalInitializer,
  279. cmGeneratorTarget* genTarget, IntegerVersion const& qtVersion,
  280. bool mocEnabled, bool uicEnabled, bool rccEnabled, bool globalAutogenTarget,
  281. bool globalAutoRccTarget)
  282. : GlobalInitializer(globalInitializer)
  283. , GenTarget(genTarget)
  284. , GlobalGen(genTarget->GetGlobalGenerator())
  285. , LocalGen(genTarget->GetLocalGenerator())
  286. , Makefile(genTarget->Makefile)
  287. , PathCheckSum(genTarget->Makefile)
  288. , QtVersion(qtVersion)
  289. {
  290. this->AutogenTarget.GlobalTarget = globalAutogenTarget;
  291. this->Moc.Enabled = mocEnabled;
  292. this->Uic.Enabled = uicEnabled;
  293. this->Rcc.Enabled = rccEnabled;
  294. this->Rcc.GlobalTarget = globalAutoRccTarget;
  295. }
  296. bool cmQtAutoGenInitializer::InitCustomTargets()
  297. {
  298. // Configurations
  299. this->MultiConfig = this->GlobalGen->IsMultiConfig();
  300. this->ConfigDefault = this->Makefile->GetDefaultConfiguration();
  301. this->ConfigsList =
  302. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  303. // Verbosity
  304. {
  305. std::string def =
  306. this->Makefile->GetSafeDefinition("CMAKE_AUTOGEN_VERBOSE");
  307. if (!def.empty()) {
  308. unsigned long iVerb = 0;
  309. if (cmStrToULong(def, &iVerb)) {
  310. // Numeric verbosity
  311. this->Verbosity = static_cast<unsigned int>(iVerb);
  312. } else {
  313. // Non numeric verbosity
  314. if (cmIsOn(def)) {
  315. this->Verbosity = 1;
  316. }
  317. }
  318. }
  319. }
  320. // Targets FOLDER
  321. {
  322. cmProp folder =
  323. this->Makefile->GetState()->GetGlobalProperty("AUTOMOC_TARGETS_FOLDER");
  324. if (!folder) {
  325. folder = this->Makefile->GetState()->GetGlobalProperty(
  326. "AUTOGEN_TARGETS_FOLDER");
  327. }
  328. // Inherit FOLDER property from target (#13688)
  329. if (!folder) {
  330. folder = this->GenTarget->GetProperty("FOLDER");
  331. }
  332. if (folder) {
  333. this->TargetsFolder = *folder;
  334. }
  335. }
  336. // Check status of policy CMP0071 regarding handling of GENERATED files
  337. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0071)) {
  338. case cmPolicies::WARN:
  339. // Ignore GENERATED files but warn
  340. this->CMP0071Warn = true;
  341. CM_FALLTHROUGH;
  342. case cmPolicies::OLD:
  343. // Ignore GENERATED files
  344. break;
  345. case cmPolicies::REQUIRED_IF_USED:
  346. case cmPolicies::REQUIRED_ALWAYS:
  347. case cmPolicies::NEW:
  348. // Process GENERATED files
  349. this->CMP0071Accept = true;
  350. break;
  351. }
  352. // Check status of policy CMP0100 regarding handling of .hh headers
  353. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0100)) {
  354. case cmPolicies::WARN:
  355. // Ignore but .hh files but warn
  356. this->CMP0100Warn = true;
  357. CM_FALLTHROUGH;
  358. case cmPolicies::OLD:
  359. // Ignore .hh files
  360. break;
  361. case cmPolicies::REQUIRED_IF_USED:
  362. case cmPolicies::REQUIRED_ALWAYS:
  363. case cmPolicies::NEW:
  364. // Process .hh file
  365. this->CMP0100Accept = true;
  366. break;
  367. }
  368. // Common directories
  369. {
  370. // Collapsed current binary directory
  371. std::string const cbd = cmSystemTools::CollapseFullPath(
  372. std::string(), this->Makefile->GetCurrentBinaryDirectory());
  373. // Info directory
  374. this->Dir.Info = cmStrCat(cbd, "/CMakeFiles/", this->GenTarget->GetName(),
  375. "_autogen.dir");
  376. cmSystemTools::ConvertToUnixSlashes(this->Dir.Info);
  377. // Build directory
  378. this->Dir.Build = this->GenTarget->GetSafeProperty("AUTOGEN_BUILD_DIR");
  379. if (this->Dir.Build.empty()) {
  380. this->Dir.Build =
  381. cmStrCat(cbd, '/', this->GenTarget->GetName(), "_autogen");
  382. }
  383. cmSystemTools::ConvertToUnixSlashes(this->Dir.Build);
  384. // Cleanup build directory
  385. this->AddCleanFile(this->Dir.Build);
  386. // Working directory
  387. this->Dir.Work = cbd;
  388. cmSystemTools::ConvertToUnixSlashes(this->Dir.Work);
  389. // Include directory
  390. this->ConfigFileNamesAndGenex(this->Dir.Include, this->Dir.IncludeGenExp,
  391. cmStrCat(this->Dir.Build, "/include"), "");
  392. }
  393. // Moc, Uic and _autogen target settings
  394. if (this->MocOrUicEnabled()) {
  395. // Init moc specific settings
  396. if (this->Moc.Enabled && !this->InitMoc()) {
  397. return false;
  398. }
  399. // Init uic specific settings
  400. if (this->Uic.Enabled && !this->InitUic()) {
  401. return false;
  402. }
  403. // Autogen target name
  404. this->AutogenTarget.Name =
  405. cmStrCat(this->GenTarget->GetName(), "_autogen");
  406. // Autogen target parallel processing
  407. {
  408. std::string const& prop =
  409. this->GenTarget->GetSafeProperty("AUTOGEN_PARALLEL");
  410. if (prop.empty() || (prop == "AUTO")) {
  411. // Autodetect number of CPUs
  412. this->AutogenTarget.Parallel = GetParallelCPUCount();
  413. } else {
  414. this->AutogenTarget.Parallel = 1;
  415. }
  416. }
  417. // Autogen target info and settings files
  418. {
  419. // Info file
  420. this->AutogenTarget.InfoFile =
  421. cmStrCat(this->Dir.Info, "/AutogenInfo.json");
  422. // Used settings file
  423. this->ConfigFileNames(this->AutogenTarget.SettingsFile,
  424. cmStrCat(this->Dir.Info, "/AutogenUsed"), ".txt");
  425. this->ConfigFileClean(this->AutogenTarget.SettingsFile);
  426. // Parse cache file
  427. this->ConfigFileNames(this->AutogenTarget.ParseCacheFile,
  428. cmStrCat(this->Dir.Info, "/ParseCache"), ".txt");
  429. this->ConfigFileClean(this->AutogenTarget.ParseCacheFile);
  430. }
  431. // Autogen target: Compute user defined dependencies
  432. {
  433. this->AutogenTarget.DependOrigin =
  434. this->GenTarget->GetPropertyAsBool("AUTOGEN_ORIGIN_DEPENDS");
  435. std::string const& deps =
  436. this->GenTarget->GetSafeProperty("AUTOGEN_TARGET_DEPENDS");
  437. if (!deps.empty()) {
  438. for (std::string const& depName : cmExpandedList(deps)) {
  439. // Allow target and file dependencies
  440. auto* depTarget = this->Makefile->FindTargetToUse(depName);
  441. if (depTarget) {
  442. this->AutogenTarget.DependTargets.insert(depTarget);
  443. } else {
  444. this->AutogenTarget.DependFiles.insert(depName);
  445. }
  446. }
  447. }
  448. }
  449. if (this->Moc.Enabled) {
  450. // Path prefix
  451. if (cmIsOn(this->GenTarget->GetProperty("AUTOMOC_PATH_PREFIX"))) {
  452. this->Moc.PathPrefix = true;
  453. }
  454. // CMAKE_AUTOMOC_RELAXED_MODE
  455. if (this->Makefile->IsOn("CMAKE_AUTOMOC_RELAXED_MODE")) {
  456. this->Moc.RelaxedMode = true;
  457. this->Makefile->IssueMessage(
  458. MessageType::AUTHOR_WARNING,
  459. cmStrCat("AUTOMOC: CMAKE_AUTOMOC_RELAXED_MODE is "
  460. "deprecated an will be removed in the future. Consider "
  461. "disabling it and converting the target ",
  462. this->GenTarget->GetName(), " to regular mode."));
  463. }
  464. // Options
  465. cmExpandList(this->GenTarget->GetSafeProperty("AUTOMOC_MOC_OPTIONS"),
  466. this->Moc.Options);
  467. // Filters
  468. cmExpandList(this->GenTarget->GetSafeProperty("AUTOMOC_MACRO_NAMES"),
  469. this->Moc.MacroNames);
  470. {
  471. auto filterList = cmExpandedList(
  472. this->GenTarget->GetSafeProperty("AUTOMOC_DEPEND_FILTERS"));
  473. if ((filterList.size() % 2) != 0) {
  474. cmSystemTools::Error(
  475. cmStrCat("AutoMoc: AUTOMOC_DEPEND_FILTERS predefs size ",
  476. filterList.size(), " is not a multiple of 2."));
  477. return false;
  478. }
  479. this->Moc.DependFilters.reserve(1 + (filterList.size() / 2));
  480. this->Moc.DependFilters.emplace_back(
  481. "Q_PLUGIN_METADATA",
  482. "[\n][ \t]*Q_PLUGIN_METADATA[ \t]*\\("
  483. "[^\\)]*FILE[ \t]*\"([^\"]+)\"");
  484. for (std::size_t ii = 0; ii != filterList.size(); ii += 2) {
  485. this->Moc.DependFilters.emplace_back(filterList[ii],
  486. filterList[ii + 1]);
  487. }
  488. }
  489. }
  490. }
  491. // Init rcc specific settings
  492. if (this->Rcc.Enabled && !this->InitRcc()) {
  493. return false;
  494. }
  495. // Add autogen include directory to the origin target INCLUDE_DIRECTORIES
  496. if (this->MocOrUicEnabled() || (this->Rcc.Enabled && this->MultiConfig)) {
  497. this->GenTarget->AddIncludeDirectory(this->Dir.IncludeGenExp, true);
  498. }
  499. // Scan files
  500. if (!this->InitScanFiles()) {
  501. return false;
  502. }
  503. // Create autogen target
  504. if (this->MocOrUicEnabled() && !this->InitAutogenTarget()) {
  505. return false;
  506. }
  507. // Create rcc targets
  508. if (this->Rcc.Enabled && !this->InitRccTargets()) {
  509. return false;
  510. }
  511. return true;
  512. }
  513. bool cmQtAutoGenInitializer::InitMoc()
  514. {
  515. // Mocs compilation file
  516. if (this->GlobalGen->IsXcode()) {
  517. // XXX(xcode-per-cfg-src): Drop this Xcode-specific code path
  518. // when the Xcode generator supports per-config sources.
  519. this->Moc.CompilationFile.Default =
  520. cmStrCat(this->Dir.Build, "/mocs_compilation.cpp");
  521. this->Moc.CompilationFileGenex = this->Moc.CompilationFile.Default;
  522. } else {
  523. this->ConfigFileNamesAndGenex(
  524. this->Moc.CompilationFile, this->Moc.CompilationFileGenex,
  525. cmStrCat(this->Dir.Build, "/mocs_compilation"_s), ".cpp"_s);
  526. }
  527. // Moc predefs
  528. if (this->GenTarget->GetPropertyAsBool("AUTOMOC_COMPILER_PREDEFINES") &&
  529. (this->QtVersion >= IntegerVersion(5, 8))) {
  530. // Command
  531. this->Makefile->GetDefExpandList("CMAKE_CXX_COMPILER_PREDEFINES_COMMAND",
  532. this->Moc.PredefsCmd);
  533. // Header
  534. if (!this->Moc.PredefsCmd.empty()) {
  535. this->ConfigFileNames(this->Moc.PredefsFile,
  536. cmStrCat(this->Dir.Build, "/moc_predefs"), ".h");
  537. }
  538. }
  539. // Moc includes
  540. {
  541. SearchPathSanitizer sanitizer(this->Makefile);
  542. auto getDirs =
  543. [this, &sanitizer](std::string const& cfg) -> std::vector<std::string> {
  544. // Get the include dirs for this target, without stripping the implicit
  545. // include dirs off, see issue #13667.
  546. std::vector<std::string> dirs;
  547. bool const appendImplicit = (this->QtVersion.Major >= 5);
  548. this->LocalGen->GetIncludeDirectoriesImplicit(
  549. dirs, this->GenTarget, "CXX", cfg, false, appendImplicit);
  550. return sanitizer(dirs);
  551. };
  552. // Default configuration include directories
  553. this->Moc.Includes.Default = getDirs(this->ConfigDefault);
  554. // Other configuration settings
  555. if (this->MultiConfig) {
  556. for (std::string const& cfg : this->ConfigsList) {
  557. std::vector<std::string> dirs = getDirs(cfg);
  558. if (dirs == this->Moc.Includes.Default) {
  559. continue;
  560. }
  561. this->Moc.Includes.Config[cfg] = std::move(dirs);
  562. }
  563. }
  564. }
  565. // Moc compile definitions
  566. {
  567. auto getDefs = [this](std::string const& cfg) -> std::set<std::string> {
  568. std::set<std::string> defines;
  569. this->LocalGen->GetTargetDefines(this->GenTarget, cfg, "CXX", defines);
  570. #ifdef _WIN32
  571. if (this->Moc.PredefsCmd.empty()) {
  572. // Add WIN32 definition if we don't have a moc_predefs.h
  573. defines.insert("WIN32");
  574. }
  575. #endif
  576. return defines;
  577. };
  578. // Default configuration defines
  579. this->Moc.Defines.Default = getDefs(this->ConfigDefault);
  580. // Other configuration defines
  581. if (this->MultiConfig) {
  582. for (std::string const& cfg : this->ConfigsList) {
  583. std::set<std::string> defines = getDefs(cfg);
  584. if (defines == this->Moc.Defines.Default) {
  585. continue;
  586. }
  587. this->Moc.Defines.Config[cfg] = std::move(defines);
  588. }
  589. }
  590. }
  591. // Moc executable
  592. {
  593. if (!this->GetQtExecutable(this->Moc, "moc", false)) {
  594. return false;
  595. }
  596. // Let the _autogen target depend on the moc executable
  597. if (this->Moc.ExecutableTarget) {
  598. this->AutogenTarget.DependTargets.insert(
  599. this->Moc.ExecutableTarget->Target);
  600. }
  601. }
  602. return true;
  603. }
  604. bool cmQtAutoGenInitializer::InitUic()
  605. {
  606. // Uic search paths
  607. {
  608. std::string const& usp =
  609. this->GenTarget->GetSafeProperty("AUTOUIC_SEARCH_PATHS");
  610. if (!usp.empty()) {
  611. this->Uic.SearchPaths =
  612. SearchPathSanitizer(this->Makefile)(cmExpandedList(usp));
  613. }
  614. }
  615. // Uic target options
  616. {
  617. auto getOpts = [this](std::string const& cfg) -> std::vector<std::string> {
  618. std::vector<std::string> opts;
  619. this->GenTarget->GetAutoUicOptions(opts, cfg);
  620. return opts;
  621. };
  622. // Default options
  623. this->Uic.Options.Default = getOpts(this->ConfigDefault);
  624. // Configuration specific options
  625. if (this->MultiConfig) {
  626. for (std::string const& cfg : this->ConfigsList) {
  627. std::vector<std::string> options = getOpts(cfg);
  628. if (options == this->Uic.Options.Default) {
  629. continue;
  630. }
  631. this->Uic.Options.Config[cfg] = std::move(options);
  632. }
  633. }
  634. }
  635. // Uic executable
  636. {
  637. if (!this->GetQtExecutable(this->Uic, "uic", true)) {
  638. return false;
  639. }
  640. // Let the _autogen target depend on the uic executable
  641. if (this->Uic.ExecutableTarget) {
  642. this->AutogenTarget.DependTargets.insert(
  643. this->Uic.ExecutableTarget->Target);
  644. }
  645. }
  646. return true;
  647. }
  648. bool cmQtAutoGenInitializer::InitRcc()
  649. {
  650. // Rcc executable
  651. {
  652. if (!this->GetQtExecutable(this->Rcc, "rcc", false)) {
  653. return false;
  654. }
  655. // Evaluate test output on demand
  656. CompilerFeatures& features = *this->Rcc.ExecutableFeatures;
  657. if (!features.Evaluated) {
  658. // Look for list options
  659. if (this->QtVersion.Major == 5 || this->QtVersion.Major == 6) {
  660. if (features.HelpOutput.find("--list") != std::string::npos) {
  661. features.ListOptions.emplace_back("--list");
  662. } else if (features.HelpOutput.find("-list") != std::string::npos) {
  663. features.ListOptions.emplace_back("-list");
  664. }
  665. }
  666. // Evaluation finished
  667. features.Evaluated = true;
  668. }
  669. }
  670. return true;
  671. }
  672. bool cmQtAutoGenInitializer::InitScanFiles()
  673. {
  674. cmake const* cm = this->Makefile->GetCMakeInstance();
  675. auto const& kw = this->GlobalInitializer->kw();
  676. auto makeMUFile = [this, &kw](cmSourceFile* sf, std::string const& fullPath,
  677. std::vector<size_t> const& configs,
  678. bool muIt) -> MUFileHandle {
  679. MUFileHandle muf = cm::make_unique<MUFile>();
  680. muf->FullPath = fullPath;
  681. muf->SF = sf;
  682. if (!configs.empty() && configs.size() != this->ConfigsList.size()) {
  683. muf->Configs = configs;
  684. }
  685. muf->Generated = sf->GetIsGenerated();
  686. bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
  687. muf->SkipMoc = this->Moc.Enabled &&
  688. (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOMOC));
  689. muf->SkipUic = this->Uic.Enabled &&
  690. (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
  691. if (muIt) {
  692. muf->MocIt = this->Moc.Enabled && !muf->SkipMoc;
  693. muf->UicIt = this->Uic.Enabled && !muf->SkipUic;
  694. }
  695. return muf;
  696. };
  697. auto addMUHeader = [this](MUFileHandle&& muf, cm::string_view extension) {
  698. cmSourceFile* sf = muf->SF;
  699. const bool muIt = (muf->MocIt || muf->UicIt);
  700. if (this->CMP0100Accept || (extension != "hh")) {
  701. // Accept
  702. if (muIt && muf->Generated) {
  703. this->AutogenTarget.FilesGenerated.emplace_back(muf.get());
  704. }
  705. this->AutogenTarget.Headers.emplace(sf, std::move(muf));
  706. } else if (muIt && this->CMP0100Warn) {
  707. // Store file for warning message
  708. this->AutogenTarget.CMP0100HeadersWarn.push_back(sf);
  709. }
  710. };
  711. auto addMUSource = [this](MUFileHandle&& muf) {
  712. if ((muf->MocIt || muf->UicIt) && muf->Generated) {
  713. this->AutogenTarget.FilesGenerated.emplace_back(muf.get());
  714. }
  715. this->AutogenTarget.Sources.emplace(muf->SF, std::move(muf));
  716. };
  717. // Scan through target files
  718. {
  719. // Scan through target files
  720. for (cmGeneratorTarget::AllConfigSource const& acs :
  721. this->GenTarget->GetAllConfigSources()) {
  722. std::string const& fullPath = acs.Source->GetFullPath();
  723. std::string const& extLower =
  724. cmSystemTools::LowerCase(acs.Source->GetExtension());
  725. // Register files that will be scanned by moc or uic
  726. if (this->MocOrUicEnabled()) {
  727. if (cm->IsAHeaderExtension(extLower)) {
  728. addMUHeader(makeMUFile(acs.Source, fullPath, acs.Configs, true),
  729. extLower);
  730. } else if (cm->IsACLikeSourceExtension(extLower)) {
  731. addMUSource(makeMUFile(acs.Source, fullPath, acs.Configs, true));
  732. }
  733. }
  734. // Register rcc enabled files
  735. if (this->Rcc.Enabled) {
  736. if ((extLower == kw.qrc) &&
  737. !acs.Source->GetPropertyAsBool(kw.SKIP_AUTOGEN) &&
  738. !acs.Source->GetPropertyAsBool(kw.SKIP_AUTORCC)) {
  739. // Register qrc file
  740. Qrc qrc;
  741. qrc.QrcFile = fullPath;
  742. qrc.QrcName =
  743. cmSystemTools::GetFilenameWithoutLastExtension(qrc.QrcFile);
  744. qrc.Generated = acs.Source->GetIsGenerated();
  745. // RCC options
  746. {
  747. std::string const& opts =
  748. acs.Source->GetSafeProperty(kw.AUTORCC_OPTIONS);
  749. if (!opts.empty()) {
  750. cmExpandList(opts, qrc.Options);
  751. }
  752. }
  753. this->Rcc.Qrcs.push_back(std::move(qrc));
  754. }
  755. }
  756. }
  757. }
  758. // cmGeneratorTarget::GetAllConfigSources computes the target's
  759. // sources meta data cache. Clear it so that OBJECT library targets that
  760. // are AUTOGEN initialized after this target get their added
  761. // mocs_compilation.cpp source acknowledged by this target.
  762. this->GenTarget->ClearSourcesCache();
  763. // For source files find additional headers and private headers
  764. if (this->MocOrUicEnabled()) {
  765. // Header search suffixes and extensions
  766. static std::initializer_list<cm::string_view> const suffixes{ "", "_p" };
  767. auto const& exts = cm->GetHeaderExtensions();
  768. // Scan through sources
  769. for (auto const& pair : this->AutogenTarget.Sources) {
  770. MUFile const& muf = *pair.second;
  771. if (muf.MocIt || muf.UicIt) {
  772. // Search for the default header file and a private header
  773. std::string const& srcFullPath = muf.SF->ResolveFullPath();
  774. std::string basePath = cmStrCat(
  775. cmQtAutoGen::SubDirPrefix(srcFullPath),
  776. cmSystemTools::GetFilenameWithoutLastExtension(srcFullPath));
  777. for (auto const& suffix : suffixes) {
  778. std::string const suffixedPath = cmStrCat(basePath, suffix);
  779. for (auto const& ext : exts) {
  780. std::string fullPath = cmStrCat(suffixedPath, '.', ext);
  781. auto constexpr locationKind = cmSourceFileLocationKind::Known;
  782. cmSourceFile* sf =
  783. this->Makefile->GetSource(fullPath, locationKind);
  784. if (sf) {
  785. // Check if we know about this header already
  786. if (cm::contains(this->AutogenTarget.Headers, sf)) {
  787. continue;
  788. }
  789. // We only accept not-GENERATED files that do exist.
  790. if (!sf->GetIsGenerated() &&
  791. !cmSystemTools::FileExists(fullPath)) {
  792. continue;
  793. }
  794. } else if (cmSystemTools::FileExists(fullPath)) {
  795. // Create a new source file for the existing file
  796. sf = this->Makefile->CreateSource(fullPath, false, locationKind);
  797. }
  798. if (sf) {
  799. auto eMuf = makeMUFile(sf, fullPath, muf.Configs, true);
  800. // Only process moc/uic when the parent is processed as well
  801. if (!muf.MocIt) {
  802. eMuf->MocIt = false;
  803. }
  804. if (!muf.UicIt) {
  805. eMuf->UicIt = false;
  806. }
  807. addMUHeader(std::move(eMuf), ext);
  808. }
  809. }
  810. }
  811. }
  812. }
  813. }
  814. // Scan through all source files in the makefile to extract moc and uic
  815. // parameters. Historically we support non target source file parameters.
  816. // The reason is that their file names might be discovered from source files
  817. // at generation time.
  818. if (this->MocOrUicEnabled()) {
  819. std::set<std::string> uicIncludes;
  820. auto collectUicIncludes = [&](std::unique_ptr<cmSourceFile> const& sf) {
  821. std::string content;
  822. FileRead(content, sf->GetFullPath());
  823. this->AutoUicHelpers.CollectUicIncludes(uicIncludes, content);
  824. };
  825. for (const auto& sf : this->Makefile->GetSourceFiles()) {
  826. // sf->GetExtension() is only valid after sf->ResolveFullPath() ...
  827. // Since we're iterating over source files that might be not in the
  828. // target we need to check for path errors (not existing files).
  829. std::string pathError;
  830. std::string const& fullPath = sf->ResolveFullPath(&pathError);
  831. if (!pathError.empty() || fullPath.empty()) {
  832. continue;
  833. }
  834. std::string const& extLower =
  835. cmSystemTools::LowerCase(sf->GetExtension());
  836. bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
  837. bool const skipUic =
  838. (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC) ||
  839. !this->Uic.Enabled);
  840. if (cm->IsAHeaderExtension(extLower)) {
  841. if (!cm::contains(this->AutogenTarget.Headers, sf.get())) {
  842. auto muf = makeMUFile(sf.get(), fullPath, {}, false);
  843. if (muf->SkipMoc || muf->SkipUic) {
  844. addMUHeader(std::move(muf), extLower);
  845. }
  846. }
  847. if (!skipUic && !sf->GetIsGenerated()) {
  848. collectUicIncludes(sf);
  849. }
  850. } else if (cm->IsACLikeSourceExtension(extLower)) {
  851. if (!cm::contains(this->AutogenTarget.Sources, sf.get())) {
  852. auto muf = makeMUFile(sf.get(), fullPath, {}, false);
  853. if (muf->SkipMoc || muf->SkipUic) {
  854. addMUSource(std::move(muf));
  855. }
  856. }
  857. if (!skipUic && !sf->GetIsGenerated()) {
  858. collectUicIncludes(sf);
  859. }
  860. } else if (this->Uic.Enabled && (extLower == kw.ui)) {
  861. // .ui file
  862. if (!skipUic) {
  863. // Check if the .ui file has uic options
  864. std::string const uicOpts = sf->GetSafeProperty(kw.AUTOUIC_OPTIONS);
  865. if (uicOpts.empty()) {
  866. this->Uic.UiFilesNoOptions.emplace_back(fullPath);
  867. } else {
  868. this->Uic.UiFilesWithOptions.emplace_back(fullPath,
  869. cmExpandedList(uicOpts));
  870. }
  871. } else {
  872. // Register skipped .ui file
  873. this->Uic.SkipUi.insert(fullPath);
  874. }
  875. }
  876. }
  877. for (const auto& include : uicIncludes) {
  878. ConfigString uiHeader;
  879. std::string uiHeaderGenex;
  880. this->ConfigFileNamesAndGenex(uiHeader, uiHeaderGenex,
  881. cmStrCat(this->Dir.Build, "/include"_s),
  882. cmStrCat("/"_s, include));
  883. this->Uic.UiHeaders.emplace_back(
  884. std::make_pair(uiHeader, uiHeaderGenex));
  885. }
  886. }
  887. // Process GENERATED sources and headers
  888. if (this->MocOrUicEnabled() && !this->AutogenTarget.FilesGenerated.empty()) {
  889. if (this->CMP0071Accept) {
  890. // Let the autogen target depend on the GENERATED files
  891. for (MUFile* muf : this->AutogenTarget.FilesGenerated) {
  892. this->AutogenTarget.DependFiles.insert(muf->FullPath);
  893. }
  894. } else if (this->CMP0071Warn) {
  895. cm::string_view property;
  896. if (this->Moc.Enabled && this->Uic.Enabled) {
  897. property = "SKIP_AUTOGEN";
  898. } else if (this->Moc.Enabled) {
  899. property = "SKIP_AUTOMOC";
  900. } else if (this->Uic.Enabled) {
  901. property = "SKIP_AUTOUIC";
  902. }
  903. std::string files;
  904. for (MUFile* muf : this->AutogenTarget.FilesGenerated) {
  905. files += cmStrCat(" ", Quoted(muf->FullPath), '\n');
  906. }
  907. this->Makefile->IssueMessage(
  908. MessageType::AUTHOR_WARNING,
  909. cmStrCat(
  910. cmPolicies::GetPolicyWarning(cmPolicies::CMP0071), '\n',
  911. "For compatibility, CMake is excluding the GENERATED source "
  912. "file(s):\n",
  913. files, "from processing by ",
  914. cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
  915. ". If any of the files should be processed, set CMP0071 to NEW. "
  916. "If any of the files should not be processed, "
  917. "explicitly exclude them by setting the source file property ",
  918. property, ":\n set_property(SOURCE file.h PROPERTY ", property,
  919. " ON)\n"));
  920. }
  921. }
  922. // Generate CMP0100 warning
  923. if (this->MocOrUicEnabled() &&
  924. !this->AutogenTarget.CMP0100HeadersWarn.empty()) {
  925. cm::string_view property;
  926. if (this->Moc.Enabled && this->Uic.Enabled) {
  927. property = "SKIP_AUTOGEN";
  928. } else if (this->Moc.Enabled) {
  929. property = "SKIP_AUTOMOC";
  930. } else if (this->Uic.Enabled) {
  931. property = "SKIP_AUTOUIC";
  932. }
  933. std::string files;
  934. for (cmSourceFile* sf : this->AutogenTarget.CMP0100HeadersWarn) {
  935. files += cmStrCat(" ", Quoted(sf->GetFullPath()), '\n');
  936. }
  937. this->Makefile->IssueMessage(
  938. MessageType::AUTHOR_WARNING,
  939. cmStrCat(
  940. cmPolicies::GetPolicyWarning(cmPolicies::CMP0100), '\n',
  941. "For compatibility, CMake is excluding the header file(s):\n", files,
  942. "from processing by ",
  943. cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
  944. ". If any of the files should be processed, set CMP0100 to NEW. "
  945. "If any of the files should not be processed, "
  946. "explicitly exclude them by setting the source file property ",
  947. property, ":\n set_property(SOURCE file.hh PROPERTY ", property,
  948. " ON)\n"));
  949. }
  950. // Process qrc files
  951. if (!this->Rcc.Qrcs.empty()) {
  952. const bool modernQt = (this->QtVersion.Major >= 5);
  953. // Target rcc options
  954. std::vector<std::string> optionsTarget =
  955. cmExpandedList(this->GenTarget->GetSafeProperty(kw.AUTORCC_OPTIONS));
  956. // Check if file name is unique
  957. for (Qrc& qrc : this->Rcc.Qrcs) {
  958. qrc.Unique = true;
  959. for (Qrc const& qrc2 : this->Rcc.Qrcs) {
  960. if ((&qrc != &qrc2) && (qrc.QrcName == qrc2.QrcName)) {
  961. qrc.Unique = false;
  962. break;
  963. }
  964. }
  965. }
  966. // Path checksum and file names
  967. for (Qrc& qrc : this->Rcc.Qrcs) {
  968. // Path checksum
  969. qrc.QrcPathChecksum = this->PathCheckSum.getPart(qrc.QrcFile);
  970. // Output file name
  971. qrc.OutputFile = cmStrCat(this->Dir.Build, '/', qrc.QrcPathChecksum,
  972. "/qrc_", qrc.QrcName, ".cpp");
  973. std::string const base = cmStrCat(this->Dir.Info, "/AutoRcc_",
  974. qrc.QrcName, '_', qrc.QrcPathChecksum);
  975. qrc.LockFile = cmStrCat(base, "_Lock.lock");
  976. qrc.InfoFile = cmStrCat(base, "_Info.json");
  977. this->ConfigFileNames(qrc.SettingsFile, cmStrCat(base, "_Used"), ".txt");
  978. }
  979. // rcc options
  980. for (Qrc& qrc : this->Rcc.Qrcs) {
  981. // Target options
  982. std::vector<std::string> opts = optionsTarget;
  983. // Merge computed "-name XYZ" option
  984. {
  985. std::string name = qrc.QrcName;
  986. // Replace '-' with '_'. The former is not valid for symbol names.
  987. std::replace(name.begin(), name.end(), '-', '_');
  988. if (!qrc.Unique) {
  989. name += cmStrCat('_', qrc.QrcPathChecksum);
  990. }
  991. std::vector<std::string> nameOpts;
  992. nameOpts.emplace_back("-name");
  993. nameOpts.emplace_back(std::move(name));
  994. RccMergeOptions(opts, nameOpts, modernQt);
  995. }
  996. // Merge file option
  997. RccMergeOptions(opts, qrc.Options, modernQt);
  998. qrc.Options = std::move(opts);
  999. }
  1000. // rcc resources
  1001. for (Qrc& qrc : this->Rcc.Qrcs) {
  1002. if (!qrc.Generated) {
  1003. std::string error;
  1004. RccLister const lister(this->Rcc.Executable,
  1005. this->Rcc.ExecutableFeatures->ListOptions);
  1006. if (!lister.list(qrc.QrcFile, qrc.Resources, error)) {
  1007. cmSystemTools::Error(error);
  1008. return false;
  1009. }
  1010. }
  1011. }
  1012. }
  1013. return true;
  1014. }
  1015. bool cmQtAutoGenInitializer::InitAutogenTarget()
  1016. {
  1017. // Register info file as generated by CMake
  1018. this->Makefile->AddCMakeOutputFile(this->AutogenTarget.InfoFile);
  1019. // Determine whether to use a depfile for the AUTOGEN target.
  1020. const bool useNinjaDepfile = this->QtVersion >= IntegerVersion(5, 15) &&
  1021. this->GlobalGen->GetName().find("Ninja") != std::string::npos;
  1022. // Files provided by the autogen target
  1023. std::vector<std::string> autogenByproducts;
  1024. std::vector<std::string> timestampByproducts;
  1025. if (this->Moc.Enabled) {
  1026. this->AddGeneratedSource(this->Moc.CompilationFile, this->Moc, true);
  1027. if (useNinjaDepfile) {
  1028. if (this->MultiConfig) {
  1029. // Make all mocs_compilation_<CONFIG>.cpp files byproducts of the
  1030. // ${target}_autogen/timestamp custom command.
  1031. // We cannot just use Moc.CompilationFileGenex here, because that
  1032. // custom command runs cmake_autogen for each configuration.
  1033. for (const auto& p : this->Moc.CompilationFile.Config) {
  1034. timestampByproducts.push_back(p.second);
  1035. }
  1036. } else {
  1037. timestampByproducts.push_back(this->Moc.CompilationFileGenex);
  1038. }
  1039. } else {
  1040. autogenByproducts.push_back(this->Moc.CompilationFileGenex);
  1041. }
  1042. }
  1043. if (this->Uic.Enabled) {
  1044. for (const auto& file : this->Uic.UiHeaders) {
  1045. this->AddGeneratedSource(file.first, this->Uic);
  1046. autogenByproducts.push_back(file.second);
  1047. }
  1048. }
  1049. // Compose target comment
  1050. std::string autogenComment;
  1051. {
  1052. std::string tools;
  1053. if (this->Moc.Enabled) {
  1054. tools += "MOC";
  1055. }
  1056. if (this->Uic.Enabled) {
  1057. if (!tools.empty()) {
  1058. tools += " and ";
  1059. }
  1060. tools += "UIC";
  1061. }
  1062. autogenComment = cmStrCat("Automatic ", tools, " for target ",
  1063. this->GenTarget->GetName());
  1064. }
  1065. // Compose command lines
  1066. // FIXME: Take advantage of our per-config mocs_compilation_$<CONFIG>.cpp
  1067. // instead of fiddling with the include directories
  1068. std::vector<std::string> configs;
  1069. this->GlobalGen->GetQtAutoGenConfigs(configs);
  1070. bool stdPipesUTF8 = true;
  1071. cmCustomCommandLines commandLines;
  1072. for (auto const& config : configs) {
  1073. commandLines.push_back(cmMakeCommandLine(
  1074. { cmSystemTools::GetCMakeCommand(), "-E", "cmake_autogen",
  1075. this->AutogenTarget.InfoFile, config }));
  1076. }
  1077. // Use PRE_BUILD on demand
  1078. bool usePRE_BUILD = false;
  1079. if (this->GlobalGen->GetName().find("Visual Studio") != std::string::npos) {
  1080. // Under VS use a PRE_BUILD event instead of a separate target to
  1081. // reduce the number of targets loaded into the IDE.
  1082. // This also works around a VS 11 bug that may skip updating the target:
  1083. // https://connect.microsoft.com/VisualStudio/feedback/details/769495
  1084. usePRE_BUILD = true;
  1085. }
  1086. // Disable PRE_BUILD in some cases
  1087. if (usePRE_BUILD) {
  1088. // Cannot use PRE_BUILD with file depends
  1089. if (!this->AutogenTarget.DependFiles.empty()) {
  1090. usePRE_BUILD = false;
  1091. }
  1092. // Cannot use PRE_BUILD when a global autogen target is in place
  1093. if (this->AutogenTarget.GlobalTarget) {
  1094. usePRE_BUILD = false;
  1095. }
  1096. }
  1097. // Create the autogen target/command
  1098. if (usePRE_BUILD) {
  1099. // Add additional autogen target dependencies to origin target
  1100. for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
  1101. this->GenTarget->Target->AddUtility(depTarget->GetName(), false,
  1102. this->Makefile);
  1103. }
  1104. if (!this->Uic.UiFilesNoOptions.empty() ||
  1105. !this->Uic.UiFilesWithOptions.empty()) {
  1106. // Add a generated timestamp file
  1107. ConfigString timestampFile;
  1108. std::string timestampFileGenex;
  1109. ConfigFileNamesAndGenex(timestampFile, timestampFileGenex,
  1110. cmStrCat(this->Dir.Build, "/autouic"_s),
  1111. ".stamp"_s);
  1112. this->AddGeneratedSource(timestampFile, this->Uic);
  1113. // Add a step in the pre-build command to touch the timestamp file
  1114. commandLines.push_back(
  1115. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E", "touch",
  1116. timestampFileGenex }));
  1117. // UIC needs to be re-run if any of the known UI files change or the
  1118. // executable itself has been updated
  1119. auto uicDependencies = this->Uic.UiFilesNoOptions;
  1120. for (auto const& uiFile : this->Uic.UiFilesWithOptions) {
  1121. uicDependencies.push_back(uiFile.first);
  1122. }
  1123. AddAutogenExecutableToDependencies(this->Uic, uicDependencies);
  1124. // Add a rule file to cause the target to build if a dependency has
  1125. // changed, which will trigger the pre-build command to run autogen
  1126. std::string no_main_dependency;
  1127. cmCustomCommandLines no_command_lines;
  1128. this->LocalGen->AddCustomCommandToOutput(
  1129. timestampFileGenex, uicDependencies, no_main_dependency,
  1130. no_command_lines, /*comment=*/"", this->Dir.Work.c_str(),
  1131. /*cmp0116=*/cmPolicies::NEW, /*replace=*/false,
  1132. /*escapeOldStyle=*/false, /*uses_terminal=*/false,
  1133. /*command_expand_lists=*/false, /*depfile=*/"", /*job_pool=*/"",
  1134. stdPipesUTF8);
  1135. }
  1136. // Add the pre-build command directly to bypass the OBJECT_LIBRARY
  1137. // rejection in cmMakefile::AddCustomCommandToTarget because we know
  1138. // PRE_BUILD will work for an OBJECT_LIBRARY in this specific case.
  1139. //
  1140. // PRE_BUILD does not support file dependencies!
  1141. const std::vector<std::string> no_output;
  1142. const std::vector<std::string> no_deps;
  1143. cmCustomCommand cc(no_output, autogenByproducts, no_deps, commandLines,
  1144. this->Makefile->GetBacktrace(), autogenComment.c_str(),
  1145. this->Dir.Work.c_str(), stdPipesUTF8);
  1146. cc.SetEscapeOldStyle(false);
  1147. cc.SetEscapeAllowMakeVars(true);
  1148. this->GenTarget->Target->AddPreBuildCommand(std::move(cc));
  1149. } else {
  1150. // Add link library target dependencies to the autogen target
  1151. // dependencies
  1152. if (this->AutogenTarget.DependOrigin) {
  1153. // add_dependencies/addUtility do not support generator expressions.
  1154. // We depend only on the libraries found in all configs therefore.
  1155. std::map<cmGeneratorTarget const*, std::size_t> commonTargets;
  1156. for (std::string const& config : this->ConfigsList) {
  1157. cmLinkImplementationLibraries const* libs =
  1158. this->GenTarget->GetLinkImplementationLibraries(config);
  1159. if (libs) {
  1160. for (cmLinkItem const& item : libs->Libraries) {
  1161. cmGeneratorTarget const* libTarget = item.Target;
  1162. if (libTarget &&
  1163. !StaticLibraryCycle(this->GenTarget, libTarget, config)) {
  1164. // Increment target config count
  1165. commonTargets[libTarget]++;
  1166. }
  1167. }
  1168. }
  1169. }
  1170. for (auto const& item : commonTargets) {
  1171. if (item.second == this->ConfigsList.size()) {
  1172. this->AutogenTarget.DependTargets.insert(item.first->Target);
  1173. }
  1174. }
  1175. }
  1176. std::vector<std::string> dependencies(
  1177. this->AutogenTarget.DependFiles.begin(),
  1178. this->AutogenTarget.DependFiles.end());
  1179. if (useNinjaDepfile) {
  1180. // Create a custom command that generates a timestamp file and
  1181. // has a depfile assigned. The depfile is created by JobDepFilesMergeT.
  1182. //
  1183. // Also create an additional '_autogen_timestamp_deps' that the custom
  1184. // command will depend on. It will have no sources or commands to
  1185. // execute, but it will have dependencies that would originally be
  1186. // assigned to the pre-Qt 5.15 'autogen' target. These dependencies will
  1187. // serve as a list of order-only dependencies for the custom command,
  1188. // without forcing the custom command to re-execute.
  1189. //
  1190. // The dependency tree would then look like
  1191. // '_autogen_timestamp_deps (order-only)' <- '/timestamp' file <-
  1192. // '_autogen' target.
  1193. const auto timestampTargetName =
  1194. cmStrCat(this->GenTarget->GetName(), "_autogen_timestamp_deps");
  1195. std::vector<std::string> timestampTargetProvides;
  1196. cmCustomCommandLines timestampTargetCommandLines;
  1197. // Add additional autogen target dependencies to
  1198. // '_autogen_timestamp_deps'.
  1199. for (const cmTarget* t : this->AutogenTarget.DependTargets) {
  1200. dependencies.push_back(t->GetName());
  1201. }
  1202. cmTarget* timestampTarget = this->LocalGen->AddUtilityCommand(
  1203. timestampTargetName, true, this->Dir.Work.c_str(),
  1204. /*byproducts=*/timestampTargetProvides,
  1205. /*depends=*/dependencies, timestampTargetCommandLines, cmPolicies::NEW,
  1206. false, nullptr);
  1207. this->LocalGen->AddGeneratorTarget(
  1208. cm::make_unique<cmGeneratorTarget>(timestampTarget, this->LocalGen));
  1209. // Set FOLDER property on the timestamp target, so it appears in the
  1210. // appropriate folder in an IDE or in the file api.
  1211. if (!this->TargetsFolder.empty()) {
  1212. timestampTarget->SetProperty("FOLDER", this->TargetsFolder);
  1213. }
  1214. // Make '/timestamp' file depend on '_autogen_timestamp_deps' and on the
  1215. // moc and uic executables (whichever are enabled).
  1216. dependencies.clear();
  1217. dependencies.push_back(timestampTargetName);
  1218. AddAutogenExecutableToDependencies(this->Moc, dependencies);
  1219. AddAutogenExecutableToDependencies(this->Uic, dependencies);
  1220. // Create the custom command that outputs the timestamp file.
  1221. const char timestampFileName[] = "timestamp";
  1222. const std::string outputFile =
  1223. cmStrCat(this->Dir.Build, "/", timestampFileName);
  1224. this->AutogenTarget.DepFile = cmStrCat(this->Dir.Build, "/deps");
  1225. this->AutogenTarget.DepFileRuleName =
  1226. cmStrCat(this->GenTarget->GetName(), "_autogen/", timestampFileName);
  1227. commandLines.push_back(cmMakeCommandLine(
  1228. { cmSystemTools::GetCMakeCommand(), "-E", "touch", outputFile }));
  1229. this->AddGeneratedSource(outputFile, this->Moc);
  1230. const std::string no_main_dependency;
  1231. this->LocalGen->AddCustomCommandToOutput(
  1232. { outputFile }, timestampByproducts, dependencies, no_main_dependency,
  1233. /*implicit_depends=*/{}, commandLines, autogenComment.c_str(),
  1234. this->Dir.Work.c_str(),
  1235. /*cmp0116=*/cmPolicies::NEW, /*replace=*/false,
  1236. /*escapeOldStyle=*/false,
  1237. /*uses_terminal=*/false,
  1238. /*command_expand_lists=*/false, this->AutogenTarget.DepFile, "",
  1239. stdPipesUTF8);
  1240. // Alter variables for the autogen target which now merely wraps the
  1241. // custom command
  1242. dependencies.clear();
  1243. dependencies.push_back(outputFile);
  1244. commandLines.clear();
  1245. autogenComment.clear();
  1246. }
  1247. // Create autogen target
  1248. cmTarget* autogenTarget = this->LocalGen->AddUtilityCommand(
  1249. this->AutogenTarget.Name, true, this->Dir.Work.c_str(),
  1250. /*byproducts=*/autogenByproducts,
  1251. /*depends=*/dependencies, commandLines, cmPolicies::NEW, false,
  1252. autogenComment.c_str());
  1253. // Create autogen generator target
  1254. this->LocalGen->AddGeneratorTarget(
  1255. cm::make_unique<cmGeneratorTarget>(autogenTarget, this->LocalGen));
  1256. // Forward origin utilities to autogen target
  1257. if (this->AutogenTarget.DependOrigin) {
  1258. for (BT<std::pair<std::string, bool>> const& depName :
  1259. this->GenTarget->GetUtilities()) {
  1260. autogenTarget->AddUtility(depName.Value.first, false, this->Makefile);
  1261. }
  1262. }
  1263. if (!useNinjaDepfile) {
  1264. // Add additional autogen target dependencies to autogen target
  1265. for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
  1266. autogenTarget->AddUtility(depTarget->GetName(), false, this->Makefile);
  1267. }
  1268. }
  1269. // Set FOLDER property in autogen target
  1270. if (!this->TargetsFolder.empty()) {
  1271. autogenTarget->SetProperty("FOLDER", this->TargetsFolder);
  1272. }
  1273. // Add autogen target to the origin target dependencies
  1274. this->GenTarget->Target->AddUtility(this->AutogenTarget.Name, false,
  1275. this->Makefile);
  1276. // Add autogen target to the global autogen target dependencies
  1277. if (this->AutogenTarget.GlobalTarget) {
  1278. this->GlobalInitializer->AddToGlobalAutoGen(this->LocalGen,
  1279. this->AutogenTarget.Name);
  1280. }
  1281. }
  1282. return true;
  1283. }
  1284. bool cmQtAutoGenInitializer::InitRccTargets()
  1285. {
  1286. for (Qrc const& qrc : this->Rcc.Qrcs) {
  1287. // Register info file as generated by CMake
  1288. this->Makefile->AddCMakeOutputFile(qrc.InfoFile);
  1289. // Register file at target
  1290. {
  1291. cmSourceFile* sf = this->AddGeneratedSource(qrc.OutputFile, this->Rcc);
  1292. sf->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "On");
  1293. }
  1294. std::vector<std::string> ccOutput;
  1295. ccOutput.push_back(qrc.OutputFile);
  1296. std::vector<std::string> ccDepends;
  1297. // Add the .qrc and info file to the custom command dependencies
  1298. ccDepends.push_back(qrc.QrcFile);
  1299. ccDepends.push_back(qrc.InfoFile);
  1300. bool stdPipesUTF8 = true;
  1301. cmCustomCommandLines commandLines;
  1302. if (this->MultiConfig) {
  1303. // Build for all configurations
  1304. for (std::string const& config : this->ConfigsList) {
  1305. commandLines.push_back(
  1306. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
  1307. "cmake_autorcc", qrc.InfoFile, config }));
  1308. }
  1309. } else {
  1310. commandLines.push_back(
  1311. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
  1312. "cmake_autorcc", qrc.InfoFile, "$<CONFIG>" }));
  1313. }
  1314. std::string ccComment =
  1315. cmStrCat("Automatic RCC for ",
  1316. FileProjectRelativePath(this->Makefile, qrc.QrcFile));
  1317. if (qrc.Generated || this->Rcc.GlobalTarget) {
  1318. // Create custom rcc target
  1319. std::string ccName;
  1320. {
  1321. ccName = cmStrCat(this->GenTarget->GetName(), "_arcc_", qrc.QrcName);
  1322. if (!qrc.Unique) {
  1323. ccName += cmStrCat('_', qrc.QrcPathChecksum);
  1324. }
  1325. cmTarget* autoRccTarget = this->LocalGen->AddUtilityCommand(
  1326. ccName, true, this->Dir.Work.c_str(), ccOutput, ccDepends,
  1327. commandLines, cmPolicies::NEW, false, ccComment.c_str(), false,
  1328. false, "", stdPipesUTF8);
  1329. // Create autogen generator target
  1330. this->LocalGen->AddGeneratorTarget(
  1331. cm::make_unique<cmGeneratorTarget>(autoRccTarget, this->LocalGen));
  1332. // Set FOLDER property in autogen target
  1333. if (!this->TargetsFolder.empty()) {
  1334. autoRccTarget->SetProperty("FOLDER", this->TargetsFolder);
  1335. }
  1336. if (!this->Rcc.ExecutableTargetName.empty()) {
  1337. autoRccTarget->AddUtility(this->Rcc.ExecutableTargetName, false,
  1338. this->Makefile);
  1339. }
  1340. }
  1341. // Add autogen target to the origin target dependencies
  1342. this->GenTarget->Target->AddUtility(ccName, false, this->Makefile);
  1343. // Add autogen target to the global autogen target dependencies
  1344. if (this->Rcc.GlobalTarget) {
  1345. this->GlobalInitializer->AddToGlobalAutoRcc(this->LocalGen, ccName);
  1346. }
  1347. } else {
  1348. // Create custom rcc command
  1349. {
  1350. std::vector<std::string> ccByproducts;
  1351. // Add the resource files to the dependencies
  1352. for (std::string const& fileName : qrc.Resources) {
  1353. // Add resource file to the custom command dependencies
  1354. ccDepends.push_back(fileName);
  1355. }
  1356. if (!this->Rcc.ExecutableTargetName.empty()) {
  1357. ccDepends.push_back(this->Rcc.ExecutableTargetName);
  1358. }
  1359. std::string no_main_dependency;
  1360. cmImplicitDependsList no_implicit_depends;
  1361. this->LocalGen->AddCustomCommandToOutput(
  1362. ccOutput, ccByproducts, ccDepends, no_main_dependency,
  1363. no_implicit_depends, commandLines, ccComment.c_str(),
  1364. this->Dir.Work.c_str(), cmPolicies::NEW, false, true, false, false,
  1365. "", "", stdPipesUTF8);
  1366. }
  1367. // Reconfigure when .qrc file changes
  1368. this->Makefile->AddCMakeDependFile(qrc.QrcFile);
  1369. }
  1370. }
  1371. return true;
  1372. }
  1373. bool cmQtAutoGenInitializer::SetupCustomTargets()
  1374. {
  1375. // Create info directory on demand
  1376. if (!cmSystemTools::MakeDirectory(this->Dir.Info)) {
  1377. cmSystemTools::Error(cmStrCat("AutoGen: Could not create directory: ",
  1378. Quoted(this->Dir.Info)));
  1379. return false;
  1380. }
  1381. // Generate autogen target info file
  1382. if (this->MocOrUicEnabled()) {
  1383. // Write autogen target info files
  1384. if (!this->SetupWriteAutogenInfo()) {
  1385. return false;
  1386. }
  1387. }
  1388. // Write AUTORCC info files
  1389. return !this->Rcc.Enabled || this->SetupWriteRccInfo();
  1390. }
  1391. bool cmQtAutoGenInitializer::SetupWriteAutogenInfo()
  1392. {
  1393. // Utility lambdas
  1394. auto MfDef = [this](std::string const& key) {
  1395. return this->Makefile->GetSafeDefinition(key);
  1396. };
  1397. // Filtered headers and sources
  1398. std::set<std::string> moc_skip;
  1399. std::set<std::string> uic_skip;
  1400. std::vector<MUFile const*> headers;
  1401. std::vector<MUFile const*> sources;
  1402. // Filter headers
  1403. {
  1404. headers.reserve(this->AutogenTarget.Headers.size());
  1405. for (auto const& pair : this->AutogenTarget.Headers) {
  1406. MUFile const* const muf = pair.second.get();
  1407. if (muf->SkipMoc) {
  1408. moc_skip.insert(muf->FullPath);
  1409. }
  1410. if (muf->SkipUic) {
  1411. uic_skip.insert(muf->FullPath);
  1412. }
  1413. if (muf->Generated && !this->CMP0071Accept) {
  1414. continue;
  1415. }
  1416. if (muf->MocIt || muf->UicIt) {
  1417. headers.emplace_back(muf);
  1418. }
  1419. }
  1420. std::sort(headers.begin(), headers.end(),
  1421. [](MUFile const* a, MUFile const* b) {
  1422. return (a->FullPath < b->FullPath);
  1423. });
  1424. }
  1425. // Filter sources
  1426. {
  1427. sources.reserve(this->AutogenTarget.Sources.size());
  1428. for (auto const& pair : this->AutogenTarget.Sources) {
  1429. MUFile const* const muf = pair.second.get();
  1430. if (muf->Generated && !this->CMP0071Accept) {
  1431. continue;
  1432. }
  1433. if (muf->SkipMoc) {
  1434. moc_skip.insert(muf->FullPath);
  1435. }
  1436. if (muf->SkipUic) {
  1437. uic_skip.insert(muf->FullPath);
  1438. }
  1439. if (muf->MocIt || muf->UicIt) {
  1440. sources.emplace_back(muf);
  1441. }
  1442. }
  1443. std::sort(sources.begin(), sources.end(),
  1444. [](MUFile const* a, MUFile const* b) {
  1445. return (a->FullPath < b->FullPath);
  1446. });
  1447. }
  1448. // Info writer
  1449. InfoWriter info;
  1450. // General
  1451. info.SetBool("MULTI_CONFIG", this->MultiConfig);
  1452. info.SetUInt("PARALLEL", this->AutogenTarget.Parallel);
  1453. info.SetUInt("VERBOSITY", this->Verbosity);
  1454. // Directories
  1455. info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
  1456. info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
  1457. info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
  1458. info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
  1459. info.Set("BUILD_DIR", this->Dir.Build);
  1460. info.SetConfig("INCLUDE_DIR", this->Dir.Include);
  1461. info.SetUInt("QT_VERSION_MAJOR", this->QtVersion.Major);
  1462. info.SetUInt("QT_VERSION_MINOR", this->QtVersion.Minor);
  1463. info.Set("QT_MOC_EXECUTABLE", this->Moc.Executable);
  1464. info.Set("QT_UIC_EXECUTABLE", this->Uic.Executable);
  1465. info.Set("CMAKE_EXECUTABLE", cmSystemTools::GetCMakeCommand());
  1466. info.SetConfig("SETTINGS_FILE", this->AutogenTarget.SettingsFile);
  1467. info.SetConfig("PARSE_CACHE_FILE", this->AutogenTarget.ParseCacheFile);
  1468. info.Set("DEP_FILE", this->AutogenTarget.DepFile);
  1469. info.Set("DEP_FILE_RULE_NAME", this->AutogenTarget.DepFileRuleName);
  1470. info.SetArray("CMAKE_LIST_FILES", this->Makefile->GetListFiles());
  1471. info.SetArray("HEADER_EXTENSIONS",
  1472. this->Makefile->GetCMakeInstance()->GetHeaderExtensions());
  1473. auto cfgArray = [this](std::vector<size_t> const& configs) -> Json::Value {
  1474. Json::Value value;
  1475. if (!configs.empty()) {
  1476. value = Json::arrayValue;
  1477. for (size_t ci : configs) {
  1478. value.append(this->ConfigsList[ci]);
  1479. }
  1480. }
  1481. return value;
  1482. };
  1483. info.SetArrayArray("HEADERS", headers,
  1484. [this, &cfgArray](Json::Value& jval, MUFile const* muf) {
  1485. jval.resize(4u);
  1486. jval[0u] = muf->FullPath;
  1487. jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm',
  1488. muf->UicIt ? 'U' : 'u');
  1489. jval[2u] = this->GetMocBuildPath(*muf);
  1490. jval[3u] = cfgArray(muf->Configs);
  1491. });
  1492. info.SetArrayArray(
  1493. "SOURCES", sources, [&cfgArray](Json::Value& jval, MUFile const* muf) {
  1494. jval.resize(3u);
  1495. jval[0u] = muf->FullPath;
  1496. jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm', muf->UicIt ? 'U' : 'u');
  1497. jval[2u] = cfgArray(muf->Configs);
  1498. });
  1499. // Write moc settings
  1500. if (this->Moc.Enabled) {
  1501. info.SetArray("MOC_SKIP", moc_skip);
  1502. info.SetConfigArray("MOC_DEFINITIONS", this->Moc.Defines);
  1503. info.SetConfigArray("MOC_INCLUDES", this->Moc.Includes);
  1504. info.SetArray("MOC_OPTIONS", this->Moc.Options);
  1505. info.SetBool("MOC_RELAXED_MODE", this->Moc.RelaxedMode);
  1506. info.SetBool("MOC_PATH_PREFIX", this->Moc.PathPrefix);
  1507. info.SetArray("MOC_MACRO_NAMES", this->Moc.MacroNames);
  1508. info.SetArrayArray(
  1509. "MOC_DEPEND_FILTERS", this->Moc.DependFilters,
  1510. [](Json::Value& jval, std::pair<std::string, std::string> const& pair) {
  1511. jval.resize(2u);
  1512. jval[0u] = pair.first;
  1513. jval[1u] = pair.second;
  1514. });
  1515. info.SetConfig("MOC_COMPILATION_FILE", this->Moc.CompilationFile);
  1516. info.SetArray("MOC_PREDEFS_CMD", this->Moc.PredefsCmd);
  1517. info.SetConfig("MOC_PREDEFS_FILE", this->Moc.PredefsFile);
  1518. }
  1519. // Write uic settings
  1520. if (this->Uic.Enabled) {
  1521. // Add skipped .ui files
  1522. uic_skip.insert(this->Uic.SkipUi.begin(), this->Uic.SkipUi.end());
  1523. info.SetArray("UIC_SKIP", uic_skip);
  1524. info.SetArrayArray("UIC_UI_FILES", this->Uic.UiFilesWithOptions,
  1525. [](Json::Value& jval, UicT::UiFileT const& uiFile) {
  1526. jval.resize(2u);
  1527. jval[0u] = uiFile.first;
  1528. InfoWriter::MakeStringArray(jval[1u], uiFile.second);
  1529. });
  1530. info.SetConfigArray("UIC_OPTIONS", this->Uic.Options);
  1531. info.SetArray("UIC_SEARCH_PATHS", this->Uic.SearchPaths);
  1532. }
  1533. info.Save(this->AutogenTarget.InfoFile);
  1534. return true;
  1535. }
  1536. bool cmQtAutoGenInitializer::SetupWriteRccInfo()
  1537. {
  1538. for (Qrc const& qrc : this->Rcc.Qrcs) {
  1539. // Utility lambdas
  1540. auto MfDef = [this](std::string const& key) {
  1541. return this->Makefile->GetSafeDefinition(key);
  1542. };
  1543. InfoWriter info;
  1544. // General
  1545. info.SetBool("MULTI_CONFIG", this->MultiConfig);
  1546. info.SetUInt("VERBOSITY", this->Verbosity);
  1547. // Files
  1548. info.Set("LOCK_FILE", qrc.LockFile);
  1549. info.SetConfig("SETTINGS_FILE", qrc.SettingsFile);
  1550. // Directories
  1551. info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
  1552. info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
  1553. info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
  1554. info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
  1555. info.Set("BUILD_DIR", this->Dir.Build);
  1556. info.SetConfig("INCLUDE_DIR", this->Dir.Include);
  1557. // rcc executable
  1558. info.Set("RCC_EXECUTABLE", this->Rcc.Executable);
  1559. info.SetArray("RCC_LIST_OPTIONS",
  1560. this->Rcc.ExecutableFeatures->ListOptions);
  1561. // qrc file
  1562. info.Set("SOURCE", qrc.QrcFile);
  1563. info.Set("OUTPUT_CHECKSUM", qrc.QrcPathChecksum);
  1564. info.Set("OUTPUT_NAME", cmSystemTools::GetFilenameName(qrc.OutputFile));
  1565. info.SetArray("OPTIONS", qrc.Options);
  1566. info.SetArray("INPUTS", qrc.Resources);
  1567. info.Save(qrc.InfoFile);
  1568. }
  1569. return true;
  1570. }
  1571. cmSourceFile* cmQtAutoGenInitializer::RegisterGeneratedSource(
  1572. std::string const& filename)
  1573. {
  1574. cmSourceFile* gFile = this->Makefile->GetOrCreateSource(filename, true);
  1575. gFile->MarkAsGenerated();
  1576. gFile->SetProperty("SKIP_AUTOGEN", "1");
  1577. return gFile;
  1578. }
  1579. cmSourceFile* cmQtAutoGenInitializer::AddGeneratedSource(
  1580. std::string const& filename, GenVarsT const& genVars, bool prepend)
  1581. {
  1582. // Register source at makefile
  1583. cmSourceFile* gFile = this->RegisterGeneratedSource(filename);
  1584. // Add source file to target
  1585. this->GenTarget->AddSource(filename, prepend);
  1586. // Add source file to source group
  1587. this->AddToSourceGroup(filename, genVars.GenNameUpper);
  1588. return gFile;
  1589. }
  1590. void cmQtAutoGenInitializer::AddGeneratedSource(ConfigString const& filename,
  1591. GenVarsT const& genVars,
  1592. bool prepend)
  1593. {
  1594. // XXX(xcode-per-cfg-src): Drop the Xcode-specific part of the condition
  1595. // when the Xcode generator supports per-config sources.
  1596. if (!this->MultiConfig || this->GlobalGen->IsXcode()) {
  1597. this->AddGeneratedSource(filename.Default, genVars, prepend);
  1598. return;
  1599. }
  1600. for (auto const& cfg : this->ConfigsList) {
  1601. std::string const& filenameCfg = filename.Config.at(cfg);
  1602. // Register source at makefile
  1603. this->RegisterGeneratedSource(filenameCfg);
  1604. // Add source file to target for this configuration.
  1605. this->GenTarget->AddSource(
  1606. cmStrCat("$<$<CONFIG:"_s, cfg, ">:"_s, filenameCfg, ">"_s), prepend);
  1607. // Add source file to source group
  1608. this->AddToSourceGroup(filenameCfg, genVars.GenNameUpper);
  1609. }
  1610. }
  1611. void cmQtAutoGenInitializer::AddToSourceGroup(std::string const& fileName,
  1612. cm::string_view genNameUpper)
  1613. {
  1614. cmSourceGroup* sourceGroup = nullptr;
  1615. // Acquire source group
  1616. {
  1617. std::string property;
  1618. std::string groupName;
  1619. {
  1620. // Prefer generator specific source group name
  1621. std::initializer_list<std::string> const props{
  1622. cmStrCat(genNameUpper, "_SOURCE_GROUP"), "AUTOGEN_SOURCE_GROUP"
  1623. };
  1624. for (std::string const& prop : props) {
  1625. cmProp propName = this->Makefile->GetState()->GetGlobalProperty(prop);
  1626. if (cmNonempty(propName)) {
  1627. groupName = *propName;
  1628. property = prop;
  1629. break;
  1630. }
  1631. }
  1632. }
  1633. // Generate a source group on demand
  1634. if (!groupName.empty()) {
  1635. sourceGroup = this->Makefile->GetOrCreateSourceGroup(groupName);
  1636. if (!sourceGroup) {
  1637. cmSystemTools::Error(
  1638. cmStrCat(genNameUpper, " error in ", property,
  1639. ": Could not find or create the source group ",
  1640. cmQtAutoGen::Quoted(groupName)));
  1641. }
  1642. }
  1643. }
  1644. if (sourceGroup) {
  1645. sourceGroup->AddGroupFile(fileName);
  1646. }
  1647. }
  1648. void cmQtAutoGenInitializer::AddCleanFile(std::string const& fileName)
  1649. {
  1650. this->GenTarget->Target->AppendProperty("ADDITIONAL_CLEAN_FILES", fileName,
  1651. false);
  1652. }
  1653. void cmQtAutoGenInitializer::ConfigFileNames(ConfigString& configString,
  1654. cm::string_view prefix,
  1655. cm::string_view suffix)
  1656. {
  1657. configString.Default = cmStrCat(prefix, suffix);
  1658. if (this->MultiConfig) {
  1659. for (auto const& cfg : this->ConfigsList) {
  1660. configString.Config[cfg] = cmStrCat(prefix, '_', cfg, suffix);
  1661. }
  1662. }
  1663. }
  1664. void cmQtAutoGenInitializer::ConfigFileNamesAndGenex(
  1665. ConfigString& configString, std::string& genex, cm::string_view const prefix,
  1666. cm::string_view const suffix)
  1667. {
  1668. this->ConfigFileNames(configString, prefix, suffix);
  1669. if (this->MultiConfig) {
  1670. genex = cmStrCat(prefix, "_$<CONFIG>"_s, suffix);
  1671. } else {
  1672. genex = configString.Default;
  1673. }
  1674. }
  1675. void cmQtAutoGenInitializer::ConfigFileClean(ConfigString& configString)
  1676. {
  1677. this->AddCleanFile(configString.Default);
  1678. if (this->MultiConfig) {
  1679. for (auto const& pair : configString.Config) {
  1680. this->AddCleanFile(pair.second);
  1681. }
  1682. }
  1683. }
  1684. static cmQtAutoGen::IntegerVersion parseMocVersion(std::string str)
  1685. {
  1686. cmQtAutoGen::IntegerVersion result;
  1687. static const std::string prelude = "moc ";
  1688. size_t pos = str.find(prelude);
  1689. if (pos == std::string::npos) {
  1690. return result;
  1691. }
  1692. str.erase(0, prelude.size() + pos);
  1693. std::istringstream iss(str);
  1694. std::string major;
  1695. std::string minor;
  1696. if (!std::getline(iss, major, '.') || !std::getline(iss, minor, '.')) {
  1697. return result;
  1698. }
  1699. result.Major = static_cast<unsigned int>(std::stoi(major));
  1700. result.Minor = static_cast<unsigned int>(std::stoi(minor));
  1701. return result;
  1702. }
  1703. static cmQtAutoGen::IntegerVersion GetMocVersion(
  1704. const std::string& mocExecutablePath)
  1705. {
  1706. std::string capturedStdOut;
  1707. int exitCode;
  1708. if (!cmSystemTools::RunSingleCommand({ mocExecutablePath, "--version" },
  1709. &capturedStdOut, nullptr, &exitCode,
  1710. nullptr, cmSystemTools::OUTPUT_NONE)) {
  1711. return {};
  1712. }
  1713. if (exitCode != 0) {
  1714. return {};
  1715. }
  1716. return parseMocVersion(capturedStdOut);
  1717. }
  1718. static std::string FindMocExecutableFromMocTarget(cmMakefile* makefile,
  1719. unsigned int qtMajorVersion)
  1720. {
  1721. std::string result;
  1722. const std::string mocTargetName =
  1723. "Qt" + std::to_string(qtMajorVersion) + "::moc";
  1724. cmTarget* mocTarget = makefile->FindTargetToUse(mocTargetName);
  1725. if (mocTarget) {
  1726. result = mocTarget->GetSafeProperty("IMPORTED_LOCATION");
  1727. }
  1728. return result;
  1729. }
  1730. std::pair<cmQtAutoGen::IntegerVersion, unsigned int>
  1731. cmQtAutoGenInitializer::GetQtVersion(cmGeneratorTarget const* target,
  1732. std::string mocExecutable)
  1733. {
  1734. // Converts a char ptr to an unsigned int value
  1735. auto toUInt = [](const char* const input) -> unsigned int {
  1736. unsigned long tmp = 0;
  1737. if (input && cmStrToULong(input, &tmp)) {
  1738. return static_cast<unsigned int>(tmp);
  1739. }
  1740. return 0u;
  1741. };
  1742. auto toUInt2 = [](cmProp input) -> unsigned int {
  1743. unsigned long tmp = 0;
  1744. if (input && cmStrToULong(*input, &tmp)) {
  1745. return static_cast<unsigned int>(tmp);
  1746. }
  1747. return 0u;
  1748. };
  1749. // Initialize return value to a default
  1750. std::pair<IntegerVersion, unsigned int> res(
  1751. IntegerVersion(),
  1752. toUInt(target->GetLinkInterfaceDependentStringProperty("QT_MAJOR_VERSION",
  1753. "")));
  1754. // Acquire known Qt versions
  1755. std::vector<cmQtAutoGen::IntegerVersion> knownQtVersions;
  1756. {
  1757. // Qt version variable prefixes
  1758. static std::initializer_list<
  1759. std::pair<cm::string_view, cm::string_view>> const keys{
  1760. { "Qt6Core_VERSION_MAJOR", "Qt6Core_VERSION_MINOR" },
  1761. { "Qt5Core_VERSION_MAJOR", "Qt5Core_VERSION_MINOR" },
  1762. { "QT_VERSION_MAJOR", "QT_VERSION_MINOR" },
  1763. };
  1764. knownQtVersions.reserve(keys.size() * 2);
  1765. // Adds a version to the result (nullptr safe)
  1766. auto addVersion = [&knownQtVersions, &toUInt2](cmProp major,
  1767. cmProp minor) {
  1768. cmQtAutoGen::IntegerVersion ver(toUInt2(major), toUInt2(minor));
  1769. if (ver.Major != 0) {
  1770. knownQtVersions.emplace_back(ver);
  1771. }
  1772. };
  1773. // Read versions from variables
  1774. for (auto const& keyPair : keys) {
  1775. addVersion(target->Makefile->GetDefinition(std::string(keyPair.first)),
  1776. target->Makefile->GetDefinition(std::string(keyPair.second)));
  1777. }
  1778. // Read versions from directory properties
  1779. for (auto const& keyPair : keys) {
  1780. addVersion(target->Makefile->GetProperty(std::string(keyPair.first)),
  1781. target->Makefile->GetProperty(std::string(keyPair.second)));
  1782. }
  1783. }
  1784. // Evaluate known Qt versions
  1785. if (!knownQtVersions.empty()) {
  1786. if (res.second == 0) {
  1787. // No specific version was requested by the target:
  1788. // Use highest known Qt version.
  1789. res.first = knownQtVersions.at(0);
  1790. } else {
  1791. // Pick a version from the known versions:
  1792. for (auto it : knownQtVersions) {
  1793. if (it.Major == res.second) {
  1794. res.first = it;
  1795. break;
  1796. }
  1797. }
  1798. }
  1799. }
  1800. if (res.first.Major == 0) {
  1801. // We could not get the version number from variables or directory
  1802. // properties. This might happen if the find_package call for Qt is wrapped
  1803. // in a function. Try to find the moc executable path from the available
  1804. // targets and call "moc --version" to get the Qt version.
  1805. if (mocExecutable.empty()) {
  1806. mocExecutable =
  1807. FindMocExecutableFromMocTarget(target->Makefile, res.second);
  1808. }
  1809. if (!mocExecutable.empty()) {
  1810. res.first = GetMocVersion(mocExecutable);
  1811. }
  1812. }
  1813. return res;
  1814. }
  1815. std::string cmQtAutoGenInitializer::GetMocBuildPath(MUFile const& muf)
  1816. {
  1817. std::string res;
  1818. if (!muf.MocIt) {
  1819. return res;
  1820. }
  1821. std::string basePath =
  1822. cmStrCat(this->PathCheckSum.getPart(muf.FullPath), "/moc_",
  1823. FileNameWithoutLastExtension(muf.FullPath));
  1824. res = cmStrCat(basePath, ".cpp");
  1825. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  1826. return res;
  1827. }
  1828. // File name already emitted.
  1829. // Try appending the header suffix to the base path.
  1830. basePath = cmStrCat(basePath, '_', muf.SF->GetExtension());
  1831. res = cmStrCat(basePath, ".cpp");
  1832. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  1833. return res;
  1834. }
  1835. // File name with header extension already emitted.
  1836. // Try adding a number to the base path.
  1837. constexpr std::size_t number_begin = 2;
  1838. constexpr std::size_t number_end = 256;
  1839. for (std::size_t ii = number_begin; ii != number_end; ++ii) {
  1840. res = cmStrCat(basePath, '_', ii, ".cpp");
  1841. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  1842. return res;
  1843. }
  1844. }
  1845. // Output file name conflict (unlikely, but still...)
  1846. cmSystemTools::Error(
  1847. cmStrCat("moc output file name conflict for ", muf.FullPath));
  1848. return res;
  1849. }
  1850. bool cmQtAutoGenInitializer::GetQtExecutable(GenVarsT& genVars,
  1851. const std::string& executable,
  1852. bool ignoreMissingTarget) const
  1853. {
  1854. auto print_err = [this, &genVars](std::string const& err) {
  1855. cmSystemTools::Error(cmStrCat(genVars.GenNameUpper, " for target ",
  1856. this->GenTarget->GetName(), ": ", err));
  1857. };
  1858. // Custom executable
  1859. {
  1860. std::string const prop = cmStrCat(genVars.GenNameUpper, "_EXECUTABLE");
  1861. std::string const& val = this->GenTarget->Target->GetSafeProperty(prop);
  1862. if (!val.empty()) {
  1863. // Evaluate generator expression
  1864. {
  1865. cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
  1866. cmGeneratorExpression ge(lfbt);
  1867. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(val);
  1868. genVars.Executable = cge->Evaluate(this->LocalGen, "");
  1869. }
  1870. if (genVars.Executable.empty() && !ignoreMissingTarget) {
  1871. print_err(prop + " evaluates to an empty value");
  1872. return false;
  1873. }
  1874. // Create empty compiler features.
  1875. genVars.ExecutableFeatures =
  1876. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  1877. return true;
  1878. }
  1879. }
  1880. // Find executable target
  1881. {
  1882. // Find executable target name
  1883. cm::string_view prefix;
  1884. if (this->QtVersion.Major == 4) {
  1885. prefix = "Qt4::";
  1886. } else if (this->QtVersion.Major == 5) {
  1887. prefix = "Qt5::";
  1888. } else if (this->QtVersion.Major == 6) {
  1889. prefix = "Qt6::";
  1890. }
  1891. std::string const targetName = cmStrCat(prefix, executable);
  1892. // Find target
  1893. cmGeneratorTarget* genTarget =
  1894. this->LocalGen->FindGeneratorTargetToUse(targetName);
  1895. if (genTarget) {
  1896. genVars.ExecutableTargetName = targetName;
  1897. genVars.ExecutableTarget = genTarget;
  1898. if (genTarget->IsImported()) {
  1899. genVars.Executable = genTarget->ImportedGetLocation("");
  1900. } else {
  1901. genVars.Executable = genTarget->GetLocation("");
  1902. }
  1903. } else {
  1904. if (ignoreMissingTarget) {
  1905. // Create empty compiler features.
  1906. genVars.ExecutableFeatures =
  1907. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  1908. return true;
  1909. }
  1910. print_err(cmStrCat("Could not find ", executable, " executable target ",
  1911. targetName));
  1912. return false;
  1913. }
  1914. }
  1915. // Get executable features
  1916. {
  1917. std::string err;
  1918. genVars.ExecutableFeatures = this->GlobalInitializer->GetCompilerFeatures(
  1919. executable, genVars.Executable, err);
  1920. if (!genVars.ExecutableFeatures) {
  1921. print_err(err);
  1922. return false;
  1923. }
  1924. }
  1925. return true;
  1926. }