cmQtAutoGenerators.cxx 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629
  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 "cmQtAutoGenerators.h"
  4. #include <algorithm>
  5. #include <assert.h>
  6. #include <cmConfigure.h>
  7. #include <cmsys/FStream.hxx>
  8. #include <cmsys/Terminal.h>
  9. #include <iostream>
  10. #include <sstream>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include <utility>
  14. #include "cmAlgorithms.h"
  15. #include "cmFilePathChecksum.h"
  16. #include "cmGlobalGenerator.h"
  17. #include "cmMakefile.h"
  18. #include "cmOutputConverter.h"
  19. #include "cmStateDirectory.h"
  20. #include "cmStateSnapshot.h"
  21. #include "cmSystemTools.h"
  22. #include "cm_auto_ptr.hxx"
  23. #include "cmake.h"
  24. #if defined(__APPLE__)
  25. #include <unistd.h>
  26. #endif
  27. // -- Static variables
  28. static const char* MocOldSettingsKey = "AM_MOC_OLD_SETTINGS";
  29. static const char* UicOldSettingsKey = "AM_UIC_OLD_SETTINGS";
  30. static const char* RccOldSettingsKey = "AM_RCC_OLD_SETTINGS";
  31. // -- Static functions
  32. static std::string GetConfigDefinition(cmMakefile* makefile,
  33. const std::string& key,
  34. const std::string& config)
  35. {
  36. std::string keyConf = key;
  37. if (!config.empty()) {
  38. keyConf += "_";
  39. keyConf += config;
  40. }
  41. const char* valueConf = makefile->GetDefinition(keyConf);
  42. if (valueConf != CM_NULLPTR) {
  43. return valueConf;
  44. }
  45. return makefile->GetSafeDefinition(key);
  46. }
  47. static std::string OldSettingsFile(const std::string& targetDirectory)
  48. {
  49. std::string filename(cmSystemTools::CollapseFullPath(targetDirectory));
  50. cmSystemTools::ConvertToUnixSlashes(filename);
  51. filename += "/AutogenOldSettings.cmake";
  52. return filename;
  53. }
  54. static std::string FindMatchingHeader(
  55. const std::string& absPath, const std::string& mocSubDir,
  56. const std::string& basename,
  57. const std::vector<std::string>& headerExtensions)
  58. {
  59. std::string header;
  60. for (std::vector<std::string>::const_iterator ext = headerExtensions.begin();
  61. ext != headerExtensions.end(); ++ext) {
  62. std::string sourceFilePath = absPath + basename + "." + (*ext);
  63. if (cmsys::SystemTools::FileExists(sourceFilePath.c_str())) {
  64. header = sourceFilePath;
  65. break;
  66. }
  67. // Try subdirectory instead
  68. if (!mocSubDir.empty()) {
  69. sourceFilePath = mocSubDir + basename + "." + (*ext);
  70. if (cmsys::SystemTools::FileExists(sourceFilePath.c_str())) {
  71. header = sourceFilePath;
  72. break;
  73. }
  74. }
  75. }
  76. return header;
  77. }
  78. static std::string ExtractSubDir(const std::string& absPath,
  79. const std::string& currentMoc)
  80. {
  81. std::string subDir;
  82. if (currentMoc.find_first_of('/') != std::string::npos) {
  83. subDir = absPath + cmsys::SystemTools::GetFilenamePath(currentMoc) + '/';
  84. }
  85. return subDir;
  86. }
  87. static bool FileNameIsUnique(const std::string& filePath,
  88. const std::map<std::string, std::string>& fileMap)
  89. {
  90. size_t count(0);
  91. const std::string fileName = cmsys::SystemTools::GetFilenameName(filePath);
  92. for (std::map<std::string, std::string>::const_iterator si = fileMap.begin();
  93. si != fileMap.end(); ++si) {
  94. if (cmsys::SystemTools::GetFilenameName(si->first) == fileName) {
  95. ++count;
  96. if (count > 1) {
  97. return false;
  98. }
  99. }
  100. }
  101. return true;
  102. }
  103. static std::string ReadAll(const std::string& filename)
  104. {
  105. cmsys::ifstream file(filename.c_str());
  106. std::ostringstream stream;
  107. stream << file.rdbuf();
  108. file.close();
  109. return stream.str();
  110. }
  111. /**
  112. * @brief Tests if buildFile doesn't exist or is older than sourceFile
  113. * @return True if buildFile doesn't exist or is older than sourceFile
  114. */
  115. static bool FileAbsentOrOlder(const std::string& buildFile,
  116. const std::string& sourceFile)
  117. {
  118. int result = 0;
  119. bool success =
  120. cmsys::SystemTools::FileTimeCompare(buildFile, sourceFile, &result);
  121. return (!success || (result <= 0));
  122. }
  123. static bool ListContains(const std::vector<std::string>& list,
  124. const std::string& entry)
  125. {
  126. return (std::find(list.begin(), list.end(), entry) != list.end());
  127. }
  128. static std::string JoinOptions(const std::map<std::string, std::string>& opts)
  129. {
  130. std::string result;
  131. for (std::map<std::string, std::string>::const_iterator it = opts.begin();
  132. it != opts.end(); ++it) {
  133. if (it != opts.begin()) {
  134. result += "%%%";
  135. }
  136. result += it->first;
  137. result += "===";
  138. result += it->second;
  139. }
  140. return result;
  141. }
  142. static std::string JoinExts(const std::vector<std::string>& lst)
  143. {
  144. std::string result;
  145. if (!lst.empty()) {
  146. const std::string separator = ",";
  147. for (std::vector<std::string>::const_iterator it = lst.begin();
  148. it != lst.end(); ++it) {
  149. if (it != lst.begin()) {
  150. result += separator;
  151. }
  152. result += '.';
  153. result += *it;
  154. }
  155. }
  156. return result;
  157. }
  158. static void UicMergeOptions(std::vector<std::string>& opts,
  159. const std::vector<std::string>& fileOpts,
  160. bool isQt5)
  161. {
  162. static const char* valueOptions[] = { "tr", "translate",
  163. "postfix", "generator",
  164. "include", // Since Qt 5.3
  165. "g" };
  166. std::vector<std::string> extraOpts;
  167. for (std::vector<std::string>::const_iterator it = fileOpts.begin();
  168. it != fileOpts.end(); ++it) {
  169. std::vector<std::string>::iterator existingIt =
  170. std::find(opts.begin(), opts.end(), *it);
  171. if (existingIt != opts.end()) {
  172. const char* o = it->c_str();
  173. if (*o == '-') {
  174. ++o;
  175. }
  176. if (isQt5 && *o == '-') {
  177. ++o;
  178. }
  179. if (std::find_if(cmArrayBegin(valueOptions), cmArrayEnd(valueOptions),
  180. cmStrCmp(*it)) != cmArrayEnd(valueOptions)) {
  181. assert(existingIt + 1 != opts.end());
  182. *(existingIt + 1) = *(it + 1);
  183. ++it;
  184. }
  185. } else {
  186. extraOpts.push_back(*it);
  187. }
  188. }
  189. opts.insert(opts.end(), extraOpts.begin(), extraOpts.end());
  190. }
  191. // -- Class methods
  192. cmQtAutoGenerators::cmQtAutoGenerators()
  193. : Verbose(cmsys::SystemTools::HasEnv("VERBOSE"))
  194. , ColorOutput(true)
  195. , RunMocFailed(false)
  196. , RunUicFailed(false)
  197. , RunRccFailed(false)
  198. , GenerateMocAll(false)
  199. , GenerateUicAll(false)
  200. , GenerateRccAll(false)
  201. {
  202. std::string colorEnv;
  203. cmsys::SystemTools::GetEnv("COLOR", colorEnv);
  204. if (!colorEnv.empty()) {
  205. if (cmSystemTools::IsOn(colorEnv.c_str())) {
  206. this->ColorOutput = true;
  207. } else {
  208. this->ColorOutput = false;
  209. }
  210. }
  211. // Precompile regular expressions
  212. this->RegExpQObject.compile("[\n][ \t]*Q_OBJECT[^a-zA-Z0-9_]");
  213. this->RegExpQGadget.compile("[\n][ \t]*Q_GADGET[^a-zA-Z0-9_]");
  214. this->RegExpMocInclude.compile(
  215. "[\n][ \t]*#[ \t]*include[ \t]+"
  216. "[\"<](([^ \">]+/)?moc_[^ \">/]+\\.cpp|[^ \">]+\\.moc)[\">]");
  217. this->RegExpUicInclude.compile("[\n][ \t]*#[ \t]*include[ \t]+"
  218. "[\"<](([^ \">]+/)?ui_[^ \">/]+\\.h)[\">]");
  219. }
  220. bool cmQtAutoGenerators::Run(const std::string& targetDirectory,
  221. const std::string& config)
  222. {
  223. cmake cm;
  224. cm.SetHomeOutputDirectory(targetDirectory);
  225. cm.SetHomeDirectory(targetDirectory);
  226. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  227. cmGlobalGenerator gg(&cm);
  228. cmStateSnapshot snapshot = cm.GetCurrentSnapshot();
  229. snapshot.GetDirectory().SetCurrentBinary(targetDirectory);
  230. snapshot.GetDirectory().SetCurrentSource(targetDirectory);
  231. CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&gg, snapshot));
  232. gg.SetCurrentMakefile(mf.get());
  233. if (!this->ReadAutogenInfoFile(mf.get(), targetDirectory, config)) {
  234. return false;
  235. }
  236. // Read old settings
  237. this->OldSettingsReadFile(mf.get(), targetDirectory);
  238. // Init and run
  239. this->Init();
  240. if (this->QtMajorVersion == "4" || this->QtMajorVersion == "5") {
  241. if (!this->RunAutogen(mf.get())) {
  242. return false;
  243. }
  244. }
  245. // Write latest settings
  246. if (!this->OldSettingsWriteFile(targetDirectory)) {
  247. return false;
  248. }
  249. return true;
  250. }
  251. bool cmQtAutoGenerators::ReadAutogenInfoFile(
  252. cmMakefile* makefile, const std::string& targetDirectory,
  253. const std::string& config)
  254. {
  255. std::string filename(cmSystemTools::CollapseFullPath(targetDirectory));
  256. cmSystemTools::ConvertToUnixSlashes(filename);
  257. filename += "/AutogenInfo.cmake";
  258. if (!makefile->ReadListFile(filename.c_str())) {
  259. std::ostringstream err;
  260. err << "AutoGen: error processing file: " << filename << std::endl;
  261. this->LogError(err.str());
  262. return false;
  263. }
  264. // - Target names
  265. this->OriginTargetName =
  266. makefile->GetSafeDefinition("AM_ORIGIN_TARGET_NAME");
  267. this->AutogenTargetName = makefile->GetSafeDefinition("AM_TARGET_NAME");
  268. // - Directories
  269. this->ProjectSourceDir = makefile->GetSafeDefinition("AM_CMAKE_SOURCE_DIR");
  270. this->ProjectBinaryDir = makefile->GetSafeDefinition("AM_CMAKE_BINARY_DIR");
  271. this->CurrentSourceDir =
  272. makefile->GetSafeDefinition("AM_CMAKE_CURRENT_SOURCE_DIR");
  273. this->CurrentBinaryDir =
  274. makefile->GetSafeDefinition("AM_CMAKE_CURRENT_BINARY_DIR");
  275. // - Qt environment
  276. this->QtMajorVersion = makefile->GetSafeDefinition("AM_QT_VERSION_MAJOR");
  277. if (this->QtMajorVersion == "") {
  278. this->QtMajorVersion =
  279. makefile->GetSafeDefinition("AM_Qt5Core_VERSION_MAJOR");
  280. }
  281. this->MocExecutable = makefile->GetSafeDefinition("AM_QT_MOC_EXECUTABLE");
  282. this->UicExecutable = makefile->GetSafeDefinition("AM_QT_UIC_EXECUTABLE");
  283. this->RccExecutable = makefile->GetSafeDefinition("AM_QT_RCC_EXECUTABLE");
  284. // - File Lists
  285. cmSystemTools::ExpandListArgument(makefile->GetSafeDefinition("AM_SOURCES"),
  286. this->Sources);
  287. cmSystemTools::ExpandListArgument(makefile->GetSafeDefinition("AM_HEADERS"),
  288. this->Headers);
  289. // - Moc
  290. cmSystemTools::ExpandListArgument(makefile->GetSafeDefinition("AM_SKIP_MOC"),
  291. this->SkipMoc);
  292. this->MocCompileDefinitionsStr =
  293. GetConfigDefinition(makefile, "AM_MOC_COMPILE_DEFINITIONS", config);
  294. this->MocIncludesStr =
  295. GetConfigDefinition(makefile, "AM_MOC_INCLUDES", config);
  296. this->MocOptionsStr = makefile->GetSafeDefinition("AM_MOC_OPTIONS");
  297. // - Uic
  298. cmSystemTools::ExpandListArgument(makefile->GetSafeDefinition("AM_SKIP_UIC"),
  299. this->SkipUic);
  300. cmSystemTools::ExpandListArgument(
  301. GetConfigDefinition(makefile, "AM_UIC_TARGET_OPTIONS", config),
  302. this->UicTargetOptions);
  303. {
  304. std::vector<std::string> uicFilesVec;
  305. std::vector<std::string> uicOptionsVec;
  306. cmSystemTools::ExpandListArgument(
  307. makefile->GetSafeDefinition("AM_UIC_OPTIONS_FILES"), uicFilesVec);
  308. cmSystemTools::ExpandListArgument(
  309. makefile->GetSafeDefinition("AM_UIC_OPTIONS_OPTIONS"), uicOptionsVec);
  310. if (uicFilesVec.size() != uicOptionsVec.size()) {
  311. std::ostringstream err;
  312. err << "AutoGen: Error: Uic files/options lists size missmatch in: "
  313. << filename << std::endl;
  314. this->LogError(err.str());
  315. return false;
  316. }
  317. for (std::vector<std::string>::iterator fileIt = uicFilesVec.begin(),
  318. optionIt = uicOptionsVec.begin();
  319. fileIt != uicFilesVec.end(); ++fileIt, ++optionIt) {
  320. cmSystemTools::ReplaceString(*optionIt, "@list_sep@", ";");
  321. this->UicOptions[*fileIt] = *optionIt;
  322. }
  323. }
  324. // - Rcc
  325. cmSystemTools::ExpandListArgument(
  326. makefile->GetSafeDefinition("AM_RCC_SOURCES"), this->RccSources);
  327. {
  328. std::vector<std::string> rccFilesVec;
  329. std::vector<std::string> rccOptionsVec;
  330. cmSystemTools::ExpandListArgument(
  331. makefile->GetSafeDefinition("AM_RCC_OPTIONS_FILES"), rccFilesVec);
  332. cmSystemTools::ExpandListArgument(
  333. makefile->GetSafeDefinition("AM_RCC_OPTIONS_OPTIONS"), rccOptionsVec);
  334. if (rccFilesVec.size() != rccOptionsVec.size()) {
  335. std::ostringstream err;
  336. err << "AutoGen: Error: RCC files/options lists size missmatch in: "
  337. << filename << std::endl;
  338. this->LogError(err.str());
  339. return false;
  340. }
  341. for (std::vector<std::string>::iterator fileIt = rccFilesVec.begin(),
  342. optionIt = rccOptionsVec.begin();
  343. fileIt != rccFilesVec.end(); ++fileIt, ++optionIt) {
  344. cmSystemTools::ReplaceString(*optionIt, "@list_sep@", ";");
  345. this->RccOptions[*fileIt] = *optionIt;
  346. }
  347. }
  348. {
  349. std::vector<std::string> rccInputLists;
  350. cmSystemTools::ExpandListArgument(
  351. makefile->GetSafeDefinition("AM_RCC_INPUTS"), rccInputLists);
  352. // qrc files in the end of the list may have been empty
  353. if (rccInputLists.size() < this->RccSources.size()) {
  354. rccInputLists.resize(this->RccSources.size());
  355. }
  356. if (this->RccSources.size() != rccInputLists.size()) {
  357. std::ostringstream err;
  358. err << "AutoGen: Error: RCC sources/inputs lists size missmatch in: "
  359. << filename << std::endl;
  360. this->LogError(err.str());
  361. return false;
  362. }
  363. for (std::vector<std::string>::iterator fileIt = this->RccSources.begin(),
  364. inputIt = rccInputLists.begin();
  365. fileIt != this->RccSources.end(); ++fileIt, ++inputIt) {
  366. cmSystemTools::ReplaceString(*inputIt, "@list_sep@", ";");
  367. std::vector<std::string> rccInputFiles;
  368. cmSystemTools::ExpandListArgument(*inputIt, rccInputFiles);
  369. this->RccInputs[*fileIt] = rccInputFiles;
  370. }
  371. }
  372. // - Flags
  373. this->IncludeProjectDirsBefore =
  374. makefile->IsOn("AM_CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE");
  375. this->MocRelaxedMode = makefile->IsOn("AM_MOC_RELAXED_MODE");
  376. return true;
  377. }
  378. std::string cmQtAutoGenerators::MocSettingsStringCompose()
  379. {
  380. std::string res;
  381. res += this->MocCompileDefinitionsStr;
  382. res += " ~~~ ";
  383. res += this->MocIncludesStr;
  384. res += " ~~~ ";
  385. res += this->MocOptionsStr;
  386. res += " ~~~ ";
  387. res += this->IncludeProjectDirsBefore ? "TRUE" : "FALSE";
  388. res += " ~~~ ";
  389. return res;
  390. }
  391. std::string cmQtAutoGenerators::UicSettingsStringCompose()
  392. {
  393. std::string res;
  394. res += cmJoin(this->UicTargetOptions, "@osep@");
  395. res += " ~~~ ";
  396. res += JoinOptions(this->UicOptions);
  397. res += " ~~~ ";
  398. return res;
  399. }
  400. std::string cmQtAutoGenerators::RccSettingsStringCompose()
  401. {
  402. std::string res;
  403. res += JoinOptions(this->RccOptions);
  404. res += " ~~~ ";
  405. return res;
  406. }
  407. void cmQtAutoGenerators::OldSettingsReadFile(
  408. cmMakefile* makefile, const std::string& targetDirectory)
  409. {
  410. if (!this->MocExecutable.empty() || !this->UicExecutable.empty() ||
  411. !this->RccExecutable.empty()) {
  412. // Compose current settings strings
  413. this->MocSettingsString = this->MocSettingsStringCompose();
  414. this->UicSettingsString = this->UicSettingsStringCompose();
  415. this->RccSettingsString = this->RccSettingsStringCompose();
  416. // Read old settings
  417. const std::string filename = OldSettingsFile(targetDirectory);
  418. if (makefile->ReadListFile(filename.c_str())) {
  419. if (!this->MocExecutable.empty()) {
  420. const std::string sol = makefile->GetSafeDefinition(MocOldSettingsKey);
  421. if (sol != this->MocSettingsString) {
  422. this->GenerateMocAll = true;
  423. }
  424. }
  425. if (!this->UicExecutable.empty()) {
  426. const std::string sol = makefile->GetSafeDefinition(UicOldSettingsKey);
  427. if (sol != this->UicSettingsString) {
  428. this->GenerateUicAll = true;
  429. }
  430. }
  431. if (!this->RccExecutable.empty()) {
  432. const std::string sol = makefile->GetSafeDefinition(RccOldSettingsKey);
  433. if (sol != this->RccSettingsString) {
  434. this->GenerateRccAll = true;
  435. }
  436. }
  437. // In case any setting changed remove the old settings file.
  438. // This triggers a full rebuild on the next run if the current
  439. // build is aborted before writing the current settings in the end.
  440. if (this->GenerateMocAll || this->GenerateUicAll ||
  441. this->GenerateRccAll) {
  442. cmSystemTools::RemoveFile(filename);
  443. }
  444. } else {
  445. // If the file could not be read re-generate everythiung.
  446. this->GenerateMocAll = true;
  447. this->GenerateUicAll = true;
  448. this->GenerateRccAll = true;
  449. }
  450. }
  451. }
  452. bool cmQtAutoGenerators::OldSettingsWriteFile(
  453. const std::string& targetDirectory)
  454. {
  455. bool success = true;
  456. // Only write if any setting changed
  457. if (this->GenerateMocAll || this->GenerateUicAll || this->GenerateRccAll) {
  458. const std::string filename = OldSettingsFile(targetDirectory);
  459. cmsys::ofstream outfile;
  460. outfile.open(filename.c_str(), std::ios::trunc);
  461. if (outfile) {
  462. if (!this->MocExecutable.empty()) {
  463. outfile << "set(" << MocOldSettingsKey << " "
  464. << cmOutputConverter::EscapeForCMake(this->MocSettingsString)
  465. << ")\n";
  466. }
  467. if (!this->UicExecutable.empty()) {
  468. outfile << "set(" << UicOldSettingsKey << " "
  469. << cmOutputConverter::EscapeForCMake(this->UicSettingsString)
  470. << ")\n";
  471. }
  472. if (!this->RccExecutable.empty()) {
  473. outfile << "set(" << RccOldSettingsKey << " "
  474. << cmOutputConverter::EscapeForCMake(this->RccSettingsString)
  475. << ")\n";
  476. }
  477. success = outfile.good();
  478. outfile.close();
  479. } else {
  480. success = false;
  481. // Remove old settings file to trigger full rebuild on next run
  482. cmSystemTools::RemoveFile(filename);
  483. {
  484. std::ostringstream err;
  485. err << "AutoGen: Error: Writing old settings file failed: " << filename
  486. << std::endl;
  487. this->LogError(err.str());
  488. }
  489. }
  490. }
  491. return success;
  492. }
  493. void cmQtAutoGenerators::Init()
  494. {
  495. this->AutogenBuildSubDir = this->AutogenTargetName;
  496. this->AutogenBuildSubDir += "/";
  497. this->OutMocCppFilenameRel = this->AutogenBuildSubDir;
  498. this->OutMocCppFilenameRel += "moc_compilation.cpp";
  499. this->OutMocCppFilenameAbs =
  500. this->CurrentBinaryDir + this->OutMocCppFilenameRel;
  501. // Init file path checksum generator
  502. fpathCheckSum.setupParentDirs(this->CurrentSourceDir, this->CurrentBinaryDir,
  503. this->ProjectSourceDir,
  504. this->ProjectBinaryDir);
  505. std::vector<std::string> cdefList;
  506. cmSystemTools::ExpandListArgument(this->MocCompileDefinitionsStr, cdefList);
  507. for (std::vector<std::string>::const_iterator it = cdefList.begin();
  508. it != cdefList.end(); ++it) {
  509. this->MocDefinitions.push_back("-D" + (*it));
  510. }
  511. cmSystemTools::ExpandListArgument(this->MocOptionsStr, this->MocOptions);
  512. std::vector<std::string> incPaths;
  513. cmSystemTools::ExpandListArgument(this->MocIncludesStr, incPaths);
  514. std::set<std::string> frameworkPaths;
  515. for (std::vector<std::string>::const_iterator it = incPaths.begin();
  516. it != incPaths.end(); ++it) {
  517. const std::string& path = *it;
  518. this->MocIncludes.push_back("-I" + path);
  519. if (cmHasLiteralSuffix(path, ".framework/Headers")) {
  520. // Go up twice to get to the framework root
  521. std::vector<std::string> pathComponents;
  522. cmsys::SystemTools::SplitPath(path, pathComponents);
  523. std::string frameworkPath = cmsys::SystemTools::JoinPath(
  524. pathComponents.begin(), pathComponents.end() - 2);
  525. frameworkPaths.insert(frameworkPath);
  526. }
  527. }
  528. for (std::set<std::string>::const_iterator it = frameworkPaths.begin();
  529. it != frameworkPaths.end(); ++it) {
  530. this->MocIncludes.push_back("-F");
  531. this->MocIncludes.push_back(*it);
  532. }
  533. if (this->IncludeProjectDirsBefore) {
  534. const std::string binDir = "-I" + this->ProjectBinaryDir;
  535. const std::string srcDir = "-I" + this->ProjectSourceDir;
  536. std::list<std::string> sortedMocIncludes;
  537. std::list<std::string>::iterator it = this->MocIncludes.begin();
  538. while (it != this->MocIncludes.end()) {
  539. if (cmsys::SystemTools::StringStartsWith(*it, binDir.c_str())) {
  540. sortedMocIncludes.push_back(*it);
  541. it = this->MocIncludes.erase(it);
  542. } else {
  543. ++it;
  544. }
  545. }
  546. it = this->MocIncludes.begin();
  547. while (it != this->MocIncludes.end()) {
  548. if (cmsys::SystemTools::StringStartsWith(*it, srcDir.c_str())) {
  549. sortedMocIncludes.push_back(*it);
  550. it = this->MocIncludes.erase(it);
  551. } else {
  552. ++it;
  553. }
  554. }
  555. sortedMocIncludes.insert(sortedMocIncludes.end(),
  556. this->MocIncludes.begin(),
  557. this->MocIncludes.end());
  558. this->MocIncludes = sortedMocIncludes;
  559. }
  560. }
  561. bool cmQtAutoGenerators::RunAutogen(cmMakefile* makefile)
  562. {
  563. // the program goes through all .cpp files to see which moc files are
  564. // included. It is not really interesting how the moc file is named, but
  565. // what file the moc is created from. Once a moc is included the same moc
  566. // may not be included in the moc_compilation.cpp file anymore. OTOH if
  567. // there's a header containing Q_OBJECT where no corresponding moc file
  568. // is included anywhere a moc_<filename>.cpp file is created and included in
  569. // the moc_compilation.cpp file.
  570. // key = moc source filepath, value = moc output filepath
  571. std::map<std::string, std::string> includedMocs;
  572. std::map<std::string, std::string> notIncludedMocs;
  573. std::map<std::string, std::vector<std::string> > includedUis;
  574. // collects all headers which may need to be mocced
  575. std::set<std::string> headerFilesMoc;
  576. std::set<std::string> headerFilesUic;
  577. // Parse sources
  578. {
  579. const std::vector<std::string>& headerExtensions =
  580. makefile->GetCMakeInstance()->GetHeaderExtensions();
  581. for (std::vector<std::string>::const_iterator it = this->Sources.begin();
  582. it != this->Sources.end(); ++it) {
  583. const std::string& absFilename = *it;
  584. // Parse source file for MOC/UIC
  585. if (!this->ParseSourceFile(absFilename, headerExtensions, includedMocs,
  586. includedUis, this->MocRelaxedMode)) {
  587. return false;
  588. }
  589. // Find additional headers
  590. this->SearchHeadersForSourceFile(absFilename, headerExtensions,
  591. headerFilesMoc, headerFilesUic);
  592. }
  593. }
  594. // Parse headers
  595. for (std::vector<std::string>::const_iterator it = this->Headers.begin();
  596. it != this->Headers.end(); ++it) {
  597. const std::string& headerName = *it;
  598. if (!this->MocSkipTest(headerName)) {
  599. headerFilesMoc.insert(headerName);
  600. }
  601. if (!this->UicSkipTest(headerName)) {
  602. headerFilesUic.insert(headerName);
  603. }
  604. }
  605. this->ParseHeaders(headerFilesMoc, headerFilesUic, includedMocs,
  606. notIncludedMocs, includedUis);
  607. // Generate files
  608. if (!this->MocGenerateAll(includedMocs, notIncludedMocs)) {
  609. return false;
  610. }
  611. if (!this->UicGenerateAll(includedUis)) {
  612. return false;
  613. }
  614. if (!this->QrcGenerateAll()) {
  615. return false;
  616. }
  617. return true;
  618. }
  619. /**
  620. * @brief Tests if the C++ content requires moc processing
  621. * @return True if moc is required
  622. */
  623. bool cmQtAutoGenerators::MocRequired(const std::string& text,
  624. std::string& macroName)
  625. {
  626. // Run a simple check before an expensive regular expression check
  627. if (strstr(text.c_str(), "Q_OBJECT") != CM_NULLPTR) {
  628. if (this->RegExpQObject.find(text)) {
  629. macroName = "Q_OBJECT";
  630. return true;
  631. }
  632. }
  633. if (strstr(text.c_str(), "Q_GADGET") != CM_NULLPTR) {
  634. if (this->RegExpQGadget.find(text)) {
  635. macroName = "Q_GADGET";
  636. return true;
  637. }
  638. }
  639. return false;
  640. }
  641. /**
  642. * @brief Tests if the file should be ignored for moc scanning
  643. * @return True if the file should be ignored
  644. */
  645. bool cmQtAutoGenerators::MocSkipTest(const std::string& absFilename)
  646. {
  647. // Test if moc scanning is enabled
  648. if (!this->MocExecutable.empty()) {
  649. // Test if the file name is on the skip list
  650. if (!ListContains(this->SkipMoc, absFilename)) {
  651. return false;
  652. }
  653. }
  654. return true;
  655. }
  656. /**
  657. * @brief Tests if the file name is in the skip list
  658. */
  659. bool cmQtAutoGenerators::UicSkipTest(const std::string& absFilename)
  660. {
  661. // Test if uic scanning is enabled
  662. if (!this->UicExecutable.empty()) {
  663. // Test if the file name is on the skip list
  664. if (!ListContains(this->SkipUic, absFilename)) {
  665. return false;
  666. }
  667. }
  668. return true;
  669. }
  670. /**
  671. * @return True on success
  672. */
  673. bool cmQtAutoGenerators::ParseSourceFile(
  674. const std::string& absFilename,
  675. const std::vector<std::string>& headerExtensions,
  676. std::map<std::string, std::string>& includedMocs,
  677. std::map<std::string, std::vector<std::string> >& includedUis, bool relaxed)
  678. {
  679. bool success = true;
  680. const std::string contentsString = ReadAll(absFilename);
  681. if (contentsString.empty()) {
  682. std::ostringstream err;
  683. err << "AutoGen: Warning: " << absFilename << "\n"
  684. << "The file is empty\n";
  685. this->LogWarning(err.str());
  686. } else {
  687. // Parse source contents for MOC
  688. if (success && !this->MocSkipTest(absFilename)) {
  689. success = this->ParseContentForMoc(
  690. absFilename, contentsString, headerExtensions, includedMocs, relaxed);
  691. }
  692. // Parse source contents for UIC
  693. if (success && !this->UicSkipTest(absFilename)) {
  694. this->ParseContentForUic(absFilename, contentsString, includedUis);
  695. }
  696. }
  697. return success;
  698. }
  699. void cmQtAutoGenerators::ParseContentForUic(
  700. const std::string& absFilename, const std::string& contentsString,
  701. std::map<std::string, std::vector<std::string> >& includedUis)
  702. {
  703. // Process
  704. if (this->Verbose) {
  705. std::ostringstream err;
  706. err << "AutoUic: Checking " << absFilename << "\n";
  707. this->LogInfo(err.str());
  708. }
  709. const std::string realName = cmsys::SystemTools::GetRealPath(absFilename);
  710. const char* contentChars = contentsString.c_str();
  711. if (strstr(contentChars, "ui_") != CM_NULLPTR) {
  712. while (this->RegExpUicInclude.find(contentChars)) {
  713. const std::string currentUi = this->RegExpUicInclude.match(1);
  714. const std::string basename =
  715. cmsys::SystemTools::GetFilenameWithoutLastExtension(currentUi);
  716. // basename should be the part of the ui filename used for
  717. // finding the correct header, so we need to remove the ui_ part
  718. includedUis[realName].push_back(basename.substr(3));
  719. contentChars += this->RegExpUicInclude.end();
  720. }
  721. }
  722. }
  723. /**
  724. * @return True on success
  725. */
  726. bool cmQtAutoGenerators::ParseContentForMoc(
  727. const std::string& absFilename, const std::string& contentsString,
  728. const std::vector<std::string>& headerExtensions,
  729. std::map<std::string, std::string>& includedMocs, bool relaxed)
  730. {
  731. // Process
  732. if (this->Verbose) {
  733. std::ostringstream err;
  734. err << "AutoMoc: Checking " << absFilename << "\n";
  735. this->LogInfo(err.str());
  736. }
  737. const std::string scannedFileAbsPath =
  738. cmsys::SystemTools::GetFilenamePath(
  739. cmsys::SystemTools::GetRealPath(absFilename)) +
  740. '/';
  741. const std::string scannedFileBasename =
  742. cmsys::SystemTools::GetFilenameWithoutLastExtension(absFilename);
  743. std::string macroName;
  744. const bool requiresMoc = this->MocRequired(contentsString, macroName);
  745. bool ownDotMocIncluded = false;
  746. bool ownMocUnderscoreIncluded = false;
  747. std::string ownMocUnderscoreFile;
  748. std::string ownMocHeaderFile;
  749. // first a simple string check for "moc" is *much* faster than the regexp,
  750. // and if the string search already fails, we don't have to try the
  751. // expensive regexp
  752. const char* contentChars = contentsString.c_str();
  753. if (strstr(contentChars, "moc") != CM_NULLPTR) {
  754. // Iterate over all included moc files
  755. while (this->RegExpMocInclude.find(contentChars)) {
  756. const std::string currentMoc = this->RegExpMocInclude.match(1);
  757. // Basename of the current moc include
  758. std::string basename =
  759. cmsys::SystemTools::GetFilenameWithoutLastExtension(currentMoc);
  760. // If the moc include is of the moc_foo.cpp style we expect
  761. // the Q_OBJECT class declaration in a header file.
  762. // If the moc include is of the foo.moc style we need to look for
  763. // a Q_OBJECT macro in the current source file, if it contains the
  764. // macro we generate the moc file from the source file.
  765. if (cmHasLiteralPrefix(basename, "moc_")) {
  766. // Include: moc_FOO.cxx
  767. // basename should be the part of the moc filename used for
  768. // finding the correct header, so we need to remove the moc_ part
  769. basename = basename.substr(4);
  770. const std::string mocSubDir =
  771. ExtractSubDir(scannedFileAbsPath, currentMoc);
  772. const std::string headerToMoc = FindMatchingHeader(
  773. scannedFileAbsPath, mocSubDir, basename, headerExtensions);
  774. if (!headerToMoc.empty()) {
  775. includedMocs[headerToMoc] = currentMoc;
  776. if (relaxed && (basename == scannedFileBasename)) {
  777. ownMocUnderscoreIncluded = true;
  778. ownMocUnderscoreFile = currentMoc;
  779. ownMocHeaderFile = headerToMoc;
  780. }
  781. } else {
  782. std::ostringstream err;
  783. err << "AutoMoc: Error: " << absFilename << "\n"
  784. << "The file includes the moc file \"" << currentMoc
  785. << "\", but could not find header \"" << basename << '{'
  786. << JoinExts(headerExtensions) << "}\" ";
  787. if (mocSubDir.empty()) {
  788. err << "in " << scannedFileAbsPath << "\n";
  789. } else {
  790. err << "neither in " << scannedFileAbsPath << " nor in "
  791. << mocSubDir << "\n";
  792. }
  793. this->LogError(err.str());
  794. return false;
  795. }
  796. } else {
  797. // Include: FOO.moc
  798. std::string fileToMoc;
  799. if (relaxed) {
  800. // Mode: Relaxed
  801. if (!requiresMoc || basename != scannedFileBasename) {
  802. const std::string mocSubDir =
  803. ExtractSubDir(scannedFileAbsPath, currentMoc);
  804. const std::string headerToMoc = FindMatchingHeader(
  805. scannedFileAbsPath, mocSubDir, basename, headerExtensions);
  806. if (!headerToMoc.empty()) {
  807. // This is for KDE4 compatibility:
  808. fileToMoc = headerToMoc;
  809. if (!requiresMoc && basename == scannedFileBasename) {
  810. std::ostringstream err;
  811. err << "AutoMoc: Warning: " << absFilename << "\n"
  812. << "The file includes the moc file \"" << currentMoc
  813. << "\", but does not contain a " << macroName
  814. << " macro. Running moc on "
  815. << "\"" << headerToMoc << "\" ! Include \"moc_" << basename
  816. << ".cpp\" for a compatibility with "
  817. "strict mode (see CMAKE_AUTOMOC_RELAXED_MODE).\n";
  818. this->LogWarning(err.str());
  819. } else {
  820. std::ostringstream err;
  821. err << "AutoMoc: Warning: " << absFilename << "\n"
  822. << "The file includes the moc file \"" << currentMoc
  823. << "\" instead of \"moc_" << basename
  824. << ".cpp\". Running moc on "
  825. << "\"" << headerToMoc << "\" ! Include \"moc_" << basename
  826. << ".cpp\" for compatibility with "
  827. "strict mode (see CMAKE_AUTOMOC_RELAXED_MODE).\n";
  828. this->LogWarning(err.str());
  829. }
  830. } else {
  831. std::ostringstream err;
  832. err << "AutoMoc: Error: " << absFilename << "\n"
  833. << "The file includes the moc file \"" << currentMoc
  834. << "\", which seems to be the moc file from a different "
  835. "source file. CMake also could not find a matching "
  836. "header.\n";
  837. this->LogError(err.str());
  838. return false;
  839. }
  840. } else {
  841. // Include self
  842. fileToMoc = absFilename;
  843. ownDotMocIncluded = true;
  844. }
  845. } else {
  846. // Mode: Strict
  847. if (basename == scannedFileBasename) {
  848. // Include self
  849. fileToMoc = absFilename;
  850. ownDotMocIncluded = true;
  851. } else {
  852. // Don't allow FOO.moc include other than self in strict mode
  853. std::ostringstream err;
  854. err << "AutoMoc: Error: " << absFilename << "\n"
  855. << "The file includes the moc file \"" << currentMoc
  856. << "\", which seems to be the moc file from a different "
  857. "source file. This is not supported. Include \""
  858. << scannedFileBasename
  859. << ".moc\" to run moc on this source file.\n";
  860. this->LogError(err.str());
  861. return false;
  862. }
  863. }
  864. if (!fileToMoc.empty()) {
  865. includedMocs[fileToMoc] = currentMoc;
  866. }
  867. }
  868. // Forward content pointer
  869. contentChars += this->RegExpMocInclude.end();
  870. }
  871. }
  872. // In this case, check whether the scanned file itself contains a Q_OBJECT.
  873. // If this is the case, the moc_foo.cpp should probably be generated from
  874. // foo.cpp instead of foo.h, because otherwise it won't build.
  875. // But warn, since this is not how it is supposed to be used.
  876. if (requiresMoc && !ownDotMocIncluded) {
  877. if (relaxed && ownMocUnderscoreIncluded) {
  878. // This is for KDE4 compatibility:
  879. std::ostringstream err;
  880. err << "AutoMoc: Warning: " << absFilename << "\n"
  881. << "The file contains a " << macroName
  882. << " macro, but does not include "
  883. << "\"" << scannedFileBasename << ".moc\", but instead includes "
  884. << "\"" << ownMocUnderscoreFile << "\". Running moc on "
  885. << "\"" << absFilename << "\" ! Better include \""
  886. << scannedFileBasename
  887. << ".moc\" for compatibility with "
  888. "strict mode (see CMAKE_AUTOMOC_RELAXED_MODE).\n";
  889. this->LogWarning(err.str());
  890. // Use scanned source file instead of scanned header file as moc source
  891. includedMocs[absFilename] = ownMocUnderscoreFile;
  892. includedMocs.erase(ownMocHeaderFile);
  893. } else {
  894. // Otherwise always error out since it will not compile:
  895. std::ostringstream err;
  896. err << "AutoMoc: Error: " << absFilename << "\n"
  897. << "The file contains a " << macroName
  898. << " macro, but does not include "
  899. << "\"" << scannedFileBasename << ".moc\" !\n";
  900. this->LogError(err.str());
  901. return false;
  902. }
  903. }
  904. return true;
  905. }
  906. void cmQtAutoGenerators::SearchHeadersForSourceFile(
  907. const std::string& absFilename,
  908. const std::vector<std::string>& headerExtensions,
  909. std::set<std::string>& absHeadersMoc, std::set<std::string>& absHeadersUic)
  910. {
  911. // search for header files and private header files we may need to moc:
  912. std::string basepath = cmsys::SystemTools::GetFilenamePath(
  913. cmsys::SystemTools::GetRealPath(absFilename));
  914. basepath += '/';
  915. basepath += cmsys::SystemTools::GetFilenameWithoutLastExtension(absFilename);
  916. // Search for regular header
  917. for (std::vector<std::string>::const_iterator ext = headerExtensions.begin();
  918. ext != headerExtensions.end(); ++ext) {
  919. const std::string headerName = basepath + "." + (*ext);
  920. if (cmsys::SystemTools::FileExists(headerName.c_str())) {
  921. // Moc headers
  922. if (!this->MocSkipTest(absFilename) && !this->MocSkipTest(headerName)) {
  923. absHeadersMoc.insert(headerName);
  924. }
  925. // Uic headers
  926. if (!this->UicSkipTest(absFilename) && !this->UicSkipTest(headerName)) {
  927. absHeadersUic.insert(headerName);
  928. }
  929. break;
  930. }
  931. }
  932. // Search for private header
  933. for (std::vector<std::string>::const_iterator ext = headerExtensions.begin();
  934. ext != headerExtensions.end(); ++ext) {
  935. const std::string headerName = basepath + "_p." + (*ext);
  936. if (cmsys::SystemTools::FileExists(headerName.c_str())) {
  937. // Moc headers
  938. if (!this->MocSkipTest(absFilename) && !this->MocSkipTest(headerName)) {
  939. absHeadersMoc.insert(headerName);
  940. }
  941. // Uic headers
  942. if (!this->UicSkipTest(absFilename) && !this->UicSkipTest(headerName)) {
  943. absHeadersUic.insert(headerName);
  944. }
  945. break;
  946. }
  947. }
  948. }
  949. void cmQtAutoGenerators::ParseHeaders(
  950. const std::set<std::string>& absHeadersMoc,
  951. const std::set<std::string>& absHeadersUic,
  952. const std::map<std::string, std::string>& includedMocs,
  953. std::map<std::string, std::string>& notIncludedMocs,
  954. std::map<std::string, std::vector<std::string> >& includedUis)
  955. {
  956. // Merged header files list to read files only once
  957. std::set<std::string> headerFiles;
  958. headerFiles.insert(absHeadersMoc.begin(), absHeadersMoc.end());
  959. headerFiles.insert(absHeadersUic.begin(), absHeadersUic.end());
  960. for (std::set<std::string>::const_iterator hIt = headerFiles.begin();
  961. hIt != headerFiles.end(); ++hIt) {
  962. const std::string& headerName = *hIt;
  963. const std::string contents = ReadAll(headerName);
  964. // Parse header content for MOC
  965. if ((absHeadersMoc.find(headerName) != absHeadersMoc.end()) &&
  966. (includedMocs.find(headerName) == includedMocs.end())) {
  967. // Process
  968. if (this->Verbose) {
  969. std::ostringstream err;
  970. err << "AutoMoc: Checking " << headerName << "\n";
  971. this->LogInfo(err.str());
  972. }
  973. std::string macroName;
  974. if (this->MocRequired(contents, macroName)) {
  975. notIncludedMocs[headerName] = fpathCheckSum.getPart(headerName) +
  976. "/moc_" +
  977. cmsys::SystemTools::GetFilenameWithoutLastExtension(headerName) +
  978. ".cpp";
  979. }
  980. }
  981. // Parse header content for UIC
  982. if (absHeadersUic.find(headerName) != absHeadersUic.end()) {
  983. this->ParseContentForUic(headerName, contents, includedUis);
  984. }
  985. }
  986. }
  987. bool cmQtAutoGenerators::MocGenerateAll(
  988. const std::map<std::string, std::string>& includedMocs,
  989. const std::map<std::string, std::string>& notIncludedMocs)
  990. {
  991. if (this->MocExecutable.empty()) {
  992. return true;
  993. }
  994. // look for name collisions
  995. {
  996. std::multimap<std::string, std::string> collisions;
  997. // Test merged map of included and notIncluded
  998. std::map<std::string, std::string> mergedMocs(includedMocs);
  999. mergedMocs.insert(notIncludedMocs.begin(), notIncludedMocs.end());
  1000. if (this->NameCollisionTest(mergedMocs, collisions)) {
  1001. std::ostringstream err;
  1002. err << "AutoMoc: Error: "
  1003. "The same moc file will be generated "
  1004. "from different sources."
  1005. << std::endl
  1006. << "To avoid this error either" << std::endl
  1007. << "- rename the source files or" << std::endl
  1008. << "- do not include the (moc_NAME.cpp|NAME.moc) file" << std::endl;
  1009. this->LogErrorNameCollision(err.str(), collisions);
  1010. return false;
  1011. }
  1012. }
  1013. // generate moc files that are included by source files.
  1014. {
  1015. const std::string subDirPrefix = "include/";
  1016. for (std::map<std::string, std::string>::const_iterator it =
  1017. includedMocs.begin();
  1018. it != includedMocs.end(); ++it) {
  1019. if (!this->MocGenerateFile(it->first, it->second, subDirPrefix)) {
  1020. if (this->RunMocFailed) {
  1021. return false;
  1022. }
  1023. }
  1024. }
  1025. }
  1026. // generate moc files that are _not_ included by source files.
  1027. bool automocCppChanged = false;
  1028. {
  1029. const std::string subDirPrefix;
  1030. for (std::map<std::string, std::string>::const_iterator it =
  1031. notIncludedMocs.begin();
  1032. it != notIncludedMocs.end(); ++it) {
  1033. if (this->MocGenerateFile(it->first, it->second, subDirPrefix)) {
  1034. automocCppChanged = true;
  1035. } else {
  1036. if (this->RunMocFailed) {
  1037. return false;
  1038. }
  1039. }
  1040. }
  1041. }
  1042. // Compose moc_compilation.cpp content
  1043. std::string automocSource;
  1044. {
  1045. std::ostringstream outStream;
  1046. outStream << "/* This file is autogenerated, do not edit*/\n";
  1047. if (notIncludedMocs.empty()) {
  1048. // Dummy content
  1049. outStream << "enum some_compilers { need_more_than_nothing };\n";
  1050. } else {
  1051. // Valid content
  1052. for (std::map<std::string, std::string>::const_iterator it =
  1053. notIncludedMocs.begin();
  1054. it != notIncludedMocs.end(); ++it) {
  1055. outStream << "#include \"" << it->second << "\"\n";
  1056. }
  1057. }
  1058. outStream.flush();
  1059. automocSource = outStream.str();
  1060. }
  1061. // Check if we even need to update moc_compilation.cpp
  1062. if (!automocCppChanged) {
  1063. // compare contents of the moc_compilation.cpp file
  1064. const std::string oldContents = ReadAll(this->OutMocCppFilenameAbs);
  1065. if (oldContents == automocSource) {
  1066. // nothing changed: don't touch the moc_compilation.cpp file
  1067. if (this->Verbose) {
  1068. std::ostringstream err;
  1069. err << "AutoMoc: " << this->OutMocCppFilenameRel << " still up to date"
  1070. << std::endl;
  1071. this->LogInfo(err.str());
  1072. }
  1073. return true;
  1074. }
  1075. }
  1076. // Actually write moc_compilation.cpp
  1077. {
  1078. std::string msg = "Generating MOC compilation ";
  1079. msg += this->OutMocCppFilenameRel;
  1080. this->LogBold(msg);
  1081. }
  1082. // Make sure the parent directory exists
  1083. bool success = this->MakeParentDirectory(this->OutMocCppFilenameAbs);
  1084. if (success) {
  1085. cmsys::ofstream outfile;
  1086. outfile.open(this->OutMocCppFilenameAbs.c_str(), std::ios::trunc);
  1087. if (!outfile) {
  1088. success = false;
  1089. std::ostringstream err;
  1090. err << "AutoMoc: error opening " << this->OutMocCppFilenameAbs << "\n";
  1091. this->LogError(err.str());
  1092. } else {
  1093. outfile << automocSource;
  1094. // Check for write errors
  1095. if (!outfile.good()) {
  1096. success = false;
  1097. std::ostringstream err;
  1098. err << "AutoMoc: error writing " << this->OutMocCppFilenameAbs << "\n";
  1099. this->LogError(err.str());
  1100. }
  1101. }
  1102. }
  1103. return success;
  1104. }
  1105. /**
  1106. * @return True if a moc file was created. False may indicate an error.
  1107. */
  1108. bool cmQtAutoGenerators::MocGenerateFile(const std::string& sourceFile,
  1109. const std::string& mocFileName,
  1110. const std::string& subDirPrefix)
  1111. {
  1112. const std::string mocFileRel =
  1113. this->AutogenBuildSubDir + subDirPrefix + mocFileName;
  1114. const std::string mocFileAbs = this->CurrentBinaryDir + mocFileRel;
  1115. bool generateMoc = this->GenerateMocAll;
  1116. // Test if the source file is newer that the build file
  1117. if (!generateMoc) {
  1118. generateMoc = FileAbsentOrOlder(mocFileAbs, sourceFile);
  1119. }
  1120. if (generateMoc) {
  1121. // Log
  1122. this->LogBold("Generating MOC source " + mocFileRel);
  1123. // Make sure the parent directory exists
  1124. if (!this->MakeParentDirectory(mocFileAbs)) {
  1125. this->RunMocFailed = true;
  1126. return false;
  1127. }
  1128. std::vector<std::string> command;
  1129. command.push_back(this->MocExecutable);
  1130. command.insert(command.end(), this->MocIncludes.begin(),
  1131. this->MocIncludes.end());
  1132. command.insert(command.end(), this->MocDefinitions.begin(),
  1133. this->MocDefinitions.end());
  1134. command.insert(command.end(), this->MocOptions.begin(),
  1135. this->MocOptions.end());
  1136. #ifdef _WIN32
  1137. command.push_back("-DWIN32");
  1138. #endif
  1139. command.push_back("-o");
  1140. command.push_back(mocFileAbs);
  1141. command.push_back(sourceFile);
  1142. if (this->Verbose) {
  1143. this->LogCommand(command);
  1144. }
  1145. std::string output;
  1146. int retVal = 0;
  1147. bool result =
  1148. cmSystemTools::RunSingleCommand(command, &output, &output, &retVal);
  1149. if (!result || retVal) {
  1150. {
  1151. std::ostringstream err;
  1152. err << "AutoMoc: Error: moc process for " << mocFileRel << " failed:\n"
  1153. << output << std::endl;
  1154. this->LogError(err.str());
  1155. }
  1156. cmSystemTools::RemoveFile(mocFileAbs);
  1157. this->RunMocFailed = true;
  1158. return false;
  1159. }
  1160. return true;
  1161. }
  1162. return false;
  1163. }
  1164. bool cmQtAutoGenerators::UicGenerateAll(
  1165. const std::map<std::string, std::vector<std::string> >& includedUis)
  1166. {
  1167. if (this->UicExecutable.empty()) {
  1168. return true;
  1169. }
  1170. // single map with input / output names
  1171. std::map<std::string, std::map<std::string, std::string> > uiGenMap;
  1172. std::map<std::string, std::string> testMap;
  1173. for (std::map<std::string, std::vector<std::string> >::const_iterator it =
  1174. includedUis.begin();
  1175. it != includedUis.end(); ++it) {
  1176. // source file path
  1177. std::string sourcePath = cmsys::SystemTools::GetFilenamePath(it->first);
  1178. sourcePath += '/';
  1179. // insert new map for source file an use new reference
  1180. uiGenMap[it->first] = std::map<std::string, std::string>();
  1181. std::map<std::string, std::string>& sourceMap = uiGenMap[it->first];
  1182. for (std::vector<std::string>::const_iterator sit = it->second.begin();
  1183. sit != it->second.end(); ++sit) {
  1184. const std::string& uiFileName = *sit;
  1185. const std::string uiInputFile = sourcePath + uiFileName + ".ui";
  1186. const std::string uiOutputFile = "ui_" + uiFileName + ".h";
  1187. sourceMap[uiInputFile] = uiOutputFile;
  1188. testMap[uiInputFile] = uiOutputFile;
  1189. }
  1190. }
  1191. // look for name collisions
  1192. {
  1193. std::multimap<std::string, std::string> collisions;
  1194. if (this->NameCollisionTest(testMap, collisions)) {
  1195. std::ostringstream err;
  1196. err << "AutoUic: Error: The same ui_NAME.h file will be generated "
  1197. "from different sources."
  1198. << std::endl
  1199. << "To avoid this error rename the source files." << std::endl;
  1200. this->LogErrorNameCollision(err.str(), collisions);
  1201. return false;
  1202. }
  1203. }
  1204. testMap.clear();
  1205. // generate ui files
  1206. for (std::map<std::string,
  1207. std::map<std::string, std::string> >::const_iterator it =
  1208. uiGenMap.begin();
  1209. it != uiGenMap.end(); ++it) {
  1210. for (std::map<std::string, std::string>::const_iterator sit =
  1211. it->second.begin();
  1212. sit != it->second.end(); ++sit) {
  1213. if (!this->UicGenerateFile(it->first, sit->first, sit->second)) {
  1214. if (this->RunUicFailed) {
  1215. return false;
  1216. }
  1217. }
  1218. }
  1219. }
  1220. return true;
  1221. }
  1222. /**
  1223. * @return True if a uic file was created. False may indicate an error.
  1224. */
  1225. bool cmQtAutoGenerators::UicGenerateFile(const std::string& realName,
  1226. const std::string& uiInputFile,
  1227. const std::string& uiOutputFile)
  1228. {
  1229. const std::string uicFileRel =
  1230. this->AutogenBuildSubDir + "include/" + uiOutputFile;
  1231. const std::string uicFileAbs = this->CurrentBinaryDir + uicFileRel;
  1232. bool generateUic = this->GenerateUicAll;
  1233. // Test if the source file is newer that the build file
  1234. if (!generateUic) {
  1235. generateUic = FileAbsentOrOlder(uicFileAbs, uiInputFile);
  1236. }
  1237. if (generateUic) {
  1238. // Log
  1239. this->LogBold("Generating UIC header " + uicFileRel);
  1240. // Make sure the parent directory exists
  1241. if (!this->MakeParentDirectory(uicFileAbs)) {
  1242. this->RunUicFailed = true;
  1243. return false;
  1244. }
  1245. std::vector<std::string> command;
  1246. command.push_back(this->UicExecutable);
  1247. std::vector<std::string> opts = this->UicTargetOptions;
  1248. std::map<std::string, std::string>::const_iterator optionIt =
  1249. this->UicOptions.find(uiInputFile);
  1250. if (optionIt != this->UicOptions.end()) {
  1251. std::vector<std::string> fileOpts;
  1252. cmSystemTools::ExpandListArgument(optionIt->second, fileOpts);
  1253. UicMergeOptions(opts, fileOpts, this->QtMajorVersion == "5");
  1254. }
  1255. command.insert(command.end(), opts.begin(), opts.end());
  1256. command.push_back("-o");
  1257. command.push_back(uicFileAbs);
  1258. command.push_back(uiInputFile);
  1259. if (this->Verbose) {
  1260. this->LogCommand(command);
  1261. }
  1262. std::string output;
  1263. int retVal = 0;
  1264. bool result =
  1265. cmSystemTools::RunSingleCommand(command, &output, &output, &retVal);
  1266. if (!result || retVal) {
  1267. {
  1268. std::ostringstream err;
  1269. err << "AutoUic: Error: uic process for " << uicFileRel
  1270. << " needed by\n \"" << realName << "\"\nfailed:\n"
  1271. << output << std::endl;
  1272. this->LogError(err.str());
  1273. }
  1274. cmSystemTools::RemoveFile(uicFileAbs);
  1275. this->RunUicFailed = true;
  1276. return false;
  1277. }
  1278. return true;
  1279. }
  1280. return false;
  1281. }
  1282. bool cmQtAutoGenerators::QrcGenerateAll()
  1283. {
  1284. if (this->RccExecutable.empty()) {
  1285. return true;
  1286. }
  1287. // generate single map with input / output names
  1288. std::map<std::string, std::string> qrcGenMap;
  1289. for (std::vector<std::string>::const_iterator si = this->RccSources.begin();
  1290. si != this->RccSources.end(); ++si) {
  1291. const std::string ext = cmsys::SystemTools::GetFilenameLastExtension(*si);
  1292. if (ext == ".qrc") {
  1293. qrcGenMap[*si] = this->AutogenBuildSubDir + fpathCheckSum.getPart(*si) +
  1294. "/qrc_" + cmsys::SystemTools::GetFilenameWithoutLastExtension(*si) +
  1295. ".cpp";
  1296. }
  1297. }
  1298. // look for name collisions
  1299. {
  1300. std::multimap<std::string, std::string> collisions;
  1301. if (this->NameCollisionTest(qrcGenMap, collisions)) {
  1302. std::ostringstream err;
  1303. err << "AutoRcc: Error: The same qrc_NAME.cpp file"
  1304. " will be generated from different sources."
  1305. << std::endl
  1306. << "To avoid this error rename the source .qrc files." << std::endl;
  1307. this->LogErrorNameCollision(err.str(), collisions);
  1308. return false;
  1309. }
  1310. }
  1311. // generate qrc files
  1312. for (std::map<std::string, std::string>::const_iterator si =
  1313. qrcGenMap.begin();
  1314. si != qrcGenMap.end(); ++si) {
  1315. bool unique = FileNameIsUnique(si->first, qrcGenMap);
  1316. if (!this->QrcGenerateFile(si->first, si->second, unique)) {
  1317. if (this->RunRccFailed) {
  1318. return false;
  1319. }
  1320. }
  1321. }
  1322. return true;
  1323. }
  1324. /**
  1325. * @return True if a rcc file was created. False may indicate an error.
  1326. */
  1327. bool cmQtAutoGenerators::QrcGenerateFile(const std::string& qrcInputFile,
  1328. const std::string& qrcOutputFile,
  1329. bool unique_n)
  1330. {
  1331. std::string symbolName =
  1332. cmsys::SystemTools::GetFilenameWithoutLastExtension(qrcInputFile);
  1333. if (!unique_n) {
  1334. symbolName += "_";
  1335. symbolName += fpathCheckSum.getPart(qrcInputFile);
  1336. }
  1337. // Replace '-' with '_'. The former is valid for
  1338. // file names but not for symbol names.
  1339. std::replace(symbolName.begin(), symbolName.end(), '-', '_');
  1340. const std::string qrcBuildFile = this->CurrentBinaryDir + qrcOutputFile;
  1341. bool generateQrc = this->GenerateRccAll;
  1342. // Test if the resources list file is newer than build file
  1343. if (!generateQrc) {
  1344. generateQrc = FileAbsentOrOlder(qrcBuildFile, qrcInputFile);
  1345. }
  1346. // Test if any resource file is newer than the build file
  1347. if (!generateQrc) {
  1348. const std::vector<std::string>& files = this->RccInputs[qrcInputFile];
  1349. for (std::vector<std::string>::const_iterator it = files.begin();
  1350. it != files.end(); ++it) {
  1351. if (FileAbsentOrOlder(qrcBuildFile, *it)) {
  1352. generateQrc = true;
  1353. break;
  1354. }
  1355. }
  1356. }
  1357. if (generateQrc) {
  1358. {
  1359. std::string msg = "Generating RCC source ";
  1360. msg += qrcOutputFile;
  1361. this->LogBold(msg);
  1362. }
  1363. // Make sure the parent directory exists
  1364. if (!this->MakeParentDirectory(qrcOutputFile)) {
  1365. this->RunRccFailed = true;
  1366. return false;
  1367. }
  1368. std::vector<std::string> command;
  1369. command.push_back(this->RccExecutable);
  1370. {
  1371. std::map<std::string, std::string>::const_iterator optionIt =
  1372. this->RccOptions.find(qrcInputFile);
  1373. if (optionIt != this->RccOptions.end()) {
  1374. cmSystemTools::ExpandListArgument(optionIt->second, command);
  1375. }
  1376. }
  1377. command.push_back("-name");
  1378. command.push_back(symbolName);
  1379. command.push_back("-o");
  1380. command.push_back(qrcBuildFile);
  1381. command.push_back(qrcInputFile);
  1382. if (this->Verbose) {
  1383. this->LogCommand(command);
  1384. }
  1385. std::string output;
  1386. int retVal = 0;
  1387. bool result =
  1388. cmSystemTools::RunSingleCommand(command, &output, &output, &retVal);
  1389. if (!result || retVal) {
  1390. {
  1391. std::ostringstream err;
  1392. err << "AutoRcc: Error: rcc process for " << qrcOutputFile
  1393. << " failed:\n"
  1394. << output << std::endl;
  1395. this->LogError(err.str());
  1396. }
  1397. cmSystemTools::RemoveFile(qrcBuildFile);
  1398. this->RunRccFailed = true;
  1399. return false;
  1400. }
  1401. return true;
  1402. }
  1403. return false;
  1404. }
  1405. void cmQtAutoGenerators::LogErrorNameCollision(
  1406. const std::string& message,
  1407. const std::multimap<std::string, std::string>& collisions)
  1408. {
  1409. typedef std::multimap<std::string, std::string>::const_iterator Iter;
  1410. std::ostringstream err;
  1411. // Add message
  1412. err << message;
  1413. // Append collision list
  1414. for (Iter it = collisions.begin(); it != collisions.end(); ++it) {
  1415. err << it->first << " : " << it->second << std::endl;
  1416. }
  1417. this->LogError(err.str());
  1418. }
  1419. void cmQtAutoGenerators::LogBold(const std::string& message)
  1420. {
  1421. cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundBlue |
  1422. cmsysTerminal_Color_ForegroundBold,
  1423. message.c_str(), true, this->ColorOutput);
  1424. }
  1425. void cmQtAutoGenerators::LogInfo(const std::string& message)
  1426. {
  1427. std::cout << message.c_str();
  1428. }
  1429. void cmQtAutoGenerators::LogWarning(const std::string& message)
  1430. {
  1431. std::ostringstream ostr;
  1432. ostr << message << "\n";
  1433. std::cout << message.c_str();
  1434. }
  1435. void cmQtAutoGenerators::LogError(const std::string& message)
  1436. {
  1437. std::ostringstream ostr;
  1438. ostr << message << "\n\n";
  1439. std::cerr << ostr.str();
  1440. }
  1441. void cmQtAutoGenerators::LogCommand(const std::vector<std::string>& command)
  1442. {
  1443. std::ostringstream sbuf;
  1444. for (std::vector<std::string>::const_iterator cmdIt = command.begin();
  1445. cmdIt != command.end(); ++cmdIt) {
  1446. if (cmdIt != command.begin()) {
  1447. sbuf << " ";
  1448. }
  1449. sbuf << *cmdIt;
  1450. }
  1451. if (!sbuf.str().empty()) {
  1452. sbuf << std::endl;
  1453. this->LogInfo(sbuf.str());
  1454. }
  1455. }
  1456. /**
  1457. * @brief Collects name collisions as output/input pairs
  1458. * @return True if there were collisions
  1459. */
  1460. bool cmQtAutoGenerators::NameCollisionTest(
  1461. const std::map<std::string, std::string>& genFiles,
  1462. std::multimap<std::string, std::string>& collisions)
  1463. {
  1464. typedef std::map<std::string, std::string>::const_iterator Iter;
  1465. typedef std::map<std::string, std::string>::value_type VType;
  1466. for (Iter ait = genFiles.begin(); ait != genFiles.end(); ++ait) {
  1467. bool first_match(true);
  1468. for (Iter bit = (++Iter(ait)); bit != genFiles.end(); ++bit) {
  1469. if (ait->second == bit->second) {
  1470. if (first_match) {
  1471. if (collisions.find(ait->second) != collisions.end()) {
  1472. // We already know of this collision from before
  1473. break;
  1474. }
  1475. collisions.insert(VType(ait->second, ait->first));
  1476. first_match = false;
  1477. }
  1478. collisions.insert(VType(bit->second, bit->first));
  1479. }
  1480. }
  1481. }
  1482. return !collisions.empty();
  1483. }
  1484. /**
  1485. * @brief Generates the parent directory of the given file on demand
  1486. * @return True on success
  1487. */
  1488. bool cmQtAutoGenerators::MakeParentDirectory(const std::string& filename)
  1489. {
  1490. bool success = true;
  1491. const std::string dirName = cmSystemTools::GetFilenamePath(filename);
  1492. if (!dirName.empty()) {
  1493. success = cmsys::SystemTools::MakeDirectory(dirName);
  1494. if (!success) {
  1495. std::ostringstream err;
  1496. err << "AutoGen: Directory creation failed: " << dirName << std::endl;
  1497. this->LogError(err.str());
  1498. }
  1499. }
  1500. return success;
  1501. }