cmQtAutoGenerators.cxx 51 KB

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