cmQtAutoGenerators.cxx 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678
  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. this->MacroFilters[0].first = "Q_OBJECT";
  196. this->MacroFilters[0].second.compile("[\n][ \t]*Q_OBJECT[^a-zA-Z0-9_]");
  197. this->MacroFilters[1].first = "Q_GADGET";
  198. this->MacroFilters[1].second.compile("[\n][ \t]*Q_GADGET[^a-zA-Z0-9_]");
  199. // Precompile regular expressions
  200. this->RegExpMocInclude.compile(
  201. "[\n][ \t]*#[ \t]*include[ \t]+"
  202. "[\"<](([^ \">]+/)?moc_[^ \">/]+\\.cpp|[^ \">]+\\.moc)[\">]");
  203. this->RegExpUicInclude.compile("[\n][ \t]*#[ \t]*include[ \t]+"
  204. "[\"<](([^ \">]+/)?ui_[^ \">/]+\\.h)[\">]");
  205. }
  206. bool cmQtAutoGenerators::Run(const std::string& targetDirectory,
  207. const std::string& config)
  208. {
  209. cmake cm;
  210. cm.SetHomeOutputDirectory(targetDirectory);
  211. cm.SetHomeDirectory(targetDirectory);
  212. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  213. cmGlobalGenerator gg(&cm);
  214. cmStateSnapshot snapshot = cm.GetCurrentSnapshot();
  215. snapshot.GetDirectory().SetCurrentBinary(targetDirectory);
  216. snapshot.GetDirectory().SetCurrentSource(targetDirectory);
  217. CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&gg, snapshot));
  218. gg.SetCurrentMakefile(mf.get());
  219. if (!this->ReadAutogenInfoFile(mf.get(), targetDirectory, config)) {
  220. return false;
  221. }
  222. // Read old settings
  223. this->SettingsFileRead(mf.get(), targetDirectory);
  224. // Init and run
  225. this->Init(mf.get());
  226. if (this->QtMajorVersion == "4" || this->QtMajorVersion == "5") {
  227. if (!this->RunAutogen()) {
  228. return false;
  229. }
  230. }
  231. // Write latest settings
  232. if (!this->SettingsFileWrite(targetDirectory)) {
  233. return false;
  234. }
  235. return true;
  236. }
  237. bool cmQtAutoGenerators::ReadAutogenInfoFile(
  238. cmMakefile* makefile, const std::string& targetDirectory,
  239. const std::string& config)
  240. {
  241. std::string filename(cmSystemTools::CollapseFullPath(targetDirectory));
  242. cmSystemTools::ConvertToUnixSlashes(filename);
  243. filename += "/AutogenInfo.cmake";
  244. if (!makefile->ReadListFile(filename.c_str())) {
  245. std::ostringstream err;
  246. err << "AutoGen: error processing file: " << filename << std::endl;
  247. this->LogError(err.str());
  248. return false;
  249. }
  250. // - Target names
  251. this->OriginTargetName =
  252. makefile->GetSafeDefinition("AM_ORIGIN_TARGET_NAME");
  253. this->AutogenTargetName = makefile->GetSafeDefinition("AM_TARGET_NAME");
  254. // - Directories
  255. this->ProjectSourceDir = makefile->GetSafeDefinition("AM_CMAKE_SOURCE_DIR");
  256. this->ProjectBinaryDir = makefile->GetSafeDefinition("AM_CMAKE_BINARY_DIR");
  257. this->CurrentSourceDir =
  258. makefile->GetSafeDefinition("AM_CMAKE_CURRENT_SOURCE_DIR");
  259. this->CurrentBinaryDir =
  260. makefile->GetSafeDefinition("AM_CMAKE_CURRENT_BINARY_DIR");
  261. // - Qt environment
  262. this->QtMajorVersion = makefile->GetSafeDefinition("AM_QT_VERSION_MAJOR");
  263. if (this->QtMajorVersion == "") {
  264. this->QtMajorVersion =
  265. makefile->GetSafeDefinition("AM_Qt5Core_VERSION_MAJOR");
  266. }
  267. this->MocExecutable = makefile->GetSafeDefinition("AM_QT_MOC_EXECUTABLE");
  268. this->UicExecutable = makefile->GetSafeDefinition("AM_QT_UIC_EXECUTABLE");
  269. this->RccExecutable = makefile->GetSafeDefinition("AM_QT_RCC_EXECUTABLE");
  270. // - File Lists
  271. cmSystemTools::ExpandListArgument(makefile->GetSafeDefinition("AM_SOURCES"),
  272. this->Sources);
  273. cmSystemTools::ExpandListArgument(makefile->GetSafeDefinition("AM_HEADERS"),
  274. this->Headers);
  275. // - Moc
  276. cmSystemTools::ExpandListArgument(makefile->GetSafeDefinition("AM_SKIP_MOC"),
  277. this->MocSkipList);
  278. cmSystemTools::ExpandListArgument(
  279. GetConfigDefinition(makefile, "AM_MOC_COMPILE_DEFINITIONS", config),
  280. this->MocDefinitions);
  281. cmSystemTools::ExpandListArgument(
  282. GetConfigDefinition(makefile, "AM_MOC_INCLUDES", config),
  283. this->MocIncludePaths);
  284. cmSystemTools::ExpandListArgument(
  285. makefile->GetSafeDefinition("AM_MOC_OPTIONS"), this->MocOptions);
  286. // - Uic
  287. cmSystemTools::ExpandListArgument(makefile->GetSafeDefinition("AM_SKIP_UIC"),
  288. this->UicSkipList);
  289. cmSystemTools::ExpandListArgument(
  290. GetConfigDefinition(makefile, "AM_UIC_TARGET_OPTIONS", config),
  291. this->UicTargetOptions);
  292. {
  293. std::vector<std::string> uicFilesVec;
  294. std::vector<std::string> uicOptionsVec;
  295. cmSystemTools::ExpandListArgument(
  296. makefile->GetSafeDefinition("AM_UIC_OPTIONS_FILES"), uicFilesVec);
  297. cmSystemTools::ExpandListArgument(
  298. makefile->GetSafeDefinition("AM_UIC_OPTIONS_OPTIONS"), uicOptionsVec);
  299. if (uicFilesVec.size() != uicOptionsVec.size()) {
  300. std::ostringstream err;
  301. err << "AutoGen: Error: Uic files/options lists size missmatch in: "
  302. << filename << std::endl;
  303. this->LogError(err.str());
  304. return false;
  305. }
  306. for (std::vector<std::string>::iterator fileIt = uicFilesVec.begin(),
  307. optionIt = uicOptionsVec.begin();
  308. fileIt != uicFilesVec.end(); ++fileIt, ++optionIt) {
  309. cmSystemTools::ReplaceString(*optionIt, "@list_sep@", ";");
  310. this->UicOptions[*fileIt] = *optionIt;
  311. }
  312. }
  313. // - Rcc
  314. cmSystemTools::ExpandListArgument(
  315. makefile->GetSafeDefinition("AM_RCC_SOURCES"), this->RccSources);
  316. {
  317. std::vector<std::string> rccFilesVec;
  318. std::vector<std::string> rccOptionsVec;
  319. cmSystemTools::ExpandListArgument(
  320. makefile->GetSafeDefinition("AM_RCC_OPTIONS_FILES"), rccFilesVec);
  321. cmSystemTools::ExpandListArgument(
  322. makefile->GetSafeDefinition("AM_RCC_OPTIONS_OPTIONS"), rccOptionsVec);
  323. if (rccFilesVec.size() != rccOptionsVec.size()) {
  324. std::ostringstream err;
  325. err << "AutoGen: Error: RCC files/options lists size missmatch in: "
  326. << filename << std::endl;
  327. this->LogError(err.str());
  328. return false;
  329. }
  330. for (std::vector<std::string>::iterator fileIt = rccFilesVec.begin(),
  331. optionIt = rccOptionsVec.begin();
  332. fileIt != rccFilesVec.end(); ++fileIt, ++optionIt) {
  333. cmSystemTools::ReplaceString(*optionIt, "@list_sep@", ";");
  334. this->RccOptions[*fileIt] = *optionIt;
  335. }
  336. }
  337. {
  338. std::vector<std::string> rccInputLists;
  339. cmSystemTools::ExpandListArgument(
  340. makefile->GetSafeDefinition("AM_RCC_INPUTS"), rccInputLists);
  341. // qrc files in the end of the list may have been empty
  342. if (rccInputLists.size() < this->RccSources.size()) {
  343. rccInputLists.resize(this->RccSources.size());
  344. }
  345. if (this->RccSources.size() != rccInputLists.size()) {
  346. std::ostringstream err;
  347. err << "AutoGen: Error: RCC sources/inputs lists size missmatch in: "
  348. << filename << std::endl;
  349. this->LogError(err.str());
  350. return false;
  351. }
  352. for (std::vector<std::string>::iterator fileIt = this->RccSources.begin(),
  353. inputIt = rccInputLists.begin();
  354. fileIt != this->RccSources.end(); ++fileIt, ++inputIt) {
  355. cmSystemTools::ReplaceString(*inputIt, "@list_sep@", ";");
  356. std::vector<std::string> rccInputFiles;
  357. cmSystemTools::ExpandListArgument(*inputIt, rccInputFiles);
  358. this->RccInputs[*fileIt] = rccInputFiles;
  359. }
  360. }
  361. // - Flags
  362. this->IncludeProjectDirsBefore =
  363. makefile->IsOn("AM_CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE");
  364. this->MocRelaxedMode = makefile->IsOn("AM_MOC_RELAXED_MODE");
  365. return true;
  366. }
  367. void cmQtAutoGenerators::SettingsFileRead(cmMakefile* makefile,
  368. const std::string& targetDirectory)
  369. {
  370. // Compose current settings strings
  371. if (this->MocEnabled()) {
  372. std::string& str = this->SettingsStringMoc;
  373. str += JoinOptionsList(this->MocDefinitions);
  374. str += " ~~~ ";
  375. str += JoinOptionsList(this->MocIncludePaths);
  376. str += " ~~~ ";
  377. str += JoinOptionsList(this->MocOptions);
  378. str += " ~~~ ";
  379. str += this->IncludeProjectDirsBefore ? "TRUE" : "FALSE";
  380. str += " ~~~ ";
  381. }
  382. if (this->UicEnabled()) {
  383. std::string& str = this->SettingsStringUic;
  384. str += JoinOptionsList(this->UicTargetOptions);
  385. str += " ~~~ ";
  386. str += JoinOptionsMap(this->UicOptions);
  387. str += " ~~~ ";
  388. }
  389. if (this->RccEnabled()) {
  390. std::string& str = this->SettingsStringRcc;
  391. str += JoinOptionsMap(this->RccOptions);
  392. str += " ~~~ ";
  393. }
  394. // Read old settings
  395. const std::string filename = SettingsFile(targetDirectory);
  396. if (makefile->ReadListFile(filename.c_str())) {
  397. if (!SettingsMatch(makefile, SettingsKeyMoc, this->SettingsStringMoc)) {
  398. this->GenerateAllMoc = true;
  399. }
  400. if (!SettingsMatch(makefile, SettingsKeyUic, this->SettingsStringUic)) {
  401. this->GenerateAllUic = true;
  402. }
  403. if (!SettingsMatch(makefile, SettingsKeyRcc, this->SettingsStringRcc)) {
  404. this->GenerateAllRcc = true;
  405. }
  406. // In case any setting changed remove the old settings file.
  407. // This triggers a full rebuild on the next run if the current
  408. // build is aborted before writing the current settings in the end.
  409. if (this->GenerateAllAny()) {
  410. cmSystemTools::RemoveFile(filename);
  411. }
  412. } else {
  413. // If the file could not be read re-generate everythiung.
  414. this->GenerateAllMoc = true;
  415. this->GenerateAllUic = true;
  416. this->GenerateAllRcc = true;
  417. }
  418. }
  419. bool cmQtAutoGenerators::SettingsFileWrite(const std::string& targetDirectory)
  420. {
  421. bool success = true;
  422. // Only write if any setting changed
  423. if (this->GenerateAllAny()) {
  424. const std::string filename = SettingsFile(targetDirectory);
  425. if (this->Verbose) {
  426. std::ostringstream err;
  427. err << "AutoGen: Writing settings file " << filename << "\n";
  428. this->LogInfo(err.str());
  429. }
  430. cmsys::ofstream outfile;
  431. outfile.open(filename.c_str(), std::ios::trunc);
  432. if (outfile) {
  433. SettingWrite(outfile, SettingsKeyMoc, this->SettingsStringMoc);
  434. SettingWrite(outfile, SettingsKeyUic, this->SettingsStringUic);
  435. SettingWrite(outfile, SettingsKeyRcc, this->SettingsStringRcc);
  436. success = outfile.good();
  437. outfile.close();
  438. } else {
  439. success = false;
  440. // Remove old settings file to trigger full rebuild on next run
  441. cmSystemTools::RemoveFile(filename);
  442. {
  443. std::ostringstream err;
  444. err << "AutoGen: Error: Writing old settings file failed: " << filename
  445. << std::endl;
  446. this->LogError(err.str());
  447. }
  448. }
  449. }
  450. return success;
  451. }
  452. void cmQtAutoGenerators::Init(cmMakefile* makefile)
  453. {
  454. this->AutogenBuildSubDir = this->AutogenTargetName;
  455. this->AutogenBuildSubDir += "/";
  456. this->MocCppFilenameRel = this->AutogenBuildSubDir;
  457. this->MocCppFilenameRel += "moc_compilation.cpp";
  458. this->MocCppFilenameAbs = this->CurrentBinaryDir + this->MocCppFilenameRel;
  459. // Init file path checksum generator
  460. fpathCheckSum.setupParentDirs(this->CurrentSourceDir, this->CurrentBinaryDir,
  461. this->ProjectSourceDir,
  462. this->ProjectBinaryDir);
  463. // Acquire header extensions
  464. this->HeaderExtensions = makefile->GetCMakeInstance()->GetHeaderExtensions();
  465. // Sort include directories on demand
  466. if (this->IncludeProjectDirsBefore) {
  467. // Move strings to temporary list
  468. std::list<std::string> includes;
  469. includes.insert(includes.end(), this->MocIncludePaths.begin(),
  470. this->MocIncludePaths.end());
  471. this->MocIncludePaths.clear();
  472. this->MocIncludePaths.reserve(includes.size());
  473. // Append project directories only
  474. {
  475. const char* movePaths[2] = { this->ProjectBinaryDir.c_str(),
  476. this->ProjectSourceDir.c_str() };
  477. for (const char* const* mpit = cmArrayBegin(movePaths);
  478. mpit != cmArrayEnd(movePaths); ++mpit) {
  479. std::list<std::string>::iterator it = includes.begin();
  480. while (it != includes.end()) {
  481. const std::string& path = *it;
  482. if (cmsys::SystemTools::StringStartsWith(path, *mpit)) {
  483. this->MocIncludePaths.push_back(path);
  484. it = includes.erase(it);
  485. } else {
  486. ++it;
  487. }
  488. }
  489. }
  490. }
  491. // Append remaining directories
  492. this->MocIncludePaths.insert(this->MocIncludePaths.end(), includes.begin(),
  493. includes.end());
  494. }
  495. // Compose moc includes list
  496. {
  497. std::set<std::string> frameworkPaths;
  498. for (std::vector<std::string>::const_iterator it =
  499. this->MocIncludePaths.begin();
  500. it != this->MocIncludePaths.end(); ++it) {
  501. const std::string& path = *it;
  502. this->MocIncludes.push_back("-I" + path);
  503. // Extract framework path
  504. if (cmHasLiteralSuffix(path, ".framework/Headers")) {
  505. // Go up twice to get to the framework root
  506. std::vector<std::string> pathComponents;
  507. cmsys::SystemTools::SplitPath(path, pathComponents);
  508. std::string frameworkPath = cmsys::SystemTools::JoinPath(
  509. pathComponents.begin(), pathComponents.end() - 2);
  510. frameworkPaths.insert(frameworkPath);
  511. }
  512. }
  513. // Append framework includes
  514. for (std::set<std::string>::const_iterator it = frameworkPaths.begin();
  515. it != frameworkPaths.end(); ++it) {
  516. this->MocIncludes.push_back("-F");
  517. this->MocIncludes.push_back(*it);
  518. }
  519. }
  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 = cmsys::SystemTools::GetRealPath(*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 = cmsys::SystemTools::GetRealPath(*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. for (unsigned int ii = 0; ii != cmArraySize(this->MacroFilters); ++ii) {
  583. MacroFilter& macroFilter = this->MacroFilters[ii];
  584. // Run a simple check before an expensive regular expression check
  585. if (text.find(macroFilter.first) != std::string::npos) {
  586. if (macroFilter.second.find(text)) {
  587. // Return macro name on demand
  588. if (macroName != CM_NULLPTR) {
  589. *macroName = macroFilter.first;
  590. }
  591. return true;
  592. }
  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 char* contentChars = contentsString.c_str();
  662. if (strstr(contentChars, "ui_") != CM_NULLPTR) {
  663. while (this->RegExpUicInclude.find(contentChars)) {
  664. const std::string currentUi = this->RegExpUicInclude.match(1);
  665. const std::string basename =
  666. cmsys::SystemTools::GetFilenameWithoutLastExtension(currentUi);
  667. // basename should be the part of the ui filename used for
  668. // finding the correct header, so we need to remove the ui_ part
  669. uisIncluded[absFilename].push_back(basename.substr(3));
  670. contentChars += this->RegExpUicInclude.end();
  671. }
  672. }
  673. }
  674. /**
  675. * @return True on success
  676. */
  677. bool cmQtAutoGenerators::ParseContentForMoc(
  678. const std::string& absFilename, const std::string& contentsString,
  679. std::map<std::string, std::string>& mocsIncluded, bool relaxed)
  680. {
  681. if (this->Verbose) {
  682. std::ostringstream err;
  683. err << "AutoMoc: Checking " << absFilename << "\n";
  684. this->LogInfo(err.str());
  685. }
  686. const std::string scannedFileAbsPath =
  687. cmsys::SystemTools::GetFilenamePath(absFilename) + '/';
  688. const std::string scannedFileBasename =
  689. cmsys::SystemTools::GetFilenameWithoutLastExtension(absFilename);
  690. std::string macroName;
  691. const bool requiresMoc = this->MocRequired(contentsString, &macroName);
  692. bool ownDotMocIncluded = false;
  693. bool ownMocUnderscoreIncluded = false;
  694. std::string ownMocUnderscoreFile;
  695. std::string ownMocHeaderFile;
  696. // first a simple string check for "moc" is *much* faster than the regexp,
  697. // and if the string search already fails, we don't have to try the
  698. // expensive regexp
  699. const char* contentChars = contentsString.c_str();
  700. if (strstr(contentChars, "moc") != CM_NULLPTR) {
  701. // Iterate over all included moc files
  702. while (this->RegExpMocInclude.find(contentChars)) {
  703. const std::string incString = this->RegExpMocInclude.match(1);
  704. // Basename of the moc include
  705. const std::string incBasename =
  706. cmsys::SystemTools::GetFilenameWithoutLastExtension(incString);
  707. std::string incSubDir;
  708. if (incString.find_first_of('/') != std::string::npos) {
  709. incSubDir = cmsys::SystemTools::GetFilenamePath(incString);
  710. incSubDir += '/';
  711. }
  712. // If the moc include is of the moc_foo.cpp style we expect
  713. // the Q_OBJECT class declaration in a header file.
  714. // If the moc include is of the foo.moc style we need to look for
  715. // a Q_OBJECT macro in the current source file, if it contains the
  716. // macro we generate the moc file from the source file.
  717. if (cmHasLiteralPrefix(incBasename, "moc_")) {
  718. // Include: moc_FOO.cxx
  719. // Remove the moc_ part
  720. const std::string incRealBasename = incBasename.substr(4);
  721. const std::string headerToMoc =
  722. this->FindMocHeader(scannedFileAbsPath, incRealBasename, incSubDir);
  723. if (!headerToMoc.empty()) {
  724. mocsIncluded[headerToMoc] = incString;
  725. if (relaxed && (incRealBasename == scannedFileBasename)) {
  726. ownMocUnderscoreIncluded = true;
  727. ownMocUnderscoreFile = incString;
  728. ownMocHeaderFile = headerToMoc;
  729. }
  730. } else {
  731. std::ostringstream err;
  732. err << "AutoMoc: Error: " << absFilename << "\n"
  733. << "The file includes the moc file \"" << incString
  734. << "\", but could not find header \"" << incRealBasename << '{'
  735. << JoinExts(this->HeaderExtensions) << "}\"\n";
  736. this->LogError(err.str());
  737. return false;
  738. }
  739. } else {
  740. // Include: FOO.moc
  741. std::string fileToMoc;
  742. if (relaxed) {
  743. // Mode: Relaxed
  744. if (requiresMoc && (incBasename == scannedFileBasename)) {
  745. // Include self
  746. fileToMoc = absFilename;
  747. ownDotMocIncluded = true;
  748. } else {
  749. // In relaxed mode try to find a header instead but issue a warning
  750. const std::string headerToMoc =
  751. this->FindMocHeader(scannedFileAbsPath, incBasename, incSubDir);
  752. if (!headerToMoc.empty()) {
  753. // This is for KDE4 compatibility:
  754. fileToMoc = headerToMoc;
  755. if (!requiresMoc && (incBasename == scannedFileBasename)) {
  756. std::ostringstream err;
  757. err << "AutoMoc: Warning: " << absFilename << "\n"
  758. << "The file includes the moc file \"" << incString << "\""
  759. << ", but does not contain a Q_OBJECT or Q_GADGET macro.\n"
  760. << "Running moc on \"" << headerToMoc << "\"!\n"
  761. << "Include \"moc_" << incBasename
  762. << ".cpp\" for a compatibility with "
  763. "strict mode (see CMAKE_AUTOMOC_RELAXED_MODE).\n";
  764. this->LogWarning(err.str());
  765. } else {
  766. std::ostringstream err;
  767. err << "AutoMoc: Warning: " << absFilename << "\n"
  768. << "The file includes the moc file \"" << incString
  769. << "\" instead of \"moc_" << incBasename << ".cpp\".\n"
  770. << "Running moc on \"" << headerToMoc << "\"!\n"
  771. << "Include \"moc_" << incBasename
  772. << ".cpp\" for compatibility with "
  773. "strict mode (see CMAKE_AUTOMOC_RELAXED_MODE).\n";
  774. this->LogWarning(err.str());
  775. }
  776. } else {
  777. std::ostringstream err;
  778. err << "AutoMoc: Error: " << absFilename << "\n"
  779. << "The file includes the moc file \"" << incString
  780. << "\", which seems to be the moc file from a different "
  781. "source file. CMake also could not find a matching "
  782. "header.\n";
  783. this->LogError(err.str());
  784. return false;
  785. }
  786. }
  787. } else {
  788. // Mode: Strict
  789. if (incBasename == scannedFileBasename) {
  790. // Include self
  791. fileToMoc = absFilename;
  792. ownDotMocIncluded = true;
  793. // Accept but issue a warning if moc isn't required
  794. if (!requiresMoc) {
  795. std::ostringstream err;
  796. err << "AutoMoc: Error: " << absFilename << "\n"
  797. << "The file includes the moc file \"" << incString << "\""
  798. << ", but does not contain a Q_OBJECT or Q_GADGET "
  799. "macro.\n";
  800. this->LogWarning(err.str());
  801. }
  802. } else {
  803. // Don't allow FOO.moc include other than self in strict mode
  804. std::ostringstream err;
  805. err << "AutoMoc: Error: " << absFilename << "\n"
  806. << "The file includes the moc file \"" << incString
  807. << "\", which seems to be the moc file from a different "
  808. "source file. This is not supported. Include \""
  809. << scannedFileBasename
  810. << ".moc\" to run moc on this source file.\n";
  811. this->LogError(err.str());
  812. return false;
  813. }
  814. }
  815. if (!fileToMoc.empty()) {
  816. mocsIncluded[fileToMoc] = incString;
  817. }
  818. }
  819. // Forward content pointer
  820. contentChars += this->RegExpMocInclude.end();
  821. }
  822. }
  823. if (requiresMoc && !ownDotMocIncluded) {
  824. // In this case, check whether the scanned file itself contains a Q_OBJECT.
  825. // If this is the case, the moc_foo.cpp should probably be generated from
  826. // foo.cpp instead of foo.h, because otherwise it won't build.
  827. // But warn, since this is not how it is supposed to be used.
  828. if (relaxed && ownMocUnderscoreIncluded) {
  829. // This is for KDE4 compatibility:
  830. std::ostringstream err;
  831. err << "AutoMoc: Warning: " << absFilename << "\n"
  832. << "The file contains a " << macroName
  833. << " macro, but does not include "
  834. << "\"" << scannedFileBasename << ".moc\", but instead includes "
  835. << "\"" << ownMocUnderscoreFile << "\".\n"
  836. << "Running moc on \"" << absFilename << "\"!\n"
  837. << "Better include \"" << scannedFileBasename
  838. << ".moc\" for compatibility with "
  839. "strict mode (see CMAKE_AUTOMOC_RELAXED_MODE).\n";
  840. this->LogWarning(err.str());
  841. // Use scanned source file instead of scanned header file as moc source
  842. mocsIncluded[absFilename] = ownMocUnderscoreFile;
  843. mocsIncluded.erase(ownMocHeaderFile);
  844. } else {
  845. // Otherwise always error out since it will not compile:
  846. std::ostringstream err;
  847. err << "AutoMoc: Error: " << absFilename << "\n"
  848. << "The file contains a " << macroName
  849. << " macro, but does not include "
  850. << "\"" << scannedFileBasename << ".moc\"!\n";
  851. this->LogError(err.str());
  852. return false;
  853. }
  854. }
  855. return true;
  856. }
  857. void cmQtAutoGenerators::SearchHeadersForSourceFile(
  858. const std::string& absFilename, std::set<std::string>& mocHeaderFiles,
  859. std::set<std::string>& uicHeaderFiles) const
  860. {
  861. std::string basepaths[2];
  862. {
  863. std::string bpath = cmsys::SystemTools::GetFilenamePath(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. std::string headerName;
  873. if (this->FindHeader(headerName, *bpit)) {
  874. // Moc headers
  875. if (!this->MocSkip(absFilename) && !this->MocSkip(headerName)) {
  876. mocHeaderFiles.insert(headerName);
  877. }
  878. // Uic headers
  879. if (!this->UicSkip(absFilename) && !this->UicSkip(headerName)) {
  880. uicHeaderFiles.insert(headerName);
  881. }
  882. break;
  883. }
  884. }
  885. }
  886. void cmQtAutoGenerators::ParseHeaders(
  887. const std::set<std::string>& mocHeaderFiles,
  888. const std::set<std::string>& uicHeaderFiles,
  889. const std::map<std::string, std::string>& mocsIncluded,
  890. std::map<std::string, std::string>& mocsNotIncluded,
  891. std::map<std::string, std::vector<std::string> >& uisIncluded)
  892. {
  893. // Merged header files list to read files only once
  894. std::set<std::string> headerFiles;
  895. headerFiles.insert(mocHeaderFiles.begin(), mocHeaderFiles.end());
  896. headerFiles.insert(uicHeaderFiles.begin(), uicHeaderFiles.end());
  897. for (std::set<std::string>::const_iterator hIt = headerFiles.begin();
  898. hIt != headerFiles.end(); ++hIt) {
  899. const std::string& headerName = *hIt;
  900. const std::string contents = ReadAll(headerName);
  901. // Parse header content for MOC
  902. if ((mocHeaderFiles.find(headerName) != mocHeaderFiles.end()) &&
  903. (mocsIncluded.find(headerName) == mocsIncluded.end())) {
  904. // Log
  905. if (this->Verbose) {
  906. std::ostringstream err;
  907. err << "AutoMoc: Checking " << headerName << "\n";
  908. this->LogInfo(err.str());
  909. }
  910. if (this->MocRequired(contents)) {
  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. bool cmQtAutoGenerators::FindHeaderGlobal(
  1479. std::string& header, const std::string& testBasePath) const
  1480. {
  1481. for (std::vector<std::string>::const_iterator iit =
  1482. this->MocIncludePaths.begin();
  1483. iit != this->MocIncludePaths.end(); ++iit) {
  1484. const std::string fullPath = ((*iit) + '/' + testBasePath);
  1485. if (FindHeader(header, fullPath)) {
  1486. return true;
  1487. }
  1488. }
  1489. return false;
  1490. }
  1491. std::string cmQtAutoGenerators::FindMocHeader(const std::string& basePath,
  1492. const std::string& baseName,
  1493. const std::string& subDir) const
  1494. {
  1495. std::string header;
  1496. do {
  1497. if (!subDir.empty()) {
  1498. if (this->FindHeader(header, basePath + subDir + baseName)) {
  1499. break;
  1500. }
  1501. }
  1502. if (this->FindHeader(header, basePath + baseName)) {
  1503. break;
  1504. }
  1505. // Try include directories
  1506. if (this->FindHeaderGlobal(header, subDir + baseName)) {
  1507. break;
  1508. }
  1509. } while (false);
  1510. // Sanitize
  1511. if (!header.empty()) {
  1512. header = cmsys::SystemTools::GetRealPath(header);
  1513. }
  1514. return header;
  1515. }
  1516. /**
  1517. * @brief Tries to find a file in the include directories
  1518. * @return True on success
  1519. */
  1520. bool cmQtAutoGenerators::FindInIncludeDirectories(
  1521. std::string& file_n, const std::string& searchString) const
  1522. {
  1523. for (std::vector<std::string>::const_iterator iit =
  1524. this->MocIncludePaths.begin();
  1525. iit != this->MocIncludePaths.end(); ++iit) {
  1526. const std::string fullPath = ((*iit) + '/' + searchString);
  1527. if (cmsys::SystemTools::FileExists(fullPath.c_str())) {
  1528. file_n = fullPath;
  1529. return true;
  1530. }
  1531. }
  1532. return false;
  1533. }
  1534. /**
  1535. * @brief Generates the parent directory of the given file on demand
  1536. * @return True on success
  1537. */
  1538. bool cmQtAutoGenerators::MakeParentDirectory(const std::string& filename)
  1539. {
  1540. bool success = true;
  1541. const std::string dirName = cmSystemTools::GetFilenamePath(filename);
  1542. if (!dirName.empty()) {
  1543. success = cmsys::SystemTools::MakeDirectory(dirName);
  1544. if (!success) {
  1545. std::ostringstream err;
  1546. err << "AutoGen: Directory creation failed: " << dirName << std::endl;
  1547. this->LogError(err.str());
  1548. }
  1549. }
  1550. return success;
  1551. }