cmQtAutoGenInitializer.cxx 72 KB

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