cmQtAutoGenerators.cxx 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644
  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();
  224. if (this->QtMajorVersion == "4" || this->QtMajorVersion == "5") {
  225. if (!this->RunAutogen(mf.get())) {
  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()
  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. // Compose moc includes list
  461. std::list<std::string> mocIncludes;
  462. {
  463. std::set<std::string> frameworkPaths;
  464. {
  465. std::vector<std::string> incPaths;
  466. cmSystemTools::ExpandListArgument(this->MocInfoIncludes, incPaths);
  467. for (std::vector<std::string>::const_iterator it = incPaths.begin();
  468. it != incPaths.end(); ++it) {
  469. const std::string& path = *it;
  470. mocIncludes.push_back("-I" + path);
  471. // Extract framework path
  472. if (cmHasLiteralSuffix(path, ".framework/Headers")) {
  473. // Go up twice to get to the framework root
  474. std::vector<std::string> pathComponents;
  475. cmsys::SystemTools::SplitPath(path, pathComponents);
  476. std::string frameworkPath = cmsys::SystemTools::JoinPath(
  477. pathComponents.begin(), pathComponents.end() - 2);
  478. frameworkPaths.insert(frameworkPath);
  479. }
  480. }
  481. }
  482. // Append framework includes
  483. for (std::set<std::string>::const_iterator it = frameworkPaths.begin();
  484. it != frameworkPaths.end(); ++it) {
  485. mocIncludes.push_back("-F");
  486. mocIncludes.push_back(*it);
  487. }
  488. }
  489. if (this->IncludeProjectDirsBefore) {
  490. // Extract project includes
  491. std::vector<std::string> mocSortedIncludes;
  492. {
  493. std::vector<std::string> movePaths;
  494. movePaths.push_back("-I" + this->ProjectBinaryDir);
  495. movePaths.push_back("-I" + this->ProjectSourceDir);
  496. for (std::vector<std::string>::const_iterator mpit = movePaths.begin();
  497. mpit != movePaths.end(); ++mpit) {
  498. std::list<std::string>::iterator it = mocIncludes.begin();
  499. while (it != mocIncludes.end()) {
  500. const std::string& path = *it;
  501. if (cmsys::SystemTools::StringStartsWith(path, mpit->c_str())) {
  502. mocSortedIncludes.push_back(path);
  503. it = mocIncludes.erase(it);
  504. } else {
  505. ++it;
  506. }
  507. }
  508. }
  509. }
  510. // Place extracted includes at the begin
  511. this->MocIncludes.insert(this->MocIncludes.end(),
  512. mocSortedIncludes.begin(),
  513. mocSortedIncludes.end());
  514. }
  515. // Append remaining includes
  516. this->MocIncludes.insert(this->MocIncludes.end(), mocIncludes.begin(),
  517. mocIncludes.end());
  518. }
  519. bool cmQtAutoGenerators::RunAutogen(cmMakefile* makefile)
  520. {
  521. // the program goes through all .cpp files to see which moc files are
  522. // included. It is not really interesting how the moc file is named, but
  523. // what file the moc is created from. Once a moc is included the same moc
  524. // may not be included in the moc_compilation.cpp file anymore. OTOH if
  525. // there's a header containing Q_OBJECT where no corresponding moc file
  526. // is included anywhere a moc_<filename>.cpp file is created and included
  527. // in the moc_compilation.cpp file.
  528. // key = moc source filepath, value = moc output filepath
  529. std::map<std::string, std::string> mocsIncluded;
  530. std::map<std::string, std::string> mocsNotIncluded;
  531. std::map<std::string, std::vector<std::string> > uisIncluded;
  532. // collects all headers which may need to be mocced
  533. std::set<std::string> mocHeaderFiles;
  534. std::set<std::string> uicHeaderFiles;
  535. // Parse sources
  536. {
  537. const std::vector<std::string>& headerExtensions =
  538. makefile->GetCMakeInstance()->GetHeaderExtensions();
  539. for (std::vector<std::string>::const_iterator it = this->Sources.begin();
  540. it != this->Sources.end(); ++it) {
  541. const std::string& absFilename = *it;
  542. // Parse source file for MOC/UIC
  543. if (!this->ParseSourceFile(absFilename, headerExtensions, mocsIncluded,
  544. uisIncluded, this->MocRelaxedMode)) {
  545. return false;
  546. }
  547. // Find additional headers
  548. this->SearchHeadersForSourceFile(absFilename, headerExtensions,
  549. mocHeaderFiles, uicHeaderFiles);
  550. }
  551. }
  552. // Parse headers
  553. for (std::vector<std::string>::const_iterator it = this->Headers.begin();
  554. it != this->Headers.end(); ++it) {
  555. const std::string& headerName = *it;
  556. if (!this->MocSkip(headerName)) {
  557. mocHeaderFiles.insert(headerName);
  558. }
  559. if (!this->UicSkip(headerName)) {
  560. uicHeaderFiles.insert(headerName);
  561. }
  562. }
  563. this->ParseHeaders(mocHeaderFiles, uicHeaderFiles, mocsIncluded,
  564. mocsNotIncluded, uisIncluded);
  565. // Generate files
  566. if (!this->MocGenerateAll(mocsIncluded, mocsNotIncluded)) {
  567. return false;
  568. }
  569. if (!this->UicGenerateAll(uisIncluded)) {
  570. return false;
  571. }
  572. if (!this->RccGenerateAll()) {
  573. return false;
  574. }
  575. return true;
  576. }
  577. /**
  578. * @brief Tests if the C++ content requires moc processing
  579. * @return True if moc is required
  580. */
  581. bool cmQtAutoGenerators::MocRequired(const std::string& text,
  582. std::string& macroName)
  583. {
  584. // Run a simple check before an expensive regular expression check
  585. if (strstr(text.c_str(), "Q_OBJECT") != CM_NULLPTR) {
  586. if (this->RegExpQObject.find(text)) {
  587. macroName = "Q_OBJECT";
  588. return true;
  589. }
  590. }
  591. if (strstr(text.c_str(), "Q_GADGET") != CM_NULLPTR) {
  592. if (this->RegExpQGadget.find(text)) {
  593. macroName = "Q_GADGET";
  594. return true;
  595. }
  596. }
  597. return false;
  598. }
  599. /**
  600. * @brief Tests if the file should be ignored for moc scanning
  601. * @return True if the file should be ignored
  602. */
  603. bool cmQtAutoGenerators::MocSkip(const std::string& absFilename)
  604. {
  605. if (this->MocEnabled()) {
  606. // Test if the file name is on the skip list
  607. if (!ListContains(this->MocSkipList, absFilename)) {
  608. return false;
  609. }
  610. }
  611. return true;
  612. }
  613. /**
  614. * @brief Tests if the file name is in the skip list
  615. */
  616. bool cmQtAutoGenerators::UicSkip(const std::string& absFilename)
  617. {
  618. if (this->UicEnabled()) {
  619. // Test if the file name is on the skip list
  620. if (!ListContains(this->UicSkipList, absFilename)) {
  621. return false;
  622. }
  623. }
  624. return true;
  625. }
  626. /**
  627. * @return True on success
  628. */
  629. bool cmQtAutoGenerators::ParseSourceFile(
  630. const std::string& absFilename,
  631. const std::vector<std::string>& headerExtensions,
  632. std::map<std::string, std::string>& mocsIncluded,
  633. std::map<std::string, std::vector<std::string> >& uisIncluded, bool relaxed)
  634. {
  635. bool success = true;
  636. const std::string contentsString = ReadAll(absFilename);
  637. if (contentsString.empty()) {
  638. std::ostringstream err;
  639. err << "AutoGen: Warning: " << absFilename << "\n"
  640. << "The file is empty\n";
  641. this->LogWarning(err.str());
  642. } else {
  643. // Parse source contents for MOC
  644. if (success && !this->MocSkip(absFilename)) {
  645. success = this->ParseContentForMoc(
  646. absFilename, contentsString, headerExtensions, mocsIncluded, relaxed);
  647. }
  648. // Parse source contents for UIC
  649. if (success && !this->UicSkip(absFilename)) {
  650. this->ParseContentForUic(absFilename, contentsString, uisIncluded);
  651. }
  652. }
  653. return success;
  654. }
  655. void cmQtAutoGenerators::ParseContentForUic(
  656. const std::string& absFilename, const std::string& contentsString,
  657. std::map<std::string, std::vector<std::string> >& uisIncluded)
  658. {
  659. if (this->Verbose) {
  660. std::ostringstream err;
  661. err << "AutoUic: Checking " << absFilename << "\n";
  662. this->LogInfo(err.str());
  663. }
  664. const std::string realName = cmsys::SystemTools::GetRealPath(absFilename);
  665. const char* contentChars = contentsString.c_str();
  666. if (strstr(contentChars, "ui_") != CM_NULLPTR) {
  667. while (this->RegExpUicInclude.find(contentChars)) {
  668. const std::string currentUi = this->RegExpUicInclude.match(1);
  669. const std::string basename =
  670. cmsys::SystemTools::GetFilenameWithoutLastExtension(currentUi);
  671. // basename should be the part of the ui filename used for
  672. // finding the correct header, so we need to remove the ui_ part
  673. uisIncluded[realName].push_back(basename.substr(3));
  674. contentChars += this->RegExpUicInclude.end();
  675. }
  676. }
  677. }
  678. /**
  679. * @return True on success
  680. */
  681. bool cmQtAutoGenerators::ParseContentForMoc(
  682. const std::string& absFilename, const std::string& contentsString,
  683. const std::vector<std::string>& headerExtensions,
  684. std::map<std::string, std::string>& mocsIncluded, bool relaxed)
  685. {
  686. if (this->Verbose) {
  687. std::ostringstream err;
  688. err << "AutoMoc: Checking " << absFilename << "\n";
  689. this->LogInfo(err.str());
  690. }
  691. const std::string scannedFileAbsPath =
  692. cmsys::SystemTools::GetFilenamePath(
  693. cmsys::SystemTools::GetRealPath(absFilename)) +
  694. '/';
  695. const std::string scannedFileBasename =
  696. cmsys::SystemTools::GetFilenameWithoutLastExtension(absFilename);
  697. std::string macroName;
  698. const bool requiresMoc = this->MocRequired(contentsString, macroName);
  699. bool ownDotMocIncluded = false;
  700. bool ownMocUnderscoreIncluded = false;
  701. std::string ownMocUnderscoreFile;
  702. std::string ownMocHeaderFile;
  703. // first a simple string check for "moc" is *much* faster than the regexp,
  704. // and if the string search already fails, we don't have to try the
  705. // expensive regexp
  706. const char* contentChars = contentsString.c_str();
  707. if (strstr(contentChars, "moc") != CM_NULLPTR) {
  708. // Iterate over all included moc files
  709. while (this->RegExpMocInclude.find(contentChars)) {
  710. const std::string incString = this->RegExpMocInclude.match(1);
  711. // Basename of the moc include
  712. const std::string incBasename =
  713. cmsys::SystemTools::GetFilenameWithoutLastExtension(incString);
  714. std::string incSubDir;
  715. if (incString.find_first_of('/') != std::string::npos) {
  716. incSubDir = cmsys::SystemTools::GetFilenamePath(incString) + '/';
  717. }
  718. // If the moc include is of the moc_foo.cpp style we expect
  719. // the Q_OBJECT class declaration in a header file.
  720. // If the moc include is of the foo.moc style we need to look for
  721. // a Q_OBJECT macro in the current source file, if it contains the
  722. // macro we generate the moc file from the source file.
  723. if (cmHasLiteralPrefix(incBasename, "moc_")) {
  724. // Include: moc_FOO.cxx
  725. // Remove the moc_ part
  726. const std::string incRealBasename = incBasename.substr(4);
  727. const std::string headerToMoc = FindMatchingHeader(
  728. scannedFileAbsPath, incRealBasename, incSubDir, headerExtensions);
  729. if (!headerToMoc.empty()) {
  730. mocsIncluded[headerToMoc] = incString;
  731. if (relaxed && (incRealBasename == scannedFileBasename)) {
  732. ownMocUnderscoreIncluded = true;
  733. ownMocUnderscoreFile = incString;
  734. ownMocHeaderFile = headerToMoc;
  735. }
  736. } else {
  737. std::ostringstream err;
  738. err << "AutoMoc: Error: " << absFilename << "\n"
  739. << "The file includes the moc file \"" << incString
  740. << "\", but could not find header \"" << incRealBasename << '{'
  741. << JoinExts(headerExtensions) << "}\"\n";
  742. this->LogError(err.str());
  743. return false;
  744. }
  745. } else {
  746. // Include: FOO.moc
  747. std::string fileToMoc;
  748. if (relaxed) {
  749. // Mode: Relaxed
  750. if (!requiresMoc || (incBasename != scannedFileBasename)) {
  751. const std::string headerToMoc = FindMatchingHeader(
  752. scannedFileAbsPath, incBasename, incSubDir, headerExtensions);
  753. if (!headerToMoc.empty()) {
  754. // This is for KDE4 compatibility:
  755. fileToMoc = headerToMoc;
  756. if (!requiresMoc && (incBasename == scannedFileBasename)) {
  757. std::ostringstream err;
  758. err << "AutoMoc: Warning: " << absFilename << "\n"
  759. << "The file includes the moc file \"" << incString
  760. << "\", but does not contain a " << macroName
  761. << " macro. Running moc on "
  762. << "\"" << headerToMoc << "\" ! Include \"moc_"
  763. << incBasename
  764. << ".cpp\" for a compatibility with "
  765. "strict mode (see CMAKE_AUTOMOC_RELAXED_MODE).\n";
  766. this->LogWarning(err.str());
  767. } else {
  768. std::ostringstream err;
  769. err << "AutoMoc: Warning: " << absFilename << "\n"
  770. << "The file includes the moc file \"" << incString
  771. << "\" instead of \"moc_" << incBasename
  772. << ".cpp\". Running moc on "
  773. << "\"" << headerToMoc << "\" ! Include \"moc_"
  774. << incBasename
  775. << ".cpp\" for compatibility with "
  776. "strict mode (see CMAKE_AUTOMOC_RELAXED_MODE).\n";
  777. this->LogWarning(err.str());
  778. }
  779. } else {
  780. std::ostringstream err;
  781. err << "AutoMoc: Error: " << absFilename << "\n"
  782. << "The file includes the moc file \"" << incString
  783. << "\", which seems to be the moc file from a different "
  784. "source file. CMake also could not find a matching "
  785. "header.\n";
  786. this->LogError(err.str());
  787. return false;
  788. }
  789. } else {
  790. // Include self
  791. fileToMoc = absFilename;
  792. ownDotMocIncluded = true;
  793. }
  794. } else {
  795. // Mode: Strict
  796. if (incBasename == scannedFileBasename) {
  797. // Include self
  798. fileToMoc = absFilename;
  799. ownDotMocIncluded = true;
  800. } else {
  801. // Don't allow FOO.moc include other than self in strict mode
  802. std::ostringstream err;
  803. err << "AutoMoc: Error: " << absFilename << "\n"
  804. << "The file includes the moc file \"" << incString
  805. << "\", which seems to be the moc file from a different "
  806. "source file. This is not supported. Include \""
  807. << scannedFileBasename
  808. << ".moc\" to run moc on this source file.\n";
  809. this->LogError(err.str());
  810. return false;
  811. }
  812. }
  813. if (!fileToMoc.empty()) {
  814. mocsIncluded[fileToMoc] = incString;
  815. }
  816. }
  817. // Forward content pointer
  818. contentChars += this->RegExpMocInclude.end();
  819. }
  820. }
  821. if (requiresMoc && !ownDotMocIncluded) {
  822. // In this case, check whether the scanned file itself contains a Q_OBJECT.
  823. // If this is the case, the moc_foo.cpp should probably be generated from
  824. // foo.cpp instead of foo.h, because otherwise it won't build.
  825. // But warn, since this is not how it is supposed to be used.
  826. if (relaxed && ownMocUnderscoreIncluded) {
  827. // This is for KDE4 compatibility:
  828. std::ostringstream err;
  829. err << "AutoMoc: Warning: " << absFilename << "\n"
  830. << "The file contains a " << macroName
  831. << " macro, but does not include "
  832. << "\"" << scannedFileBasename << ".moc\", but instead includes "
  833. << "\"" << ownMocUnderscoreFile << "\". Running moc on "
  834. << "\"" << absFilename << "\" ! Better include \""
  835. << scannedFileBasename
  836. << ".moc\" for compatibility with "
  837. "strict mode (see CMAKE_AUTOMOC_RELAXED_MODE).\n";
  838. this->LogWarning(err.str());
  839. // Use scanned source file instead of scanned header file as moc source
  840. mocsIncluded[absFilename] = ownMocUnderscoreFile;
  841. mocsIncluded.erase(ownMocHeaderFile);
  842. } else {
  843. // Otherwise always error out since it will not compile:
  844. std::ostringstream err;
  845. err << "AutoMoc: Error: " << absFilename << "\n"
  846. << "The file contains a " << macroName
  847. << " macro, but does not include "
  848. << "\"" << scannedFileBasename << ".moc\" !\n";
  849. this->LogError(err.str());
  850. return false;
  851. }
  852. }
  853. return true;
  854. }
  855. void cmQtAutoGenerators::SearchHeadersForSourceFile(
  856. const std::string& absFilename,
  857. const std::vector<std::string>& headerExtensions,
  858. std::set<std::string>& mocHeaderFiles, std::set<std::string>& uicHeaderFiles)
  859. {
  860. std::string basepaths[2];
  861. {
  862. std::string bpath = cmsys::SystemTools::GetFilenamePath(
  863. cmsys::SystemTools::GetRealPath(absFilename));
  864. bpath += '/';
  865. bpath += cmsys::SystemTools::GetFilenameWithoutLastExtension(absFilename);
  866. // search for default header files and private header files
  867. basepaths[0] = (bpath + ".");
  868. basepaths[1] = (bpath + "_p.");
  869. }
  870. for (const std::string* bpit = cmArrayBegin(basepaths);
  871. bpit != cmArrayEnd(basepaths); ++bpit) {
  872. for (std::vector<std::string>::const_iterator heit =
  873. headerExtensions.begin();
  874. heit != headerExtensions.end(); ++heit) {
  875. const std::string hname = (*bpit) + (*heit);
  876. if (cmsys::SystemTools::FileExists(hname.c_str())) {
  877. // Moc headers
  878. if (!this->MocSkip(absFilename) && !this->MocSkip(hname)) {
  879. mocHeaderFiles.insert(hname);
  880. }
  881. // Uic headers
  882. if (!this->UicSkip(absFilename) && !this->UicSkip(hname)) {
  883. uicHeaderFiles.insert(hname);
  884. }
  885. break;
  886. }
  887. }
  888. }
  889. }
  890. void cmQtAutoGenerators::ParseHeaders(
  891. const std::set<std::string>& mocHeaderFiles,
  892. const std::set<std::string>& uicHeaderFiles,
  893. const std::map<std::string, std::string>& mocsIncluded,
  894. std::map<std::string, std::string>& mocsNotIncluded,
  895. std::map<std::string, std::vector<std::string> >& uisIncluded)
  896. {
  897. // Merged header files list to read files only once
  898. std::set<std::string> headerFiles;
  899. headerFiles.insert(mocHeaderFiles.begin(), mocHeaderFiles.end());
  900. headerFiles.insert(uicHeaderFiles.begin(), uicHeaderFiles.end());
  901. for (std::set<std::string>::const_iterator hIt = headerFiles.begin();
  902. hIt != headerFiles.end(); ++hIt) {
  903. const std::string& headerName = *hIt;
  904. const std::string contents = ReadAll(headerName);
  905. // Parse header content for MOC
  906. if ((mocHeaderFiles.find(headerName) != mocHeaderFiles.end()) &&
  907. (mocsIncluded.find(headerName) == mocsIncluded.end())) {
  908. // Log
  909. if (this->Verbose) {
  910. std::ostringstream err;
  911. err << "AutoMoc: Checking " << headerName << "\n";
  912. this->LogInfo(err.str());
  913. }
  914. std::string macroName;
  915. if (this->MocRequired(contents, macroName)) {
  916. mocsNotIncluded[headerName] =
  917. this->ChecksumedPath(headerName, "moc_", ".cpp");
  918. }
  919. }
  920. // Parse header content for UIC
  921. if (uicHeaderFiles.find(headerName) != uicHeaderFiles.end()) {
  922. this->ParseContentForUic(headerName, contents, uisIncluded);
  923. }
  924. }
  925. }
  926. bool cmQtAutoGenerators::MocGenerateAll(
  927. const std::map<std::string, std::string>& mocsIncluded,
  928. const std::map<std::string, std::string>& mocsNotIncluded)
  929. {
  930. if (!this->MocEnabled()) {
  931. return true;
  932. }
  933. // look for name collisions
  934. {
  935. std::multimap<std::string, std::string> collisions;
  936. // Test merged map of included and notIncluded
  937. std::map<std::string, std::string> mergedMocs(mocsIncluded);
  938. mergedMocs.insert(mocsNotIncluded.begin(), mocsNotIncluded.end());
  939. if (this->NameCollisionTest(mergedMocs, collisions)) {
  940. std::ostringstream err;
  941. err << "AutoMoc: Error: "
  942. "The same moc file will be generated "
  943. "from different sources."
  944. << std::endl
  945. << "To avoid this error either" << std::endl
  946. << "- rename the source files or" << std::endl
  947. << "- do not include the (moc_NAME.cpp|NAME.moc) file" << std::endl;
  948. this->LogErrorNameCollision(err.str(), collisions);
  949. return false;
  950. }
  951. }
  952. // generate moc files that are included by source files.
  953. {
  954. const std::string subDirPrefix = "include/";
  955. for (std::map<std::string, std::string>::const_iterator it =
  956. mocsIncluded.begin();
  957. it != mocsIncluded.end(); ++it) {
  958. if (!this->MocGenerateFile(it->first, it->second, subDirPrefix)) {
  959. if (this->RunMocFailed) {
  960. return false;
  961. }
  962. }
  963. }
  964. }
  965. // generate moc files that are _not_ included by source files.
  966. bool automocCppChanged = false;
  967. {
  968. const std::string subDirPrefix;
  969. for (std::map<std::string, std::string>::const_iterator it =
  970. mocsNotIncluded.begin();
  971. it != mocsNotIncluded.end(); ++it) {
  972. if (this->MocGenerateFile(it->first, it->second, subDirPrefix)) {
  973. automocCppChanged = true;
  974. } else {
  975. if (this->RunMocFailed) {
  976. return false;
  977. }
  978. }
  979. }
  980. }
  981. // Compose moc_compilation.cpp content
  982. std::string automocSource;
  983. {
  984. std::ostringstream outStream;
  985. outStream << "/* This file is autogenerated, do not edit*/\n";
  986. if (mocsNotIncluded.empty()) {
  987. // Dummy content
  988. outStream << "enum some_compilers { need_more_than_nothing };\n";
  989. } else {
  990. // Valid content
  991. for (std::map<std::string, std::string>::const_iterator it =
  992. mocsNotIncluded.begin();
  993. it != mocsNotIncluded.end(); ++it) {
  994. outStream << "#include \"" << it->second << "\"\n";
  995. }
  996. }
  997. outStream.flush();
  998. automocSource = outStream.str();
  999. }
  1000. // Check if we even need to update moc_compilation.cpp
  1001. if (!automocCppChanged) {
  1002. // compare contents of the moc_compilation.cpp file
  1003. const std::string oldContents = ReadAll(this->MocCppFilenameAbs);
  1004. if (oldContents == automocSource) {
  1005. // nothing changed: don't touch the moc_compilation.cpp file
  1006. if (this->Verbose) {
  1007. std::ostringstream err;
  1008. err << "AutoMoc: " << this->MocCppFilenameRel << " still up to date"
  1009. << std::endl;
  1010. this->LogInfo(err.str());
  1011. }
  1012. return true;
  1013. }
  1014. }
  1015. // Actually write moc_compilation.cpp
  1016. this->LogBold("Generating MOC compilation " + this->MocCppFilenameRel);
  1017. // Make sure the parent directory exists
  1018. bool success = this->MakeParentDirectory(this->MocCppFilenameAbs);
  1019. if (success) {
  1020. cmsys::ofstream outfile;
  1021. outfile.open(this->MocCppFilenameAbs.c_str(), std::ios::trunc);
  1022. if (!outfile) {
  1023. success = false;
  1024. std::ostringstream err;
  1025. err << "AutoMoc: error opening " << this->MocCppFilenameAbs << "\n";
  1026. this->LogError(err.str());
  1027. } else {
  1028. outfile << automocSource;
  1029. // Check for write errors
  1030. if (!outfile.good()) {
  1031. success = false;
  1032. std::ostringstream err;
  1033. err << "AutoMoc: error writing " << this->MocCppFilenameAbs << "\n";
  1034. this->LogError(err.str());
  1035. }
  1036. }
  1037. }
  1038. return success;
  1039. }
  1040. /**
  1041. * @return True if a moc file was created. False may indicate an error.
  1042. */
  1043. bool cmQtAutoGenerators::MocGenerateFile(const std::string& sourceFile,
  1044. const std::string& mocFileName,
  1045. const std::string& subDirPrefix)
  1046. {
  1047. bool mocGenerated = false;
  1048. bool generateMoc = this->GenerateAllMoc;
  1049. const std::string mocFileRel =
  1050. this->AutogenBuildSubDir + subDirPrefix + mocFileName;
  1051. const std::string mocFileAbs = this->CurrentBinaryDir + mocFileRel;
  1052. if (!generateMoc) {
  1053. // Test if the source file is newer that the build file
  1054. generateMoc = FileAbsentOrOlder(mocFileAbs, sourceFile);
  1055. }
  1056. if (generateMoc) {
  1057. // Log
  1058. this->LogBold("Generating MOC source " + mocFileRel);
  1059. // Make sure the parent directory exists
  1060. if (this->MakeParentDirectory(mocFileAbs)) {
  1061. // Compose moc command
  1062. std::vector<std::string> cmd;
  1063. cmd.push_back(this->MocExecutable);
  1064. cmd.insert(cmd.end(), this->MocIncludes.begin(),
  1065. this->MocIncludes.end());
  1066. // Add definitions
  1067. for (std::vector<std::string>::const_iterator it =
  1068. this->MocDefinitions.begin();
  1069. it != this->MocDefinitions.end(); ++it) {
  1070. cmd.push_back("-D" + (*it));
  1071. }
  1072. cmd.insert(cmd.end(), this->MocOptions.begin(), this->MocOptions.end());
  1073. #ifdef _WIN32
  1074. cmd.push_back("-DWIN32");
  1075. #endif
  1076. cmd.push_back("-o");
  1077. cmd.push_back(mocFileAbs);
  1078. cmd.push_back(sourceFile);
  1079. // Log moc command
  1080. if (this->Verbose) {
  1081. this->LogCommand(cmd);
  1082. }
  1083. // Execute moc command
  1084. bool res = false;
  1085. int retVal = 0;
  1086. std::string output;
  1087. res = cmSystemTools::RunSingleCommand(cmd, &output, &output, &retVal);
  1088. if (!res || (retVal != 0)) {
  1089. // Command failed
  1090. {
  1091. std::ostringstream err;
  1092. err << "AutoMoc: Error: moc process failed for\n";
  1093. err << "\"" << mocFileRel << "\"\n";
  1094. err << "AutoMoc: Command:\n" << cmJoin(cmd, " ") << "\n";
  1095. err << "AutoMoc: Command output:\n" << output << "\n";
  1096. this->LogError(err.str());
  1097. }
  1098. cmSystemTools::RemoveFile(mocFileAbs);
  1099. this->RunMocFailed = true;
  1100. } else {
  1101. // Success
  1102. mocGenerated = true;
  1103. }
  1104. } else {
  1105. // Parent directory creation failed
  1106. this->RunMocFailed = true;
  1107. }
  1108. }
  1109. return mocGenerated;
  1110. }
  1111. bool cmQtAutoGenerators::UicGenerateAll(
  1112. const std::map<std::string, std::vector<std::string> >& uisIncluded)
  1113. {
  1114. if (!this->UicEnabled()) {
  1115. return true;
  1116. }
  1117. // single map with input / output names
  1118. std::map<std::string, std::map<std::string, std::string> > uiGenMap;
  1119. std::map<std::string, std::string> testMap;
  1120. for (std::map<std::string, std::vector<std::string> >::const_iterator it =
  1121. uisIncluded.begin();
  1122. it != uisIncluded.end(); ++it) {
  1123. // source file path
  1124. std::string sourcePath = cmsys::SystemTools::GetFilenamePath(it->first);
  1125. sourcePath += '/';
  1126. // insert new map for source file an use new reference
  1127. uiGenMap[it->first] = std::map<std::string, std::string>();
  1128. std::map<std::string, std::string>& sourceMap = uiGenMap[it->first];
  1129. for (std::vector<std::string>::const_iterator sit = it->second.begin();
  1130. sit != it->second.end(); ++sit) {
  1131. const std::string& uiFileName = *sit;
  1132. const std::string uiInputFile = sourcePath + uiFileName + ".ui";
  1133. const std::string uiOutputFile = "ui_" + uiFileName + ".h";
  1134. sourceMap[uiInputFile] = uiOutputFile;
  1135. testMap[uiInputFile] = uiOutputFile;
  1136. }
  1137. }
  1138. // look for name collisions
  1139. {
  1140. std::multimap<std::string, std::string> collisions;
  1141. if (this->NameCollisionTest(testMap, collisions)) {
  1142. std::ostringstream err;
  1143. err << "AutoUic: Error: The same ui_NAME.h file will be generated "
  1144. "from different sources."
  1145. << std::endl
  1146. << "To avoid this error rename the source files." << std::endl;
  1147. this->LogErrorNameCollision(err.str(), collisions);
  1148. return false;
  1149. }
  1150. }
  1151. testMap.clear();
  1152. // generate ui files
  1153. for (std::map<std::string,
  1154. std::map<std::string, std::string> >::const_iterator it =
  1155. uiGenMap.begin();
  1156. it != uiGenMap.end(); ++it) {
  1157. for (std::map<std::string, std::string>::const_iterator sit =
  1158. it->second.begin();
  1159. sit != it->second.end(); ++sit) {
  1160. if (!this->UicGenerateFile(it->first, sit->first, sit->second)) {
  1161. if (this->RunUicFailed) {
  1162. return false;
  1163. }
  1164. }
  1165. }
  1166. }
  1167. return true;
  1168. }
  1169. /**
  1170. * @return True if a uic file was created. False may indicate an error.
  1171. */
  1172. bool cmQtAutoGenerators::UicGenerateFile(const std::string& realName,
  1173. const std::string& uiInputFile,
  1174. const std::string& uiOutputFile)
  1175. {
  1176. bool uicGenerated = false;
  1177. bool generateUic = this->GenerateAllUic;
  1178. const std::string uicFileRel =
  1179. this->AutogenBuildSubDir + "include/" + uiOutputFile;
  1180. const std::string uicFileAbs = this->CurrentBinaryDir + uicFileRel;
  1181. if (!generateUic) {
  1182. // Test if the source file is newer that the build file
  1183. generateUic = FileAbsentOrOlder(uicFileAbs, uiInputFile);
  1184. }
  1185. if (generateUic) {
  1186. // Log
  1187. this->LogBold("Generating UIC header " + uicFileRel);
  1188. // Make sure the parent directory exists
  1189. if (this->MakeParentDirectory(uicFileAbs)) {
  1190. // Compose uic command
  1191. std::vector<std::string> cmd;
  1192. cmd.push_back(this->UicExecutable);
  1193. {
  1194. std::vector<std::string> opts = this->UicTargetOptions;
  1195. std::map<std::string, std::string>::const_iterator optionIt =
  1196. this->UicOptions.find(uiInputFile);
  1197. if (optionIt != this->UicOptions.end()) {
  1198. std::vector<std::string> fileOpts;
  1199. cmSystemTools::ExpandListArgument(optionIt->second, fileOpts);
  1200. UicMergeOptions(opts, fileOpts, (this->QtMajorVersion == "5"));
  1201. }
  1202. cmd.insert(cmd.end(), opts.begin(), opts.end());
  1203. }
  1204. cmd.push_back("-o");
  1205. cmd.push_back(uicFileAbs);
  1206. cmd.push_back(uiInputFile);
  1207. // Log command
  1208. if (this->Verbose) {
  1209. this->LogCommand(cmd);
  1210. }
  1211. // Execute command
  1212. bool res = false;
  1213. int retVal = 0;
  1214. std::string output;
  1215. res = cmSystemTools::RunSingleCommand(cmd, &output, &output, &retVal);
  1216. if (!res || (retVal != 0)) {
  1217. // Command failed
  1218. {
  1219. std::ostringstream err;
  1220. err << "AutoUic: Error: uic process failed for\n";
  1221. err << "\"" << uicFileRel << "\" needed by\n";
  1222. err << "\"" << realName << "\"\n";
  1223. err << "AutoUic: Command:\n" << cmJoin(cmd, " ") << "\n";
  1224. err << "AutoUic: Command output:\n" << output << "\n";
  1225. this->LogError(err.str());
  1226. }
  1227. cmSystemTools::RemoveFile(uicFileAbs);
  1228. this->RunUicFailed = true;
  1229. } else {
  1230. // Success
  1231. uicGenerated = true;
  1232. }
  1233. } else {
  1234. // Parent directory creation failed
  1235. this->RunUicFailed = true;
  1236. }
  1237. }
  1238. return uicGenerated;
  1239. }
  1240. bool cmQtAutoGenerators::RccGenerateAll()
  1241. {
  1242. if (!this->RccEnabled()) {
  1243. return true;
  1244. }
  1245. // generate single map with input / output names
  1246. std::map<std::string, std::string> qrcGenMap;
  1247. for (std::vector<std::string>::const_iterator si = this->RccSources.begin();
  1248. si != this->RccSources.end(); ++si) {
  1249. const std::string ext = cmsys::SystemTools::GetFilenameLastExtension(*si);
  1250. if (ext == ".qrc") {
  1251. qrcGenMap[*si] =
  1252. this->AutogenBuildSubDir + this->ChecksumedPath(*si, "qrc_", ".cpp");
  1253. }
  1254. }
  1255. // look for name collisions
  1256. {
  1257. std::multimap<std::string, std::string> collisions;
  1258. if (this->NameCollisionTest(qrcGenMap, collisions)) {
  1259. std::ostringstream err;
  1260. err << "AutoRcc: Error: The same qrc_NAME.cpp file"
  1261. " will be generated from different sources."
  1262. << std::endl
  1263. << "To avoid this error rename the source .qrc files." << std::endl;
  1264. this->LogErrorNameCollision(err.str(), collisions);
  1265. return false;
  1266. }
  1267. }
  1268. // generate qrc files
  1269. for (std::map<std::string, std::string>::const_iterator si =
  1270. qrcGenMap.begin();
  1271. si != qrcGenMap.end(); ++si) {
  1272. bool unique = FileNameIsUnique(si->first, qrcGenMap);
  1273. if (!this->RccGenerateFile(si->first, si->second, unique)) {
  1274. if (this->RunRccFailed) {
  1275. return false;
  1276. }
  1277. }
  1278. }
  1279. return true;
  1280. }
  1281. /**
  1282. * @return True if a rcc file was created. False may indicate an error.
  1283. */
  1284. bool cmQtAutoGenerators::RccGenerateFile(const std::string& rccInputFile,
  1285. const std::string& rccOutputFile,
  1286. bool unique_n)
  1287. {
  1288. bool rccGenerated = false;
  1289. bool generateRcc = this->GenerateAllRcc;
  1290. const std::string rccBuildFile = this->CurrentBinaryDir + rccOutputFile;
  1291. if (!generateRcc) {
  1292. // Test if the resources list file is newer than build file
  1293. generateRcc = FileAbsentOrOlder(rccBuildFile, rccInputFile);
  1294. if (!generateRcc) {
  1295. // Test if any resource file is newer than the build file
  1296. const std::vector<std::string>& files = this->RccInputs[rccInputFile];
  1297. for (std::vector<std::string>::const_iterator it = files.begin();
  1298. it != files.end(); ++it) {
  1299. if (FileAbsentOrOlder(rccBuildFile, *it)) {
  1300. generateRcc = true;
  1301. break;
  1302. }
  1303. }
  1304. }
  1305. }
  1306. if (generateRcc) {
  1307. // Log
  1308. this->LogBold("Generating RCC source " + rccOutputFile);
  1309. // Make sure the parent directory exists
  1310. if (this->MakeParentDirectory(rccBuildFile)) {
  1311. // Compose symbol name
  1312. std::string symbolName =
  1313. cmsys::SystemTools::GetFilenameWithoutLastExtension(rccInputFile);
  1314. if (!unique_n) {
  1315. symbolName += "_";
  1316. symbolName += fpathCheckSum.getPart(rccInputFile);
  1317. }
  1318. // Replace '-' with '_'. The former is valid for
  1319. // file names but not for symbol names.
  1320. std::replace(symbolName.begin(), symbolName.end(), '-', '_');
  1321. // Compose rcc command
  1322. std::vector<std::string> cmd;
  1323. cmd.push_back(this->RccExecutable);
  1324. {
  1325. std::map<std::string, std::string>::const_iterator optionIt =
  1326. this->RccOptions.find(rccInputFile);
  1327. if (optionIt != this->RccOptions.end()) {
  1328. cmSystemTools::ExpandListArgument(optionIt->second, cmd);
  1329. }
  1330. }
  1331. cmd.push_back("-name");
  1332. cmd.push_back(symbolName);
  1333. cmd.push_back("-o");
  1334. cmd.push_back(rccBuildFile);
  1335. cmd.push_back(rccInputFile);
  1336. // Log command
  1337. if (this->Verbose) {
  1338. this->LogCommand(cmd);
  1339. }
  1340. // Execute command
  1341. bool res = false;
  1342. int retVal = 0;
  1343. std::string output;
  1344. res = cmSystemTools::RunSingleCommand(cmd, &output, &output, &retVal);
  1345. if (!res || (retVal != 0)) {
  1346. // Command failed
  1347. {
  1348. std::ostringstream err;
  1349. err << "AutoRcc: Error: rcc process failed for\n";
  1350. err << "\"" << rccOutputFile << "\"\n";
  1351. err << "AutoRcc: Command:\n" << cmJoin(cmd, " ") << "\n";
  1352. err << "AutoRcc: Command output:\n" << output << "\n";
  1353. this->LogError(err.str());
  1354. }
  1355. cmSystemTools::RemoveFile(rccBuildFile);
  1356. this->RunRccFailed = true;
  1357. } else {
  1358. // Success
  1359. rccGenerated = true;
  1360. }
  1361. } else {
  1362. // Parent directory creation failed
  1363. this->RunRccFailed = true;
  1364. }
  1365. }
  1366. return rccGenerated;
  1367. }
  1368. void cmQtAutoGenerators::LogErrorNameCollision(
  1369. const std::string& message,
  1370. const std::multimap<std::string, std::string>& collisions)
  1371. {
  1372. typedef std::multimap<std::string, std::string>::const_iterator Iter;
  1373. std::ostringstream err;
  1374. // Add message
  1375. err << message;
  1376. // Append collision list
  1377. for (Iter it = collisions.begin(); it != collisions.end(); ++it) {
  1378. err << it->first << " : " << it->second << std::endl;
  1379. }
  1380. this->LogError(err.str());
  1381. }
  1382. void cmQtAutoGenerators::LogBold(const std::string& message)
  1383. {
  1384. cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundBlue |
  1385. cmsysTerminal_Color_ForegroundBold,
  1386. message.c_str(), true, this->ColorOutput);
  1387. }
  1388. void cmQtAutoGenerators::LogInfo(const std::string& message)
  1389. {
  1390. cmSystemTools::Stdout(message.c_str(), message.size());
  1391. }
  1392. void cmQtAutoGenerators::LogWarning(const std::string& message)
  1393. {
  1394. std::string msg(message);
  1395. msg += "\n";
  1396. cmSystemTools::Stdout(msg.c_str(), msg.size());
  1397. }
  1398. void cmQtAutoGenerators::LogError(const std::string& message)
  1399. {
  1400. std::string msg(message);
  1401. msg += "\n";
  1402. cmSystemTools::Stderr(msg.c_str(), msg.size());
  1403. }
  1404. void cmQtAutoGenerators::LogCommand(const std::vector<std::string>& command)
  1405. {
  1406. std::ostringstream sbuf;
  1407. for (std::vector<std::string>::const_iterator cmdIt = command.begin();
  1408. cmdIt != command.end(); ++cmdIt) {
  1409. if (cmdIt != command.begin()) {
  1410. sbuf << " ";
  1411. }
  1412. sbuf << *cmdIt;
  1413. }
  1414. if (!sbuf.str().empty()) {
  1415. sbuf << std::endl;
  1416. this->LogInfo(sbuf.str());
  1417. }
  1418. }
  1419. /**
  1420. * @brief Collects name collisions as output/input pairs
  1421. * @return True if there were collisions
  1422. */
  1423. bool cmQtAutoGenerators::NameCollisionTest(
  1424. const std::map<std::string, std::string>& genFiles,
  1425. std::multimap<std::string, std::string>& collisions) const
  1426. {
  1427. typedef std::map<std::string, std::string>::const_iterator Iter;
  1428. typedef std::map<std::string, std::string>::value_type VType;
  1429. for (Iter ait = genFiles.begin(); ait != genFiles.end(); ++ait) {
  1430. bool first_match(true);
  1431. for (Iter bit = (++Iter(ait)); bit != genFiles.end(); ++bit) {
  1432. if (ait->second == bit->second) {
  1433. if (first_match) {
  1434. if (collisions.find(ait->second) != collisions.end()) {
  1435. // We already know of this collision from before
  1436. break;
  1437. }
  1438. collisions.insert(VType(ait->second, ait->first));
  1439. first_match = false;
  1440. }
  1441. collisions.insert(VType(bit->second, bit->first));
  1442. }
  1443. }
  1444. }
  1445. return !collisions.empty();
  1446. }
  1447. /**
  1448. * @brief Generates a file path based on the checksum of the source file path
  1449. * @return The path
  1450. */
  1451. std::string cmQtAutoGenerators::ChecksumedPath(const std::string& sourceFile,
  1452. const char* basePrefix,
  1453. const char* baseSuffix) const
  1454. {
  1455. std::string res = fpathCheckSum.getPart(sourceFile);
  1456. res += "/";
  1457. res += basePrefix;
  1458. res += cmsys::SystemTools::GetFilenameWithoutLastExtension(sourceFile);
  1459. res += baseSuffix;
  1460. return res;
  1461. }
  1462. /**
  1463. * @brief Tries to find the header file to the given file base path by
  1464. * appending different header extensions
  1465. * @return True on success
  1466. */
  1467. bool cmQtAutoGenerators::FindHeader(
  1468. std::string& header, const std::string& testBasePath,
  1469. const std::vector<std::string>& headerExtensions) const
  1470. {
  1471. for (std::vector<std::string>::const_iterator ext = headerExtensions.begin();
  1472. ext != headerExtensions.end(); ++ext) {
  1473. std::string testFilePath(testBasePath);
  1474. testFilePath += '.';
  1475. testFilePath += (*ext);
  1476. if (cmsys::SystemTools::FileExists(testFilePath.c_str())) {
  1477. header = testFilePath;
  1478. return true;
  1479. }
  1480. }
  1481. return false;
  1482. }
  1483. std::string cmQtAutoGenerators::FindMatchingHeader(
  1484. const std::string& basePath, const std::string& baseName,
  1485. const std::string& subDir,
  1486. const std::vector<std::string>& headerExtensions) const
  1487. {
  1488. std::string header;
  1489. do {
  1490. if (!subDir.empty()) {
  1491. if (FindHeader(header, basePath + subDir + baseName, headerExtensions)) {
  1492. break;
  1493. }
  1494. }
  1495. if (FindHeader(header, basePath + baseName, headerExtensions)) {
  1496. break;
  1497. }
  1498. } while (false);
  1499. return header;
  1500. }
  1501. /**
  1502. * @brief Generates the parent directory of the given file on demand
  1503. * @return True on success
  1504. */
  1505. bool cmQtAutoGenerators::MakeParentDirectory(const std::string& filename)
  1506. {
  1507. bool success = true;
  1508. const std::string dirName = cmSystemTools::GetFilenamePath(filename);
  1509. if (!dirName.empty()) {
  1510. success = cmsys::SystemTools::MakeDirectory(dirName);
  1511. if (!success) {
  1512. std::ostringstream err;
  1513. err << "AutoGen: Directory creation failed: " << dirName << std::endl;
  1514. this->LogError(err.str());
  1515. }
  1516. }
  1517. return success;
  1518. }