cmQtAutoGenerators.cxx 54 KB

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