cmQtAutoGenerators.cxx 55 KB

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