cmQtAutoGenerators.cxx 55 KB

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