cmQtAutoGenInitializer.cxx 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110
  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. // Files provided by the autogen target
  1020. std::vector<std::string> autogenByproducts;
  1021. if (this->Moc.Enabled) {
  1022. this->AddGeneratedSource(this->Moc.CompilationFile, this->Moc, true);
  1023. autogenByproducts.push_back(this->Moc.CompilationFileGenex);
  1024. }
  1025. if (this->Uic.Enabled) {
  1026. for (const auto& file : this->Uic.UiHeaders) {
  1027. this->AddGeneratedSource(file.first, this->Uic);
  1028. autogenByproducts.push_back(file.second);
  1029. }
  1030. }
  1031. // Compose target comment
  1032. std::string autogenComment;
  1033. {
  1034. std::string tools;
  1035. if (this->Moc.Enabled) {
  1036. tools += "MOC";
  1037. }
  1038. if (this->Uic.Enabled) {
  1039. if (!tools.empty()) {
  1040. tools += " and ";
  1041. }
  1042. tools += "UIC";
  1043. }
  1044. autogenComment = cmStrCat("Automatic ", tools, " for target ",
  1045. this->GenTarget->GetName());
  1046. }
  1047. // Compose command lines
  1048. // FIXME: Take advantage of our per-config mocs_compilation_$<CONFIG>.cpp
  1049. // instead of fiddling with the include directories
  1050. std::vector<std::string> configs;
  1051. this->GlobalGen->GetQtAutoGenConfigs(configs);
  1052. bool stdPipesUTF8 = true;
  1053. cmCustomCommandLines commandLines;
  1054. for (auto const& config : configs) {
  1055. commandLines.push_back(cmMakeCommandLine(
  1056. { cmSystemTools::GetCMakeCommand(), "-E", "cmake_autogen",
  1057. this->AutogenTarget.InfoFile, config }));
  1058. }
  1059. // Use PRE_BUILD on demand
  1060. bool usePRE_BUILD = false;
  1061. if (this->GlobalGen->GetName().find("Visual Studio") != std::string::npos) {
  1062. // Under VS use a PRE_BUILD event instead of a separate target to
  1063. // reduce the number of targets loaded into the IDE.
  1064. // This also works around a VS 11 bug that may skip updating the target:
  1065. // https://connect.microsoft.com/VisualStudio/feedback/details/769495
  1066. usePRE_BUILD = true;
  1067. }
  1068. // Disable PRE_BUILD in some cases
  1069. if (usePRE_BUILD) {
  1070. // Cannot use PRE_BUILD with file depends
  1071. if (!this->AutogenTarget.DependFiles.empty()) {
  1072. usePRE_BUILD = false;
  1073. }
  1074. // Cannot use PRE_BUILD when a global autogen target is in place
  1075. if (this->AutogenTarget.GlobalTarget) {
  1076. usePRE_BUILD = false;
  1077. }
  1078. }
  1079. // Create the autogen target/command
  1080. if (usePRE_BUILD) {
  1081. // Add additional autogen target dependencies to origin target
  1082. for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
  1083. this->GenTarget->Target->AddUtility(depTarget->GetName(), false,
  1084. this->Makefile);
  1085. }
  1086. if (!this->Uic.UiFilesNoOptions.empty() ||
  1087. !this->Uic.UiFilesWithOptions.empty()) {
  1088. // Add a generated timestamp file
  1089. ConfigString timestampFile;
  1090. std::string timestampFileGenex;
  1091. ConfigFileNamesAndGenex(timestampFile, timestampFileGenex,
  1092. cmStrCat(this->Dir.Build, "/autouic"_s),
  1093. ".stamp"_s);
  1094. this->AddGeneratedSource(timestampFile, this->Uic);
  1095. // Add a step in the pre-build command to touch the timestamp file
  1096. commandLines.push_back(
  1097. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E", "touch",
  1098. timestampFileGenex }));
  1099. // UIC needs to be re-run if any of the known UI files change or the
  1100. // executable itself has been updated
  1101. auto uicDependencies = this->Uic.UiFilesNoOptions;
  1102. for (auto const& uiFile : this->Uic.UiFilesWithOptions) {
  1103. uicDependencies.push_back(uiFile.first);
  1104. }
  1105. AddAutogenExecutableToDependencies(this->Uic, uicDependencies);
  1106. // Add a rule file to cause the target to build if a dependency has
  1107. // changed, which will trigger the pre-build command to run autogen
  1108. std::string no_main_dependency;
  1109. cmCustomCommandLines no_command_lines;
  1110. this->LocalGen->AddCustomCommandToOutput(
  1111. timestampFileGenex, uicDependencies, no_main_dependency,
  1112. no_command_lines, /*comment=*/"", this->Dir.Work.c_str(),
  1113. /*cmp0116=*/cmPolicies::NEW, /*replace=*/false,
  1114. /*escapeOldStyle=*/false, /*uses_terminal=*/false,
  1115. /*command_expand_lists=*/false, /*depfile=*/"", /*job_pool=*/"",
  1116. stdPipesUTF8);
  1117. }
  1118. // Add the pre-build command directly to bypass the OBJECT_LIBRARY
  1119. // rejection in cmMakefile::AddCustomCommandToTarget because we know
  1120. // PRE_BUILD will work for an OBJECT_LIBRARY in this specific case.
  1121. //
  1122. // PRE_BUILD does not support file dependencies!
  1123. const std::vector<std::string> no_output;
  1124. const std::vector<std::string> no_deps;
  1125. cmCustomCommand cc(no_output, autogenByproducts, no_deps, commandLines,
  1126. this->Makefile->GetBacktrace(), autogenComment.c_str(),
  1127. this->Dir.Work.c_str(), stdPipesUTF8);
  1128. cc.SetEscapeOldStyle(false);
  1129. cc.SetEscapeAllowMakeVars(true);
  1130. this->GenTarget->Target->AddPreBuildCommand(std::move(cc));
  1131. } else {
  1132. // Add link library target dependencies to the autogen target
  1133. // dependencies
  1134. if (this->AutogenTarget.DependOrigin) {
  1135. // add_dependencies/addUtility do not support generator expressions.
  1136. // We depend only on the libraries found in all configs therefore.
  1137. std::map<cmGeneratorTarget const*, std::size_t> commonTargets;
  1138. for (std::string const& config : this->ConfigsList) {
  1139. cmLinkImplementationLibraries const* libs =
  1140. this->GenTarget->GetLinkImplementationLibraries(config);
  1141. if (libs) {
  1142. for (cmLinkItem const& item : libs->Libraries) {
  1143. cmGeneratorTarget const* libTarget = item.Target;
  1144. if (libTarget &&
  1145. !StaticLibraryCycle(this->GenTarget, libTarget, config)) {
  1146. // Increment target config count
  1147. commonTargets[libTarget]++;
  1148. }
  1149. }
  1150. }
  1151. }
  1152. for (auto const& item : commonTargets) {
  1153. if (item.second == this->ConfigsList.size()) {
  1154. this->AutogenTarget.DependTargets.insert(item.first->Target);
  1155. }
  1156. }
  1157. }
  1158. std::vector<std::string> dependencies(
  1159. this->AutogenTarget.DependFiles.begin(),
  1160. this->AutogenTarget.DependFiles.end());
  1161. const bool useNinjaDepfile = this->QtVersion >= IntegerVersion(5, 15) &&
  1162. this->GlobalGen->GetName().find("Ninja") != std::string::npos;
  1163. if (useNinjaDepfile) {
  1164. // Create a custom command that generates a timestamp file and
  1165. // has a depfile assigned. The depfile is created by JobDepFilesMergeT.
  1166. //
  1167. // Also create an additional '_autogen_timestamp_deps' that the custom
  1168. // command will depend on. It will have no sources or commands to
  1169. // execute, but it will have dependencies that would originally be
  1170. // assigned to the pre-Qt 5.15 'autogen' target. These dependencies will
  1171. // serve as a list of order-only dependencies for the custom command,
  1172. // without forcing the custom command to re-execute.
  1173. //
  1174. // The dependency tree would then look like
  1175. // '_autogen_timestamp_deps (order-only)' <- '/timestamp' file <-
  1176. // '_autogen' target.
  1177. const auto timestampTargetName =
  1178. cmStrCat(this->GenTarget->GetName(), "_autogen_timestamp_deps");
  1179. std::vector<std::string> timestampTargetProvides;
  1180. cmCustomCommandLines timestampTargetCommandLines;
  1181. // Add additional autogen target dependencies to
  1182. // '_autogen_timestamp_deps'.
  1183. for (const cmTarget* t : this->AutogenTarget.DependTargets) {
  1184. dependencies.push_back(t->GetName());
  1185. }
  1186. cmTarget* timestampTarget = this->LocalGen->AddUtilityCommand(
  1187. timestampTargetName, true, this->Dir.Work.c_str(),
  1188. /*byproducts=*/timestampTargetProvides,
  1189. /*depends=*/dependencies, timestampTargetCommandLines, cmPolicies::NEW,
  1190. false, nullptr);
  1191. this->LocalGen->AddGeneratorTarget(
  1192. cm::make_unique<cmGeneratorTarget>(timestampTarget, this->LocalGen));
  1193. // Set FOLDER property on the timestamp target, so it appears in the
  1194. // appropriate folder in an IDE or in the file api.
  1195. if (!this->TargetsFolder.empty()) {
  1196. timestampTarget->SetProperty("FOLDER", this->TargetsFolder);
  1197. }
  1198. // Make '/timestamp' file depend on '_autogen_timestamp_deps' and on the
  1199. // moc and uic executables (whichever are enabled).
  1200. dependencies.clear();
  1201. dependencies.push_back(timestampTargetName);
  1202. AddAutogenExecutableToDependencies(this->Moc, dependencies);
  1203. AddAutogenExecutableToDependencies(this->Uic, dependencies);
  1204. // Create the custom command that outputs the timestamp file.
  1205. const char timestampFileName[] = "timestamp";
  1206. const std::string outputFile =
  1207. cmStrCat(this->Dir.Build, "/", timestampFileName);
  1208. this->AutogenTarget.DepFile = cmStrCat(this->Dir.Build, "/deps");
  1209. this->AutogenTarget.DepFileRuleName =
  1210. cmStrCat(this->GenTarget->GetName(), "_autogen/", timestampFileName);
  1211. commandLines.push_back(cmMakeCommandLine(
  1212. { cmSystemTools::GetCMakeCommand(), "-E", "touch", outputFile }));
  1213. this->AddGeneratedSource(outputFile, this->Moc);
  1214. const std::string no_main_dependency;
  1215. this->LocalGen->AddCustomCommandToOutput(
  1216. outputFile, dependencies, no_main_dependency, commandLines,
  1217. autogenComment.c_str(), this->Dir.Work.c_str(),
  1218. /*cmp0116=*/cmPolicies::NEW, /*replace=*/false,
  1219. /*escapeOldStyle=*/false,
  1220. /*uses_terminal=*/false,
  1221. /*command_expand_lists=*/false, this->AutogenTarget.DepFile, "",
  1222. stdPipesUTF8);
  1223. // Alter variables for the autogen target which now merely wraps the
  1224. // custom command
  1225. dependencies.clear();
  1226. dependencies.push_back(outputFile);
  1227. commandLines.clear();
  1228. autogenComment.clear();
  1229. }
  1230. // Create autogen target
  1231. cmTarget* autogenTarget = this->LocalGen->AddUtilityCommand(
  1232. this->AutogenTarget.Name, true, this->Dir.Work.c_str(),
  1233. /*byproducts=*/autogenByproducts,
  1234. /*depends=*/dependencies, commandLines, cmPolicies::NEW, false,
  1235. autogenComment.c_str());
  1236. // Create autogen generator target
  1237. this->LocalGen->AddGeneratorTarget(
  1238. cm::make_unique<cmGeneratorTarget>(autogenTarget, this->LocalGen));
  1239. // Forward origin utilities to autogen target
  1240. if (this->AutogenTarget.DependOrigin) {
  1241. for (BT<std::pair<std::string, bool>> const& depName :
  1242. this->GenTarget->GetUtilities()) {
  1243. autogenTarget->AddUtility(depName.Value.first, false, this->Makefile);
  1244. }
  1245. }
  1246. if (!useNinjaDepfile) {
  1247. // Add additional autogen target dependencies to autogen target
  1248. for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
  1249. autogenTarget->AddUtility(depTarget->GetName(), false, this->Makefile);
  1250. }
  1251. }
  1252. // Set FOLDER property in autogen target
  1253. if (!this->TargetsFolder.empty()) {
  1254. autogenTarget->SetProperty("FOLDER", this->TargetsFolder);
  1255. }
  1256. // Add autogen target to the origin target dependencies
  1257. this->GenTarget->Target->AddUtility(this->AutogenTarget.Name, false,
  1258. this->Makefile);
  1259. // Add autogen target to the global autogen target dependencies
  1260. if (this->AutogenTarget.GlobalTarget) {
  1261. this->GlobalInitializer->AddToGlobalAutoGen(this->LocalGen,
  1262. this->AutogenTarget.Name);
  1263. }
  1264. }
  1265. return true;
  1266. }
  1267. bool cmQtAutoGenInitializer::InitRccTargets()
  1268. {
  1269. for (Qrc const& qrc : this->Rcc.Qrcs) {
  1270. // Register info file as generated by CMake
  1271. this->Makefile->AddCMakeOutputFile(qrc.InfoFile);
  1272. // Register file at target
  1273. {
  1274. cmSourceFile* sf = this->AddGeneratedSource(qrc.OutputFile, this->Rcc);
  1275. sf->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "On");
  1276. }
  1277. std::vector<std::string> ccOutput;
  1278. ccOutput.push_back(qrc.OutputFile);
  1279. std::vector<std::string> ccDepends;
  1280. // Add the .qrc and info file to the custom command dependencies
  1281. ccDepends.push_back(qrc.QrcFile);
  1282. ccDepends.push_back(qrc.InfoFile);
  1283. bool stdPipesUTF8 = true;
  1284. cmCustomCommandLines commandLines;
  1285. if (this->MultiConfig) {
  1286. // Build for all configurations
  1287. for (std::string const& config : this->ConfigsList) {
  1288. commandLines.push_back(
  1289. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
  1290. "cmake_autorcc", qrc.InfoFile, config }));
  1291. }
  1292. } else {
  1293. commandLines.push_back(
  1294. cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
  1295. "cmake_autorcc", qrc.InfoFile, "$<CONFIG>" }));
  1296. }
  1297. std::string ccComment =
  1298. cmStrCat("Automatic RCC for ",
  1299. FileProjectRelativePath(this->Makefile, qrc.QrcFile));
  1300. if (qrc.Generated || this->Rcc.GlobalTarget) {
  1301. // Create custom rcc target
  1302. std::string ccName;
  1303. {
  1304. ccName = cmStrCat(this->GenTarget->GetName(), "_arcc_", qrc.QrcName);
  1305. if (!qrc.Unique) {
  1306. ccName += cmStrCat('_', qrc.QrcPathChecksum);
  1307. }
  1308. cmTarget* autoRccTarget = this->LocalGen->AddUtilityCommand(
  1309. ccName, true, this->Dir.Work.c_str(), ccOutput, ccDepends,
  1310. commandLines, cmPolicies::NEW, false, ccComment.c_str(), false,
  1311. false, "", stdPipesUTF8);
  1312. // Create autogen generator target
  1313. this->LocalGen->AddGeneratorTarget(
  1314. cm::make_unique<cmGeneratorTarget>(autoRccTarget, this->LocalGen));
  1315. // Set FOLDER property in autogen target
  1316. if (!this->TargetsFolder.empty()) {
  1317. autoRccTarget->SetProperty("FOLDER", this->TargetsFolder);
  1318. }
  1319. if (!this->Rcc.ExecutableTargetName.empty()) {
  1320. autoRccTarget->AddUtility(this->Rcc.ExecutableTargetName, false,
  1321. this->Makefile);
  1322. }
  1323. }
  1324. // Add autogen target to the origin target dependencies
  1325. this->GenTarget->Target->AddUtility(ccName, false, this->Makefile);
  1326. // Add autogen target to the global autogen target dependencies
  1327. if (this->Rcc.GlobalTarget) {
  1328. this->GlobalInitializer->AddToGlobalAutoRcc(this->LocalGen, ccName);
  1329. }
  1330. } else {
  1331. // Create custom rcc command
  1332. {
  1333. std::vector<std::string> ccByproducts;
  1334. // Add the resource files to the dependencies
  1335. for (std::string const& fileName : qrc.Resources) {
  1336. // Add resource file to the custom command dependencies
  1337. ccDepends.push_back(fileName);
  1338. }
  1339. if (!this->Rcc.ExecutableTargetName.empty()) {
  1340. ccDepends.push_back(this->Rcc.ExecutableTargetName);
  1341. }
  1342. std::string no_main_dependency;
  1343. cmImplicitDependsList no_implicit_depends;
  1344. this->LocalGen->AddCustomCommandToOutput(
  1345. ccOutput, ccByproducts, ccDepends, no_main_dependency,
  1346. no_implicit_depends, commandLines, ccComment.c_str(),
  1347. this->Dir.Work.c_str(), cmPolicies::NEW, false, true, false, false,
  1348. "", "", stdPipesUTF8);
  1349. }
  1350. // Reconfigure when .qrc file changes
  1351. this->Makefile->AddCMakeDependFile(qrc.QrcFile);
  1352. }
  1353. }
  1354. return true;
  1355. }
  1356. bool cmQtAutoGenInitializer::SetupCustomTargets()
  1357. {
  1358. // Create info directory on demand
  1359. if (!cmSystemTools::MakeDirectory(this->Dir.Info)) {
  1360. cmSystemTools::Error(cmStrCat("AutoGen: Could not create directory: ",
  1361. Quoted(this->Dir.Info)));
  1362. return false;
  1363. }
  1364. // Generate autogen target info file
  1365. if (this->MocOrUicEnabled()) {
  1366. // Write autogen target info files
  1367. if (!this->SetupWriteAutogenInfo()) {
  1368. return false;
  1369. }
  1370. }
  1371. // Write AUTORCC info files
  1372. return !this->Rcc.Enabled || this->SetupWriteRccInfo();
  1373. }
  1374. bool cmQtAutoGenInitializer::SetupWriteAutogenInfo()
  1375. {
  1376. // Utility lambdas
  1377. auto MfDef = [this](std::string const& key) {
  1378. return this->Makefile->GetSafeDefinition(key);
  1379. };
  1380. // Filtered headers and sources
  1381. std::set<std::string> moc_skip;
  1382. std::set<std::string> uic_skip;
  1383. std::vector<MUFile const*> headers;
  1384. std::vector<MUFile const*> sources;
  1385. // Filter headers
  1386. {
  1387. headers.reserve(this->AutogenTarget.Headers.size());
  1388. for (auto const& pair : this->AutogenTarget.Headers) {
  1389. MUFile const* const muf = pair.second.get();
  1390. if (muf->SkipMoc) {
  1391. moc_skip.insert(muf->FullPath);
  1392. }
  1393. if (muf->SkipUic) {
  1394. uic_skip.insert(muf->FullPath);
  1395. }
  1396. if (muf->Generated && !this->CMP0071Accept) {
  1397. continue;
  1398. }
  1399. if (muf->MocIt || muf->UicIt) {
  1400. headers.emplace_back(muf);
  1401. }
  1402. }
  1403. std::sort(headers.begin(), headers.end(),
  1404. [](MUFile const* a, MUFile const* b) {
  1405. return (a->FullPath < b->FullPath);
  1406. });
  1407. }
  1408. // Filter sources
  1409. {
  1410. sources.reserve(this->AutogenTarget.Sources.size());
  1411. for (auto const& pair : this->AutogenTarget.Sources) {
  1412. MUFile const* const muf = pair.second.get();
  1413. if (muf->Generated && !this->CMP0071Accept) {
  1414. continue;
  1415. }
  1416. if (muf->SkipMoc) {
  1417. moc_skip.insert(muf->FullPath);
  1418. }
  1419. if (muf->SkipUic) {
  1420. uic_skip.insert(muf->FullPath);
  1421. }
  1422. if (muf->MocIt || muf->UicIt) {
  1423. sources.emplace_back(muf);
  1424. }
  1425. }
  1426. std::sort(sources.begin(), sources.end(),
  1427. [](MUFile const* a, MUFile const* b) {
  1428. return (a->FullPath < b->FullPath);
  1429. });
  1430. }
  1431. // Info writer
  1432. InfoWriter info;
  1433. // General
  1434. info.SetBool("MULTI_CONFIG", this->MultiConfig);
  1435. info.SetUInt("PARALLEL", this->AutogenTarget.Parallel);
  1436. info.SetUInt("VERBOSITY", this->Verbosity);
  1437. // Directories
  1438. info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
  1439. info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
  1440. info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
  1441. info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
  1442. info.Set("BUILD_DIR", this->Dir.Build);
  1443. info.SetConfig("INCLUDE_DIR", this->Dir.Include);
  1444. info.SetUInt("QT_VERSION_MAJOR", this->QtVersion.Major);
  1445. info.SetUInt("QT_VERSION_MINOR", this->QtVersion.Minor);
  1446. info.Set("QT_MOC_EXECUTABLE", this->Moc.Executable);
  1447. info.Set("QT_UIC_EXECUTABLE", this->Uic.Executable);
  1448. info.Set("CMAKE_EXECUTABLE", cmSystemTools::GetCMakeCommand());
  1449. info.SetConfig("SETTINGS_FILE", this->AutogenTarget.SettingsFile);
  1450. info.SetConfig("PARSE_CACHE_FILE", this->AutogenTarget.ParseCacheFile);
  1451. info.Set("DEP_FILE", this->AutogenTarget.DepFile);
  1452. info.Set("DEP_FILE_RULE_NAME", this->AutogenTarget.DepFileRuleName);
  1453. info.SetArray("CMAKE_LIST_FILES", this->Makefile->GetListFiles());
  1454. info.SetArray("HEADER_EXTENSIONS",
  1455. this->Makefile->GetCMakeInstance()->GetHeaderExtensions());
  1456. auto cfgArray = [this](std::vector<size_t> const& configs) -> Json::Value {
  1457. Json::Value value;
  1458. if (!configs.empty()) {
  1459. value = Json::arrayValue;
  1460. for (size_t ci : configs) {
  1461. value.append(this->ConfigsList[ci]);
  1462. }
  1463. }
  1464. return value;
  1465. };
  1466. info.SetArrayArray("HEADERS", headers,
  1467. [this, &cfgArray](Json::Value& jval, MUFile const* muf) {
  1468. jval.resize(4u);
  1469. jval[0u] = muf->FullPath;
  1470. jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm',
  1471. muf->UicIt ? 'U' : 'u');
  1472. jval[2u] = this->GetMocBuildPath(*muf);
  1473. jval[3u] = cfgArray(muf->Configs);
  1474. });
  1475. info.SetArrayArray(
  1476. "SOURCES", sources, [&cfgArray](Json::Value& jval, MUFile const* muf) {
  1477. jval.resize(3u);
  1478. jval[0u] = muf->FullPath;
  1479. jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm', muf->UicIt ? 'U' : 'u');
  1480. jval[2u] = cfgArray(muf->Configs);
  1481. });
  1482. // Write moc settings
  1483. if (this->Moc.Enabled) {
  1484. info.SetArray("MOC_SKIP", moc_skip);
  1485. info.SetConfigArray("MOC_DEFINITIONS", this->Moc.Defines);
  1486. info.SetConfigArray("MOC_INCLUDES", this->Moc.Includes);
  1487. info.SetArray("MOC_OPTIONS", this->Moc.Options);
  1488. info.SetBool("MOC_RELAXED_MODE", this->Moc.RelaxedMode);
  1489. info.SetBool("MOC_PATH_PREFIX", this->Moc.PathPrefix);
  1490. info.SetArray("MOC_MACRO_NAMES", this->Moc.MacroNames);
  1491. info.SetArrayArray(
  1492. "MOC_DEPEND_FILTERS", this->Moc.DependFilters,
  1493. [](Json::Value& jval, std::pair<std::string, std::string> const& pair) {
  1494. jval.resize(2u);
  1495. jval[0u] = pair.first;
  1496. jval[1u] = pair.second;
  1497. });
  1498. info.SetConfig("MOC_COMPILATION_FILE", this->Moc.CompilationFile);
  1499. info.SetArray("MOC_PREDEFS_CMD", this->Moc.PredefsCmd);
  1500. info.SetConfig("MOC_PREDEFS_FILE", this->Moc.PredefsFile);
  1501. }
  1502. // Write uic settings
  1503. if (this->Uic.Enabled) {
  1504. // Add skipped .ui files
  1505. uic_skip.insert(this->Uic.SkipUi.begin(), this->Uic.SkipUi.end());
  1506. info.SetArray("UIC_SKIP", uic_skip);
  1507. info.SetArrayArray("UIC_UI_FILES", this->Uic.UiFilesWithOptions,
  1508. [](Json::Value& jval, UicT::UiFileT const& uiFile) {
  1509. jval.resize(2u);
  1510. jval[0u] = uiFile.first;
  1511. InfoWriter::MakeStringArray(jval[1u], uiFile.second);
  1512. });
  1513. info.SetConfigArray("UIC_OPTIONS", this->Uic.Options);
  1514. info.SetArray("UIC_SEARCH_PATHS", this->Uic.SearchPaths);
  1515. }
  1516. info.Save(this->AutogenTarget.InfoFile);
  1517. return true;
  1518. }
  1519. bool cmQtAutoGenInitializer::SetupWriteRccInfo()
  1520. {
  1521. for (Qrc const& qrc : this->Rcc.Qrcs) {
  1522. // Utility lambdas
  1523. auto MfDef = [this](std::string const& key) {
  1524. return this->Makefile->GetSafeDefinition(key);
  1525. };
  1526. InfoWriter info;
  1527. // General
  1528. info.SetBool("MULTI_CONFIG", this->MultiConfig);
  1529. info.SetUInt("VERBOSITY", this->Verbosity);
  1530. // Files
  1531. info.Set("LOCK_FILE", qrc.LockFile);
  1532. info.SetConfig("SETTINGS_FILE", qrc.SettingsFile);
  1533. // Directories
  1534. info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
  1535. info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
  1536. info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
  1537. info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
  1538. info.Set("BUILD_DIR", this->Dir.Build);
  1539. info.SetConfig("INCLUDE_DIR", this->Dir.Include);
  1540. // rcc executable
  1541. info.Set("RCC_EXECUTABLE", this->Rcc.Executable);
  1542. info.SetArray("RCC_LIST_OPTIONS",
  1543. this->Rcc.ExecutableFeatures->ListOptions);
  1544. // qrc file
  1545. info.Set("SOURCE", qrc.QrcFile);
  1546. info.Set("OUTPUT_CHECKSUM", qrc.QrcPathChecksum);
  1547. info.Set("OUTPUT_NAME", cmSystemTools::GetFilenameName(qrc.OutputFile));
  1548. info.SetArray("OPTIONS", qrc.Options);
  1549. info.SetArray("INPUTS", qrc.Resources);
  1550. info.Save(qrc.InfoFile);
  1551. }
  1552. return true;
  1553. }
  1554. cmSourceFile* cmQtAutoGenInitializer::RegisterGeneratedSource(
  1555. std::string const& filename)
  1556. {
  1557. cmSourceFile* gFile = this->Makefile->GetOrCreateSource(filename, true);
  1558. gFile->MarkAsGenerated();
  1559. gFile->SetProperty("SKIP_AUTOGEN", "1");
  1560. return gFile;
  1561. }
  1562. cmSourceFile* cmQtAutoGenInitializer::AddGeneratedSource(
  1563. std::string const& filename, GenVarsT const& genVars, bool prepend)
  1564. {
  1565. // Register source at makefile
  1566. cmSourceFile* gFile = this->RegisterGeneratedSource(filename);
  1567. // Add source file to target
  1568. this->GenTarget->AddSource(filename, prepend);
  1569. // Add source file to source group
  1570. this->AddToSourceGroup(filename, genVars.GenNameUpper);
  1571. return gFile;
  1572. }
  1573. void cmQtAutoGenInitializer::AddGeneratedSource(ConfigString const& filename,
  1574. GenVarsT const& genVars,
  1575. bool prepend)
  1576. {
  1577. // XXX(xcode-per-cfg-src): Drop the Xcode-specific part of the condition
  1578. // when the Xcode generator supports per-config sources.
  1579. if (!this->MultiConfig || this->GlobalGen->IsXcode()) {
  1580. this->AddGeneratedSource(filename.Default, genVars, prepend);
  1581. return;
  1582. }
  1583. for (auto const& cfg : this->ConfigsList) {
  1584. std::string const& filenameCfg = filename.Config.at(cfg);
  1585. // Register source at makefile
  1586. this->RegisterGeneratedSource(filenameCfg);
  1587. // Add source file to target for this configuration.
  1588. this->GenTarget->AddSource(
  1589. cmStrCat("$<$<CONFIG:"_s, cfg, ">:"_s, filenameCfg, ">"_s), prepend);
  1590. // Add source file to source group
  1591. this->AddToSourceGroup(filenameCfg, genVars.GenNameUpper);
  1592. }
  1593. }
  1594. void cmQtAutoGenInitializer::AddToSourceGroup(std::string const& fileName,
  1595. cm::string_view genNameUpper)
  1596. {
  1597. cmSourceGroup* sourceGroup = nullptr;
  1598. // Acquire source group
  1599. {
  1600. std::string property;
  1601. std::string groupName;
  1602. {
  1603. // Prefer generator specific source group name
  1604. std::initializer_list<std::string> const props{
  1605. cmStrCat(genNameUpper, "_SOURCE_GROUP"), "AUTOGEN_SOURCE_GROUP"
  1606. };
  1607. for (std::string const& prop : props) {
  1608. cmProp propName = this->Makefile->GetState()->GetGlobalProperty(prop);
  1609. if (cmNonempty(propName)) {
  1610. groupName = *propName;
  1611. property = prop;
  1612. break;
  1613. }
  1614. }
  1615. }
  1616. // Generate a source group on demand
  1617. if (!groupName.empty()) {
  1618. sourceGroup = this->Makefile->GetOrCreateSourceGroup(groupName);
  1619. if (!sourceGroup) {
  1620. cmSystemTools::Error(
  1621. cmStrCat(genNameUpper, " error in ", property,
  1622. ": Could not find or create the source group ",
  1623. cmQtAutoGen::Quoted(groupName)));
  1624. }
  1625. }
  1626. }
  1627. if (sourceGroup) {
  1628. sourceGroup->AddGroupFile(fileName);
  1629. }
  1630. }
  1631. void cmQtAutoGenInitializer::AddCleanFile(std::string const& fileName)
  1632. {
  1633. this->GenTarget->Target->AppendProperty("ADDITIONAL_CLEAN_FILES", fileName,
  1634. false);
  1635. }
  1636. void cmQtAutoGenInitializer::ConfigFileNames(ConfigString& configString,
  1637. cm::string_view prefix,
  1638. cm::string_view suffix)
  1639. {
  1640. configString.Default = cmStrCat(prefix, suffix);
  1641. if (this->MultiConfig) {
  1642. for (auto const& cfg : this->ConfigsList) {
  1643. configString.Config[cfg] = cmStrCat(prefix, '_', cfg, suffix);
  1644. }
  1645. }
  1646. }
  1647. void cmQtAutoGenInitializer::ConfigFileNamesAndGenex(
  1648. ConfigString& configString, std::string& genex, cm::string_view const prefix,
  1649. cm::string_view const suffix)
  1650. {
  1651. this->ConfigFileNames(configString, prefix, suffix);
  1652. if (this->MultiConfig) {
  1653. genex = cmStrCat(prefix, "_$<CONFIG>"_s, suffix);
  1654. } else {
  1655. genex = configString.Default;
  1656. }
  1657. }
  1658. void cmQtAutoGenInitializer::ConfigFileClean(ConfigString& configString)
  1659. {
  1660. this->AddCleanFile(configString.Default);
  1661. if (this->MultiConfig) {
  1662. for (auto const& pair : configString.Config) {
  1663. this->AddCleanFile(pair.second);
  1664. }
  1665. }
  1666. }
  1667. static cmQtAutoGen::IntegerVersion parseMocVersion(std::string str)
  1668. {
  1669. cmQtAutoGen::IntegerVersion result;
  1670. static const std::string prelude = "moc ";
  1671. size_t pos = str.find(prelude);
  1672. if (pos == std::string::npos) {
  1673. return result;
  1674. }
  1675. str.erase(0, prelude.size() + pos);
  1676. std::istringstream iss(str);
  1677. std::string major;
  1678. std::string minor;
  1679. if (!std::getline(iss, major, '.') || !std::getline(iss, minor, '.')) {
  1680. return result;
  1681. }
  1682. result.Major = static_cast<unsigned int>(std::stoi(major));
  1683. result.Minor = static_cast<unsigned int>(std::stoi(minor));
  1684. return result;
  1685. }
  1686. static cmQtAutoGen::IntegerVersion GetMocVersion(
  1687. const std::string& mocExecutablePath)
  1688. {
  1689. std::string capturedStdOut;
  1690. int exitCode;
  1691. if (!cmSystemTools::RunSingleCommand({ mocExecutablePath, "--version" },
  1692. &capturedStdOut, nullptr, &exitCode,
  1693. nullptr, cmSystemTools::OUTPUT_NONE)) {
  1694. return {};
  1695. }
  1696. if (exitCode != 0) {
  1697. return {};
  1698. }
  1699. return parseMocVersion(capturedStdOut);
  1700. }
  1701. static std::string FindMocExecutableFromMocTarget(cmMakefile* makefile,
  1702. unsigned int qtMajorVersion)
  1703. {
  1704. std::string result;
  1705. const std::string mocTargetName =
  1706. "Qt" + std::to_string(qtMajorVersion) + "::moc";
  1707. cmTarget* mocTarget = makefile->FindTargetToUse(mocTargetName);
  1708. if (mocTarget) {
  1709. result = mocTarget->GetSafeProperty("IMPORTED_LOCATION");
  1710. }
  1711. return result;
  1712. }
  1713. std::pair<cmQtAutoGen::IntegerVersion, unsigned int>
  1714. cmQtAutoGenInitializer::GetQtVersion(cmGeneratorTarget const* target,
  1715. std::string mocExecutable)
  1716. {
  1717. // Converts a char ptr to an unsigned int value
  1718. auto toUInt = [](const char* const input) -> unsigned int {
  1719. unsigned long tmp = 0;
  1720. if (input && cmStrToULong(input, &tmp)) {
  1721. return static_cast<unsigned int>(tmp);
  1722. }
  1723. return 0u;
  1724. };
  1725. auto toUInt2 = [](cmProp input) -> unsigned int {
  1726. unsigned long tmp = 0;
  1727. if (input && cmStrToULong(*input, &tmp)) {
  1728. return static_cast<unsigned int>(tmp);
  1729. }
  1730. return 0u;
  1731. };
  1732. // Initialize return value to a default
  1733. std::pair<IntegerVersion, unsigned int> res(
  1734. IntegerVersion(),
  1735. toUInt(target->GetLinkInterfaceDependentStringProperty("QT_MAJOR_VERSION",
  1736. "")));
  1737. // Acquire known Qt versions
  1738. std::vector<cmQtAutoGen::IntegerVersion> knownQtVersions;
  1739. {
  1740. // Qt version variable prefixes
  1741. static std::initializer_list<
  1742. std::pair<cm::string_view, cm::string_view>> const keys{
  1743. { "Qt6Core_VERSION_MAJOR", "Qt6Core_VERSION_MINOR" },
  1744. { "Qt5Core_VERSION_MAJOR", "Qt5Core_VERSION_MINOR" },
  1745. { "QT_VERSION_MAJOR", "QT_VERSION_MINOR" },
  1746. };
  1747. knownQtVersions.reserve(keys.size() * 2);
  1748. // Adds a version to the result (nullptr safe)
  1749. auto addVersion = [&knownQtVersions, &toUInt2](cmProp major,
  1750. cmProp minor) {
  1751. cmQtAutoGen::IntegerVersion ver(toUInt2(major), toUInt2(minor));
  1752. if (ver.Major != 0) {
  1753. knownQtVersions.emplace_back(ver);
  1754. }
  1755. };
  1756. // Read versions from variables
  1757. for (auto const& keyPair : keys) {
  1758. addVersion(target->Makefile->GetDefinition(std::string(keyPair.first)),
  1759. target->Makefile->GetDefinition(std::string(keyPair.second)));
  1760. }
  1761. // Read versions from directory properties
  1762. for (auto const& keyPair : keys) {
  1763. addVersion(target->Makefile->GetProperty(std::string(keyPair.first)),
  1764. target->Makefile->GetProperty(std::string(keyPair.second)));
  1765. }
  1766. }
  1767. // Evaluate known Qt versions
  1768. if (!knownQtVersions.empty()) {
  1769. if (res.second == 0) {
  1770. // No specific version was requested by the target:
  1771. // Use highest known Qt version.
  1772. res.first = knownQtVersions.at(0);
  1773. } else {
  1774. // Pick a version from the known versions:
  1775. for (auto it : knownQtVersions) {
  1776. if (it.Major == res.second) {
  1777. res.first = it;
  1778. break;
  1779. }
  1780. }
  1781. }
  1782. }
  1783. if (res.first.Major == 0) {
  1784. // We could not get the version number from variables or directory
  1785. // properties. This might happen if the find_package call for Qt is wrapped
  1786. // in a function. Try to find the moc executable path from the available
  1787. // targets and call "moc --version" to get the Qt version.
  1788. if (mocExecutable.empty()) {
  1789. mocExecutable =
  1790. FindMocExecutableFromMocTarget(target->Makefile, res.second);
  1791. }
  1792. if (!mocExecutable.empty()) {
  1793. res.first = GetMocVersion(mocExecutable);
  1794. }
  1795. }
  1796. return res;
  1797. }
  1798. std::string cmQtAutoGenInitializer::GetMocBuildPath(MUFile const& muf)
  1799. {
  1800. std::string res;
  1801. if (!muf.MocIt) {
  1802. return res;
  1803. }
  1804. std::string basePath =
  1805. cmStrCat(this->PathCheckSum.getPart(muf.FullPath), "/moc_",
  1806. FileNameWithoutLastExtension(muf.FullPath));
  1807. res = cmStrCat(basePath, ".cpp");
  1808. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  1809. return res;
  1810. }
  1811. // File name already emitted.
  1812. // Try appending the header suffix to the base path.
  1813. basePath = cmStrCat(basePath, '_', muf.SF->GetExtension());
  1814. res = cmStrCat(basePath, ".cpp");
  1815. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  1816. return res;
  1817. }
  1818. // File name with header extension already emitted.
  1819. // Try adding a number to the base path.
  1820. constexpr std::size_t number_begin = 2;
  1821. constexpr std::size_t number_end = 256;
  1822. for (std::size_t ii = number_begin; ii != number_end; ++ii) {
  1823. res = cmStrCat(basePath, '_', ii, ".cpp");
  1824. if (this->Moc.EmittedBuildPaths.emplace(res).second) {
  1825. return res;
  1826. }
  1827. }
  1828. // Output file name conflict (unlikely, but still...)
  1829. cmSystemTools::Error(
  1830. cmStrCat("moc output file name conflict for ", muf.FullPath));
  1831. return res;
  1832. }
  1833. bool cmQtAutoGenInitializer::GetQtExecutable(GenVarsT& genVars,
  1834. const std::string& executable,
  1835. bool ignoreMissingTarget) const
  1836. {
  1837. auto print_err = [this, &genVars](std::string const& err) {
  1838. cmSystemTools::Error(cmStrCat(genVars.GenNameUpper, " for target ",
  1839. this->GenTarget->GetName(), ": ", err));
  1840. };
  1841. // Custom executable
  1842. {
  1843. std::string const prop = cmStrCat(genVars.GenNameUpper, "_EXECUTABLE");
  1844. std::string const& val = this->GenTarget->Target->GetSafeProperty(prop);
  1845. if (!val.empty()) {
  1846. // Evaluate generator expression
  1847. {
  1848. cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
  1849. cmGeneratorExpression ge(lfbt);
  1850. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(val);
  1851. genVars.Executable = cge->Evaluate(this->LocalGen, "");
  1852. }
  1853. if (genVars.Executable.empty() && !ignoreMissingTarget) {
  1854. print_err(prop + " evaluates to an empty value");
  1855. return false;
  1856. }
  1857. // Create empty compiler features.
  1858. genVars.ExecutableFeatures =
  1859. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  1860. return true;
  1861. }
  1862. }
  1863. // Find executable target
  1864. {
  1865. // Find executable target name
  1866. cm::string_view prefix;
  1867. if (this->QtVersion.Major == 4) {
  1868. prefix = "Qt4::";
  1869. } else if (this->QtVersion.Major == 5) {
  1870. prefix = "Qt5::";
  1871. } else if (this->QtVersion.Major == 6) {
  1872. prefix = "Qt6::";
  1873. }
  1874. std::string const targetName = cmStrCat(prefix, executable);
  1875. // Find target
  1876. cmGeneratorTarget* genTarget =
  1877. this->LocalGen->FindGeneratorTargetToUse(targetName);
  1878. if (genTarget) {
  1879. genVars.ExecutableTargetName = targetName;
  1880. genVars.ExecutableTarget = genTarget;
  1881. if (genTarget->IsImported()) {
  1882. genVars.Executable = genTarget->ImportedGetLocation("");
  1883. } else {
  1884. genVars.Executable = genTarget->GetLocation("");
  1885. }
  1886. } else {
  1887. if (ignoreMissingTarget) {
  1888. // Create empty compiler features.
  1889. genVars.ExecutableFeatures =
  1890. std::make_shared<cmQtAutoGen::CompilerFeatures>();
  1891. return true;
  1892. }
  1893. print_err(cmStrCat("Could not find ", executable, " executable target ",
  1894. targetName));
  1895. return false;
  1896. }
  1897. }
  1898. // Get executable features
  1899. {
  1900. std::string err;
  1901. genVars.ExecutableFeatures = this->GlobalInitializer->GetCompilerFeatures(
  1902. executable, genVars.Executable, err);
  1903. if (!genVars.ExecutableFeatures) {
  1904. print_err(err);
  1905. return false;
  1906. }
  1907. }
  1908. return true;
  1909. }