cmQtAutoGenerators.cxx 54 KB

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