cmQtAutoGenerators.cxx 54 KB

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