cmQtAutoGenerators.cxx 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063
  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 "cmQtAutoGen.h"
  4. #include "cmQtAutoGenerators.h"
  5. #include "cmsys/FStream.hxx"
  6. #include "cmsys/Terminal.h"
  7. #include <algorithm>
  8. #include <array>
  9. #include <assert.h>
  10. #include <list>
  11. #include <sstream>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <utility>
  15. #include "cmAlgorithms.h"
  16. #include "cmCryptoHash.h"
  17. #include "cmFilePathChecksum.h"
  18. #include "cmGlobalGenerator.h"
  19. #include "cmMakefile.h"
  20. #include "cmOutputConverter.h"
  21. #include "cmStateDirectory.h"
  22. #include "cmStateSnapshot.h"
  23. #include "cmSystemTools.h"
  24. #include "cm_auto_ptr.hxx"
  25. #include "cmake.h"
  26. #if defined(__APPLE__)
  27. #include <unistd.h>
  28. #endif
  29. // -- Static variables
  30. static const char* SettingsKeyMoc = "AM_MOC_SETTINGS_HASH";
  31. static const char* SettingsKeyUic = "AM_UIC_SETTINGS_HASH";
  32. static const char* SettingsKeyRcc = "AM_RCC_SETTINGS_HASH";
  33. // -- Static functions
  34. inline static std::string Quoted(const std::string& text)
  35. {
  36. return cmQtAutoGen::Quoted(text);
  37. }
  38. static std::string QuotedCommand(const std::vector<std::string>& command)
  39. {
  40. std::string res;
  41. for (const std::string& item : command) {
  42. if (!res.empty()) {
  43. res.push_back(' ');
  44. }
  45. const std::string cesc = Quoted(item);
  46. if (item.empty() || (cesc.size() > (item.size() + 2)) ||
  47. (cesc.find(' ') != std::string::npos)) {
  48. res += cesc;
  49. } else {
  50. res += item;
  51. }
  52. }
  53. return res;
  54. }
  55. static void InfoGet(cmMakefile* makefile, const char* key, std::string& value)
  56. {
  57. value = makefile->GetSafeDefinition(key);
  58. }
  59. static void InfoGet(cmMakefile* makefile, const char* key, bool& value)
  60. {
  61. value = makefile->IsOn(key);
  62. }
  63. static void InfoGet(cmMakefile* makefile, const char* key,
  64. std::vector<std::string>& list)
  65. {
  66. cmSystemTools::ExpandListArgument(makefile->GetSafeDefinition(key), list);
  67. }
  68. static void InfoGetConfig(cmMakefile* makefile, const char* key,
  69. const std::string& config, std::string& value)
  70. {
  71. const char* valueConf = nullptr;
  72. {
  73. std::string keyConf = key;
  74. if (!config.empty()) {
  75. keyConf += "_";
  76. keyConf += config;
  77. }
  78. valueConf = makefile->GetDefinition(keyConf);
  79. }
  80. if (valueConf == nullptr) {
  81. valueConf = makefile->GetSafeDefinition(key);
  82. }
  83. value = valueConf;
  84. }
  85. static void InfoGetConfig(cmMakefile* makefile, const char* key,
  86. const std::string& config,
  87. std::vector<std::string>& list)
  88. {
  89. std::string value;
  90. InfoGetConfig(makefile, key, config, value);
  91. cmSystemTools::ExpandListArgument(value, list);
  92. }
  93. inline static bool SettingsMatch(cmMakefile* makefile, const char* key,
  94. const std::string& value)
  95. {
  96. return (value == makefile->GetSafeDefinition(key));
  97. }
  98. static void SettingAppend(std::string& str, const char* key,
  99. const std::string& value)
  100. {
  101. if (!value.empty()) {
  102. str += "set(";
  103. str += key;
  104. str += " ";
  105. str += cmOutputConverter::EscapeForCMake(value);
  106. str += ")\n";
  107. }
  108. }
  109. static std::string SubDirPrefix(const std::string& fileName)
  110. {
  111. std::string res(cmsys::SystemTools::GetFilenamePath(fileName));
  112. if (!res.empty()) {
  113. res += '/';
  114. }
  115. return res;
  116. }
  117. static bool FileNameIsUnique(const std::string& filePath,
  118. const std::map<std::string, std::string>& fileMap)
  119. {
  120. size_t count(0);
  121. const std::string fileName = cmsys::SystemTools::GetFilenameName(filePath);
  122. for (const auto& item : fileMap) {
  123. if (cmsys::SystemTools::GetFilenameName(item.first) == fileName) {
  124. ++count;
  125. if (count > 1) {
  126. return false;
  127. }
  128. }
  129. }
  130. return true;
  131. }
  132. static bool ReadAll(std::string& content, const std::string& filename)
  133. {
  134. bool success = false;
  135. {
  136. cmsys::ifstream ifs(filename.c_str());
  137. if (ifs) {
  138. std::ostringstream osst;
  139. osst << ifs.rdbuf();
  140. content = osst.str();
  141. success = true;
  142. }
  143. }
  144. return success;
  145. }
  146. /**
  147. * @brief Tests if buildFile doesn't exist or is older than sourceFile
  148. * @return True if buildFile doesn't exist or is older than sourceFile
  149. */
  150. static bool FileAbsentOrOlder(const std::string& buildFile,
  151. const std::string& sourceFile)
  152. {
  153. int result = 0;
  154. bool success =
  155. cmsys::SystemTools::FileTimeCompare(buildFile, sourceFile, &result);
  156. return (!success || (result <= 0));
  157. }
  158. static bool ListContains(const std::vector<std::string>& list,
  159. const std::string& entry)
  160. {
  161. return (std::find(list.begin(), list.end(), entry) != list.end());
  162. }
  163. static std::string JoinOptionsList(const std::vector<std::string>& opts)
  164. {
  165. return cmOutputConverter::EscapeForCMake(cmJoin(opts, ";"));
  166. }
  167. static std::string JoinOptionsMap(
  168. const std::map<std::string, std::string>& opts)
  169. {
  170. std::string result;
  171. for (const auto& item : opts) {
  172. if (!result.empty()) {
  173. result += cmQtAutoGen::listSep;
  174. }
  175. result += item.first;
  176. result += "===";
  177. result += item.second;
  178. }
  179. return result;
  180. }
  181. static void UicMergeOptions(std::vector<std::string>& opts,
  182. const std::vector<std::string>& fileOpts,
  183. bool isQt5)
  184. {
  185. static const char* valueOptions[] = { "tr", "translate",
  186. "postfix", "generator",
  187. "include", // Since Qt 5.3
  188. "g" };
  189. std::vector<std::string> extraOpts;
  190. for (std::vector<std::string>::const_iterator it = fileOpts.begin();
  191. it != fileOpts.end(); ++it) {
  192. std::vector<std::string>::iterator existingIt =
  193. std::find(opts.begin(), opts.end(), *it);
  194. if (existingIt != opts.end()) {
  195. const char* o = it->c_str();
  196. if (*o == '-') {
  197. ++o;
  198. }
  199. if (isQt5 && *o == '-') {
  200. ++o;
  201. }
  202. if (std::find_if(cmArrayBegin(valueOptions), cmArrayEnd(valueOptions),
  203. cmStrCmp(*it)) != cmArrayEnd(valueOptions)) {
  204. assert(existingIt + 1 != opts.end());
  205. *(existingIt + 1) = *(it + 1);
  206. ++it;
  207. }
  208. } else {
  209. extraOpts.push_back(*it);
  210. }
  211. }
  212. opts.insert(opts.end(), extraOpts.begin(), extraOpts.end());
  213. }
  214. // -- Class methods
  215. cmQtAutoGenerators::cmQtAutoGenerators()
  216. : Verbose(cmsys::SystemTools::HasEnv("VERBOSE"))
  217. , ColorOutput(true)
  218. , MocSettingsChanged(false)
  219. , MocPredefsChanged(false)
  220. , MocRunFailed(false)
  221. , UicSettingsChanged(false)
  222. , UicRunFailed(false)
  223. , RccSettingsChanged(false)
  224. , RccRunFailed(false)
  225. {
  226. std::string colorEnv;
  227. cmsys::SystemTools::GetEnv("COLOR", colorEnv);
  228. if (!colorEnv.empty()) {
  229. if (cmSystemTools::IsOn(colorEnv.c_str())) {
  230. this->ColorOutput = true;
  231. } else {
  232. this->ColorOutput = false;
  233. }
  234. }
  235. // Moc macro filters
  236. this->MocMacroFilters.push_back(
  237. MocMacroFilter("Q_OBJECT", "[\n][ \t]*{?[ \t]*Q_OBJECT[^a-zA-Z0-9_]"));
  238. this->MocMacroFilters.push_back(
  239. MocMacroFilter("Q_GADGET", "[\n][ \t]*{?[ \t]*Q_GADGET[^a-zA-Z0-9_]"));
  240. // Precompile regular expressions
  241. this->MocRegExpInclude.compile(
  242. "[\n][ \t]*#[ \t]*include[ \t]+"
  243. "[\"<](([^ \">]+/)?moc_[^ \">/]+\\.cpp|[^ \">]+\\.moc)[\">]");
  244. this->UicRegExpInclude.compile("[\n][ \t]*#[ \t]*include[ \t]+"
  245. "[\"<](([^ \">]+/)?ui_[^ \">/]+\\.h)[\">]");
  246. }
  247. bool cmQtAutoGenerators::Run(const std::string& targetDirectory,
  248. const std::string& config)
  249. {
  250. cmake cm(cmake::RoleScript);
  251. cm.SetHomeOutputDirectory(targetDirectory);
  252. cm.SetHomeDirectory(targetDirectory);
  253. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  254. cmGlobalGenerator gg(&cm);
  255. cmStateSnapshot snapshot = cm.GetCurrentSnapshot();
  256. snapshot.GetDirectory().SetCurrentBinary(targetDirectory);
  257. snapshot.GetDirectory().SetCurrentSource(targetDirectory);
  258. CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&gg, snapshot));
  259. gg.SetCurrentMakefile(mf.get());
  260. bool success = false;
  261. if (this->ReadAutogenInfoFile(mf.get(), targetDirectory, config)) {
  262. // Read old settings
  263. this->SettingsFileRead(mf.get());
  264. // Init and run
  265. this->Init(mf.get());
  266. if (this->RunAutogen()) {
  267. // Write current settings
  268. if (this->SettingsFileWrite()) {
  269. success = true;
  270. }
  271. }
  272. }
  273. return success;
  274. }
  275. bool cmQtAutoGenerators::MocDependFilterPush(const std::string& key,
  276. const std::string& regExp)
  277. {
  278. bool success = false;
  279. if (!key.empty()) {
  280. if (!regExp.empty()) {
  281. MocDependFilter filter;
  282. filter.key = key;
  283. if (filter.regExp.compile(regExp)) {
  284. this->MocDependFilters.push_back(filter);
  285. success = true;
  286. } else {
  287. this->LogError("AutoMoc: Error in AUTOMOC_DEPEND_FILTERS: Compiling "
  288. "regular expression failed.\nKey: " +
  289. Quoted(key) + "\nExp.: " + Quoted(regExp));
  290. }
  291. } else {
  292. this->LogError("AutoMoc: Error in AUTOMOC_DEPEND_FILTERS: Regular "
  293. "expression is empty");
  294. }
  295. } else {
  296. this->LogError("AutoMoc: Error in AUTOMOC_DEPEND_FILTERS: Key is empty");
  297. }
  298. return success;
  299. }
  300. bool cmQtAutoGenerators::ReadAutogenInfoFile(
  301. cmMakefile* makefile, const std::string& targetDirectory,
  302. const std::string& config)
  303. {
  304. std::string filename(cmSystemTools::CollapseFullPath(targetDirectory));
  305. cmSystemTools::ConvertToUnixSlashes(filename);
  306. filename += "/AutogenInfo.cmake";
  307. if (!makefile->ReadListFile(filename.c_str())) {
  308. this->LogError("AutoGen: Error processing file: " + filename);
  309. return false;
  310. }
  311. // -- Meta
  312. InfoGetConfig(makefile, "AM_CONFIG_SUFFIX", config, this->ConfigSuffix);
  313. // - Old settings file
  314. {
  315. this->SettingsFile = cmSystemTools::CollapseFullPath(targetDirectory);
  316. cmSystemTools::ConvertToUnixSlashes(this->SettingsFile);
  317. this->SettingsFile += "/AutogenOldSettings";
  318. this->SettingsFile += this->ConfigSuffix;
  319. this->SettingsFile += ".cmake";
  320. }
  321. // - Files and directories
  322. InfoGet(makefile, "AM_CMAKE_SOURCE_DIR", this->ProjectSourceDir);
  323. InfoGet(makefile, "AM_CMAKE_BINARY_DIR", this->ProjectBinaryDir);
  324. InfoGet(makefile, "AM_CMAKE_CURRENT_SOURCE_DIR", this->CurrentSourceDir);
  325. InfoGet(makefile, "AM_CMAKE_CURRENT_BINARY_DIR", this->CurrentBinaryDir);
  326. InfoGet(makefile, "AM_CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE",
  327. this->IncludeProjectDirsBefore);
  328. InfoGet(makefile, "AM_BUILD_DIR", this->AutogenBuildDir);
  329. if (this->AutogenBuildDir.empty()) {
  330. this->LogError("AutoGen: Error: Missing autogen build directory ");
  331. return false;
  332. }
  333. InfoGet(makefile, "AM_SOURCES", this->Sources);
  334. InfoGet(makefile, "AM_HEADERS", this->Headers);
  335. // - Qt environment
  336. InfoGet(makefile, "AM_QT_VERSION_MAJOR", this->QtMajorVersion);
  337. if (this->QtMajorVersion.empty()) {
  338. InfoGet(makefile, "AM_Qt5Core_VERSION_MAJOR", this->QtMajorVersion);
  339. }
  340. InfoGet(makefile, "AM_QT_MOC_EXECUTABLE", this->MocExecutable);
  341. InfoGet(makefile, "AM_QT_UIC_EXECUTABLE", this->UicExecutable);
  342. InfoGet(makefile, "AM_QT_RCC_EXECUTABLE", this->RccExecutable);
  343. // Check Qt version
  344. if ((this->QtMajorVersion != "4") && (this->QtMajorVersion != "5")) {
  345. this->LogError("AutoGen: Error: Unsupported Qt version: " +
  346. Quoted(this->QtMajorVersion));
  347. return false;
  348. }
  349. // - Moc
  350. if (this->MocEnabled()) {
  351. InfoGet(makefile, "AM_MOC_SKIP", this->MocSkipList);
  352. InfoGetConfig(makefile, "AM_MOC_DEFINITIONS", config,
  353. this->MocDefinitions);
  354. #ifdef _WIN32
  355. {
  356. const std::string win32("WIN32");
  357. if (!ListContains(this->MocDefinitions, win32)) {
  358. this->MocDefinitions.push_back(win32);
  359. }
  360. }
  361. #endif
  362. InfoGetConfig(makefile, "AM_MOC_INCLUDES", config, this->MocIncludePaths);
  363. InfoGet(makefile, "AM_MOC_OPTIONS", this->MocOptions);
  364. InfoGet(makefile, "AM_MOC_RELAXED_MODE", this->MocRelaxedMode);
  365. {
  366. std::vector<std::string> MocMacroNames;
  367. InfoGet(makefile, "AM_MOC_MACRO_NAMES", MocMacroNames);
  368. for (const std::string& item : MocMacroNames) {
  369. this->MocMacroFilters.emplace_back(
  370. item, ("[^a-zA-Z0-9_]" + item).append("[^a-zA-Z0-9_]"));
  371. }
  372. }
  373. {
  374. std::vector<std::string> mocDependFilters;
  375. InfoGet(makefile, "AM_MOC_DEPEND_FILTERS", mocDependFilters);
  376. // Insert Q_PLUGIN_METADATA dependency filter
  377. if (this->QtMajorVersion != "4") {
  378. this->MocDependFilterPush("Q_PLUGIN_METADATA",
  379. "[\n][ \t]*Q_PLUGIN_METADATA[ \t]*\\("
  380. "[^\\)]*FILE[ \t]*\"([^\"]+)\"");
  381. }
  382. // Insert user defined dependency filters
  383. if ((mocDependFilters.size() % 2) == 0) {
  384. for (std::vector<std::string>::const_iterator
  385. dit = mocDependFilters.begin(),
  386. ditEnd = mocDependFilters.end();
  387. dit != ditEnd; dit += 2) {
  388. if (!this->MocDependFilterPush(*dit, *(dit + 1))) {
  389. return false;
  390. }
  391. }
  392. } else {
  393. this->LogError(
  394. "AutoMoc: Error: AUTOMOC_DEPEND_FILTERS list size is not "
  395. "a multiple of 2 in:\n" +
  396. Quoted(filename));
  397. return false;
  398. }
  399. }
  400. InfoGet(makefile, "AM_MOC_PREDEFS_CMD", this->MocPredefsCmd);
  401. }
  402. // - Uic
  403. if (this->UicEnabled()) {
  404. InfoGet(makefile, "AM_UIC_SKIP", this->UicSkipList);
  405. InfoGet(makefile, "AM_UIC_SEARCH_PATHS", this->UicSearchPaths);
  406. InfoGetConfig(makefile, "AM_UIC_TARGET_OPTIONS", config,
  407. this->UicTargetOptions);
  408. {
  409. std::vector<std::string> uicFilesVec;
  410. std::vector<std::string> uicOptionsVec;
  411. InfoGet(makefile, "AM_UIC_OPTIONS_FILES", uicFilesVec);
  412. InfoGet(makefile, "AM_UIC_OPTIONS_OPTIONS", uicOptionsVec);
  413. // Compare list sizes
  414. if (uicFilesVec.size() == uicOptionsVec.size()) {
  415. for (std::vector<std::string>::iterator
  416. fileIt = uicFilesVec.begin(),
  417. optionIt = uicOptionsVec.begin();
  418. fileIt != uicFilesVec.end(); ++fileIt, ++optionIt) {
  419. cmSystemTools::ReplaceString(*optionIt, cmQtAutoGen::listSep, ";");
  420. this->UicOptions[*fileIt] = *optionIt;
  421. }
  422. } else {
  423. this->LogError(
  424. "AutoGen: Error: Uic files/options lists size missmatch in:\n" +
  425. Quoted(filename));
  426. return false;
  427. }
  428. }
  429. }
  430. // - Rcc
  431. if (this->RccEnabled()) {
  432. InfoGet(makefile, "AM_RCC_SOURCES", this->RccSources);
  433. // File options
  434. {
  435. std::vector<std::string> rccFilesVec;
  436. std::vector<std::string> rccOptionsVec;
  437. InfoGet(makefile, "AM_RCC_OPTIONS_FILES", rccFilesVec);
  438. InfoGet(makefile, "AM_RCC_OPTIONS_OPTIONS", rccOptionsVec);
  439. if (rccFilesVec.size() == rccOptionsVec.size()) {
  440. for (std::vector<std::string>::iterator
  441. fileIt = rccFilesVec.begin(),
  442. optionIt = rccOptionsVec.begin();
  443. fileIt != rccFilesVec.end(); ++fileIt, ++optionIt) {
  444. // Replace item separator
  445. cmSystemTools::ReplaceString(*optionIt, cmQtAutoGen::listSep, ";");
  446. this->RccOptions[*fileIt] = *optionIt;
  447. }
  448. } else {
  449. this->LogError(
  450. "AutoGen: Error: RCC files/options lists size missmatch in:\n" +
  451. Quoted(filename));
  452. return false;
  453. }
  454. }
  455. // File lists
  456. {
  457. std::vector<std::string> rccInputLists;
  458. InfoGet(makefile, "AM_RCC_INPUTS", rccInputLists);
  459. if (this->RccSources.size() == rccInputLists.size()) {
  460. for (std::vector<std::string>::iterator
  461. fileIt = this->RccSources.begin(),
  462. inputIt = rccInputLists.begin();
  463. fileIt != this->RccSources.end(); ++fileIt, ++inputIt) {
  464. // Remove braces
  465. *inputIt = inputIt->substr(1, inputIt->size() - 2);
  466. // Replace item separator
  467. cmSystemTools::ReplaceString(*inputIt, cmQtAutoGen::listSep, ";");
  468. std::vector<std::string> rccInputFiles;
  469. cmSystemTools::ExpandListArgument(*inputIt, rccInputFiles);
  470. this->RccInputs[*fileIt] = rccInputFiles;
  471. }
  472. } else {
  473. this->LogError(
  474. "AutoGen: Error: RCC sources/inputs lists size missmatch in:\n" +
  475. Quoted(filename));
  476. return false;
  477. }
  478. }
  479. }
  480. return true;
  481. }
  482. void cmQtAutoGenerators::SettingsFileRead(cmMakefile* makefile)
  483. {
  484. // Compose current settings strings
  485. {
  486. cmCryptoHash crypt(cmCryptoHash::AlgoSHA256);
  487. const std::string sep(" ~~~ ");
  488. if (this->MocEnabled()) {
  489. std::string str;
  490. str += this->MocExecutable;
  491. str += sep;
  492. str += JoinOptionsList(this->MocDefinitions);
  493. str += sep;
  494. str += JoinOptionsList(this->MocIncludePaths);
  495. str += sep;
  496. str += JoinOptionsList(this->MocOptions);
  497. str += sep;
  498. str += this->IncludeProjectDirsBefore ? "TRUE" : "FALSE";
  499. str += sep;
  500. str += JoinOptionsList(this->MocPredefsCmd);
  501. str += sep;
  502. this->SettingsStringMoc = crypt.HashString(str);
  503. }
  504. if (this->UicEnabled()) {
  505. std::string str;
  506. str += this->UicExecutable;
  507. str += sep;
  508. str += JoinOptionsList(this->UicTargetOptions);
  509. str += sep;
  510. str += JoinOptionsMap(this->UicOptions);
  511. str += sep;
  512. this->SettingsStringUic = crypt.HashString(str);
  513. }
  514. if (this->RccEnabled()) {
  515. std::string str;
  516. str += this->RccExecutable;
  517. str += sep;
  518. str += JoinOptionsMap(this->RccOptions);
  519. str += sep;
  520. this->SettingsStringRcc = crypt.HashString(str);
  521. }
  522. }
  523. // Read old settings
  524. if (makefile->ReadListFile(this->SettingsFile.c_str())) {
  525. if (!SettingsMatch(makefile, SettingsKeyMoc, this->SettingsStringMoc)) {
  526. this->MocSettingsChanged = true;
  527. }
  528. if (!SettingsMatch(makefile, SettingsKeyUic, this->SettingsStringUic)) {
  529. this->UicSettingsChanged = true;
  530. }
  531. if (!SettingsMatch(makefile, SettingsKeyRcc, this->SettingsStringRcc)) {
  532. this->RccSettingsChanged = true;
  533. }
  534. // In case any setting changed remove the old settings file.
  535. // This triggers a full rebuild on the next run if the current
  536. // build is aborted before writing the current settings in the end.
  537. if (this->AnySettingsChanged()) {
  538. cmSystemTools::RemoveFile(this->SettingsFile);
  539. }
  540. } else {
  541. // If the file could not be read re-generate everythiung.
  542. this->MocSettingsChanged = true;
  543. this->UicSettingsChanged = true;
  544. this->RccSettingsChanged = true;
  545. }
  546. }
  547. bool cmQtAutoGenerators::SettingsFileWrite()
  548. {
  549. bool success = true;
  550. // Only write if any setting changed
  551. if (this->AnySettingsChanged()) {
  552. if (this->Verbose) {
  553. this->LogInfo("AutoGen: Writing settings file " +
  554. Quoted(this->SettingsFile));
  555. }
  556. // Compose settings file content
  557. std::string settings;
  558. SettingAppend(settings, SettingsKeyMoc, this->SettingsStringMoc);
  559. SettingAppend(settings, SettingsKeyUic, this->SettingsStringUic);
  560. SettingAppend(settings, SettingsKeyRcc, this->SettingsStringRcc);
  561. // Write settings file
  562. if (!this->FileWrite(cmQtAutoGen::GEN, this->SettingsFile, settings)) {
  563. this->LogError("AutoGen: Error: Could not write old settings file " +
  564. Quoted(this->SettingsFile));
  565. // Remove old settings file to trigger a full rebuild on the next run
  566. cmSystemTools::RemoveFile(this->SettingsFile);
  567. success = false;
  568. }
  569. }
  570. return success;
  571. }
  572. void cmQtAutoGenerators::Init(cmMakefile* makefile)
  573. {
  574. // Mocs compilation file
  575. this->MocCompFileRel = "mocs_compilation.cpp";
  576. this->MocCompFileAbs = cmSystemTools::CollapseCombinedPath(
  577. this->AutogenBuildDir, this->MocCompFileRel);
  578. // Mocs include directory
  579. this->AutogenIncludeDir = "include";
  580. this->AutogenIncludeDir += this->ConfigSuffix;
  581. this->AutogenIncludeDir += "/";
  582. // Moc predefs file
  583. if (!this->MocPredefsCmd.empty()) {
  584. this->MocPredefsFileRel = "moc_predefs";
  585. this->MocPredefsFileRel += this->ConfigSuffix;
  586. this->MocPredefsFileRel += ".h";
  587. this->MocPredefsFileAbs = cmSystemTools::CollapseCombinedPath(
  588. this->AutogenBuildDir, this->MocPredefsFileRel);
  589. }
  590. // Init file path checksum generator
  591. FPathChecksum.setupParentDirs(this->CurrentSourceDir, this->CurrentBinaryDir,
  592. this->ProjectSourceDir,
  593. this->ProjectBinaryDir);
  594. // Acquire header extensions
  595. this->HeaderExtensions = makefile->GetCMakeInstance()->GetHeaderExtensions();
  596. // Sort include directories on demand
  597. if (this->IncludeProjectDirsBefore) {
  598. // Move strings to temporary list
  599. std::list<std::string> includes;
  600. includes.insert(includes.end(), this->MocIncludePaths.begin(),
  601. this->MocIncludePaths.end());
  602. this->MocIncludePaths.clear();
  603. this->MocIncludePaths.reserve(includes.size());
  604. // Append project directories only
  605. {
  606. const std::array<const std::string*, 2> movePaths = {
  607. { &this->ProjectBinaryDir, &this->ProjectSourceDir }
  608. };
  609. for (const std::string* ppath : movePaths) {
  610. std::list<std::string>::iterator it = includes.begin();
  611. while (it != includes.end()) {
  612. const std::string& path = *it;
  613. if (cmSystemTools::StringStartsWith(path, ppath->c_str())) {
  614. this->MocIncludePaths.push_back(path);
  615. it = includes.erase(it);
  616. } else {
  617. ++it;
  618. }
  619. }
  620. }
  621. }
  622. // Append remaining directories
  623. this->MocIncludePaths.insert(this->MocIncludePaths.end(), includes.begin(),
  624. includes.end());
  625. }
  626. // Compose moc includes list
  627. {
  628. std::set<std::string> frameworkPaths;
  629. for (const std::string& path : this->MocIncludePaths) {
  630. this->MocIncludes.push_back("-I" + path);
  631. // Extract framework path
  632. if (cmHasLiteralSuffix(path, ".framework/Headers")) {
  633. // Go up twice to get to the framework root
  634. std::vector<std::string> pathComponents;
  635. cmsys::SystemTools::SplitPath(path, pathComponents);
  636. std::string frameworkPath = cmsys::SystemTools::JoinPath(
  637. pathComponents.begin(), pathComponents.end() - 2);
  638. frameworkPaths.insert(frameworkPath);
  639. }
  640. }
  641. // Append framework includes
  642. for (const std::string& path : frameworkPaths) {
  643. this->MocIncludes.push_back("-F");
  644. this->MocIncludes.push_back(path);
  645. }
  646. }
  647. }
  648. bool cmQtAutoGenerators::RunAutogen()
  649. {
  650. // the program goes through all .cpp files to see which moc files are
  651. // included. It is not really interesting how the moc file is named, but
  652. // what file the moc is created from. Once a moc is included the same moc
  653. // may not be included in the mocs_compilation.cpp file anymore.
  654. // OTOH if there's a header containing Q_OBJECT where no corresponding
  655. // moc file is included anywhere a moc_<filename>.cpp file is created and
  656. // included in the mocs_compilation.cpp file.
  657. // Create AUTOGEN include directory
  658. {
  659. const std::string incDirAbs = cmSystemTools::CollapseCombinedPath(
  660. this->AutogenBuildDir, this->AutogenIncludeDir);
  661. if (!cmsys::SystemTools::MakeDirectory(incDirAbs)) {
  662. this->LogError("AutoGen: Error: Could not create include directory " +
  663. Quoted(incDirAbs));
  664. return false;
  665. }
  666. }
  667. // key = moc source filepath, value = moc output filepath
  668. std::map<std::string, std::string> mocsIncluded;
  669. std::map<std::string, std::string> mocsNotIncluded;
  670. std::map<std::string, std::set<std::string>> mocDepends;
  671. std::map<std::string, std::vector<std::string>> uisIncluded;
  672. // collects all headers which may need to be mocced
  673. std::set<std::string> mocHeaderFiles;
  674. std::set<std::string> uicHeaderFiles;
  675. // Parse sources
  676. for (const std::string& src : this->Sources) {
  677. // Parse source file for MOC/UIC
  678. if (!this->ParseSourceFile(src, mocsIncluded, mocDepends, uisIncluded,
  679. this->MocRelaxedMode)) {
  680. return false;
  681. }
  682. // Find additional headers
  683. this->SearchHeadersForSourceFile(src, mocHeaderFiles, uicHeaderFiles);
  684. }
  685. // Parse headers
  686. for (const std::string& hdr : this->Headers) {
  687. if (!this->MocSkip(hdr)) {
  688. mocHeaderFiles.insert(hdr);
  689. }
  690. if (!this->UicSkip(hdr)) {
  691. uicHeaderFiles.insert(hdr);
  692. }
  693. }
  694. if (!this->ParseHeaders(mocHeaderFiles, uicHeaderFiles, mocsIncluded,
  695. mocsNotIncluded, mocDepends, uisIncluded)) {
  696. return false;
  697. };
  698. // Generate files
  699. if (!this->MocGenerateAll(mocsIncluded, mocsNotIncluded, mocDepends)) {
  700. return false;
  701. }
  702. if (!this->UicGenerateAll(uisIncluded)) {
  703. return false;
  704. }
  705. if (!this->RccGenerateAll()) {
  706. return false;
  707. }
  708. return true;
  709. }
  710. /**
  711. * @brief Tests if the C++ content requires moc processing
  712. * @return True if moc is required
  713. */
  714. bool cmQtAutoGenerators::MocRequired(const std::string& contentText,
  715. std::string* macroName)
  716. {
  717. for (MocMacroFilter& filter : this->MocMacroFilters) {
  718. // Run a simple find string operation before the expensive
  719. // regular expression check
  720. if (contentText.find(filter.first) != std::string::npos) {
  721. if (filter.second.find(contentText)) {
  722. // Return macro name on demand
  723. if (macroName != nullptr) {
  724. *macroName = filter.first;
  725. }
  726. return true;
  727. }
  728. }
  729. }
  730. return false;
  731. }
  732. void cmQtAutoGenerators::MocFindDepends(
  733. const std::string& absFilename, const std::string& contentText,
  734. std::map<std::string, std::set<std::string>>& mocDepends)
  735. {
  736. for (MocDependFilter& filter : this->MocDependFilters) {
  737. // Run a simple find string operation before the expensive
  738. // regular expression check
  739. if (contentText.find(filter.key) != std::string::npos) {
  740. // Run regular expression check loop
  741. const std::string sourcePath = SubDirPrefix(absFilename);
  742. const char* contentChars = contentText.c_str();
  743. while (filter.regExp.find(contentChars)) {
  744. // Evaluate match
  745. const std::string match = filter.regExp.match(1);
  746. if (!match.empty()) {
  747. // Find the dependency file
  748. std::string incFile;
  749. if (this->MocFindIncludedFile(incFile, sourcePath, match)) {
  750. mocDepends[absFilename].insert(incFile);
  751. if (this->Verbose) {
  752. this->LogInfo("AutoMoc: Found dependency:\n " +
  753. Quoted(absFilename) + "\n " + Quoted(incFile));
  754. }
  755. } else {
  756. this->LogWarning("AutoMoc: Warning: " + Quoted(absFilename) +
  757. "\n" + "Could not find dependency file " +
  758. Quoted(match));
  759. }
  760. }
  761. contentChars += filter.regExp.end();
  762. }
  763. }
  764. }
  765. }
  766. /**
  767. * @brief Tests if the file should be ignored for moc scanning
  768. * @return True if the file should be ignored
  769. */
  770. bool cmQtAutoGenerators::MocSkip(const std::string& absFilename) const
  771. {
  772. if (this->MocEnabled()) {
  773. // Test if the file name is on the skip list
  774. if (!ListContains(this->MocSkipList, absFilename)) {
  775. return false;
  776. }
  777. }
  778. return true;
  779. }
  780. /**
  781. * @brief Tests if the file name is in the skip list
  782. */
  783. bool cmQtAutoGenerators::UicSkip(const std::string& absFilename) const
  784. {
  785. if (this->UicEnabled()) {
  786. // Test if the file name is on the skip list
  787. if (!ListContains(this->UicSkipList, absFilename)) {
  788. return false;
  789. }
  790. }
  791. return true;
  792. }
  793. /**
  794. * @return True on success
  795. */
  796. bool cmQtAutoGenerators::ParseSourceFile(
  797. const std::string& absFilename,
  798. std::map<std::string, std::string>& mocsIncluded,
  799. std::map<std::string, std::set<std::string>>& mocDepends,
  800. std::map<std::string, std::vector<std::string>>& uisIncluded, bool relaxed)
  801. {
  802. std::string contentText;
  803. bool success = ReadAll(contentText, absFilename);
  804. if (success) {
  805. if (!contentText.empty()) {
  806. // Parse source contents for MOC
  807. if (success && !this->MocSkip(absFilename)) {
  808. success = this->MocParseSourceContent(
  809. absFilename, contentText, mocsIncluded, mocDepends, relaxed);
  810. }
  811. // Parse source contents for UIC
  812. if (success && !this->UicSkip(absFilename)) {
  813. this->UicParseContent(absFilename, contentText, uisIncluded);
  814. }
  815. } else {
  816. std::ostringstream ost;
  817. ost << "AutoGen: Warning: The file is empty:\n"
  818. << Quoted(absFilename) << "\n";
  819. this->LogWarning(ost.str());
  820. }
  821. } else {
  822. std::ostringstream ost;
  823. ost << "AutoGen: Error: Could not read file:\n" << Quoted(absFilename);
  824. this->LogError(ost.str());
  825. }
  826. return success;
  827. }
  828. void cmQtAutoGenerators::UicParseContent(
  829. const std::string& absFilename, const std::string& contentText,
  830. std::map<std::string, std::vector<std::string>>& uisIncluded)
  831. {
  832. if (this->Verbose) {
  833. this->LogInfo("AutoUic: Checking " + absFilename);
  834. }
  835. const char* contentChars = contentText.c_str();
  836. if (strstr(contentChars, "ui_") != nullptr) {
  837. while (this->UicRegExpInclude.find(contentChars)) {
  838. uisIncluded[absFilename].push_back(this->UicRegExpInclude.match(1));
  839. contentChars += this->UicRegExpInclude.end();
  840. }
  841. }
  842. }
  843. /**
  844. * @return True on success
  845. */
  846. bool cmQtAutoGenerators::MocParseSourceContent(
  847. const std::string& absFilename, const std::string& contentText,
  848. std::map<std::string, std::string>& mocsIncluded,
  849. std::map<std::string, std::set<std::string>>& mocDepends, bool relaxed)
  850. {
  851. if (this->Verbose) {
  852. this->LogInfo("AutoMoc: Checking " + absFilename);
  853. }
  854. const std::string scannedFileAbsPath = SubDirPrefix(absFilename);
  855. const std::string scannedFileBasename =
  856. cmsys::SystemTools::GetFilenameWithoutLastExtension(absFilename);
  857. std::string macroName;
  858. const bool requiresMoc = this->MocRequired(contentText, &macroName);
  859. bool ownDotMocIncluded = false;
  860. std::string ownMocUnderscoreInclude;
  861. std::string ownMocUnderscoreHeader;
  862. // first a simple string check for "moc" is *much* faster than the regexp,
  863. // and if the string search already fails, we don't have to try the
  864. // expensive regexp
  865. const char* contentChars = contentText.c_str();
  866. if (strstr(contentChars, "moc") != nullptr) {
  867. // Iterate over all included moc files
  868. while (this->MocRegExpInclude.find(contentChars)) {
  869. const std::string incString = this->MocRegExpInclude.match(1);
  870. // Basename of the moc include
  871. const std::string incSubDir(SubDirPrefix(incString));
  872. const std::string incBasename =
  873. cmsys::SystemTools::GetFilenameWithoutLastExtension(incString);
  874. // If the moc include is of the moc_foo.cpp style we expect
  875. // the Q_OBJECT class declaration in a header file.
  876. // If the moc include is of the foo.moc style we need to look for
  877. // a Q_OBJECT macro in the current source file, if it contains the
  878. // macro we generate the moc file from the source file.
  879. if (cmHasLiteralPrefix(incBasename, "moc_")) {
  880. // Include: moc_FOO.cxx
  881. // Remove the moc_ part
  882. const std::string incRealBasename = incBasename.substr(4);
  883. const std::string headerToMoc =
  884. this->MocFindHeader(scannedFileAbsPath, incSubDir + incRealBasename);
  885. if (!headerToMoc.empty()) {
  886. if (!this->MocSkip(headerToMoc)) {
  887. // Register moc job
  888. mocsIncluded[headerToMoc] = incString;
  889. this->MocFindDepends(headerToMoc, contentText, mocDepends);
  890. // Store meta information for relaxed mode
  891. if (relaxed && (incRealBasename == scannedFileBasename)) {
  892. ownMocUnderscoreInclude = incString;
  893. ownMocUnderscoreHeader = headerToMoc;
  894. }
  895. }
  896. } else {
  897. std::ostringstream ost;
  898. ost << "AutoMoc: Error: " << Quoted(absFilename) << "\n"
  899. << "The file includes the moc file " << Quoted(incString)
  900. << ", but could not find header "
  901. << Quoted(incRealBasename + ".{" +
  902. cmJoin(this->HeaderExtensions, ",") + "}");
  903. this->LogError(ost.str());
  904. return false;
  905. }
  906. } else {
  907. // Include: FOO.moc
  908. std::string fileToMoc;
  909. if (relaxed) {
  910. // Mode: Relaxed
  911. if (requiresMoc && (incBasename == scannedFileBasename)) {
  912. // Include self
  913. fileToMoc = absFilename;
  914. ownDotMocIncluded = true;
  915. } else {
  916. // In relaxed mode try to find a header instead but issue a warning
  917. const std::string headerToMoc =
  918. this->MocFindHeader(scannedFileAbsPath, incSubDir + incBasename);
  919. if (!headerToMoc.empty()) {
  920. if (!this->MocSkip(headerToMoc)) {
  921. // This is for KDE4 compatibility:
  922. fileToMoc = headerToMoc;
  923. if (!requiresMoc && (incBasename == scannedFileBasename)) {
  924. std::ostringstream ost;
  925. ost
  926. << "AutoMoc: Warning: " << Quoted(absFilename) << "\n"
  927. << "The file includes the moc file " << Quoted(incString)
  928. << ", but does not contain a Q_OBJECT or Q_GADGET macro.\n"
  929. << "Running moc on " << Quoted(headerToMoc) << "!\n"
  930. << "Include " << Quoted("moc_" + incBasename + ".cpp")
  931. << " for a compatibility with strict mode (see "
  932. "CMAKE_AUTOMOC_RELAXED_MODE).\n";
  933. this->LogWarning(ost.str());
  934. } else {
  935. std::ostringstream ost;
  936. ost << "AutoMoc: Warning: " << Quoted(absFilename) << "\n"
  937. << "The file includes the moc file " << Quoted(incString)
  938. << " instead of "
  939. << Quoted("moc_" + incBasename + ".cpp") << ".\n"
  940. << "Running moc on " << Quoted(headerToMoc) << "!\n"
  941. << "Include " << Quoted("moc_" + incBasename + ".cpp")
  942. << " for compatibility with strict mode (see "
  943. "CMAKE_AUTOMOC_RELAXED_MODE).\n";
  944. this->LogWarning(ost.str());
  945. }
  946. }
  947. } else {
  948. std::ostringstream ost;
  949. ost << "AutoMoc: Error: " << Quoted(absFilename) << "\n"
  950. << "The file includes the moc file " << Quoted(incString)
  951. << ", which seems to be the moc file from a different "
  952. "source file. CMake also could not find a matching "
  953. "header.";
  954. this->LogError(ost.str());
  955. return false;
  956. }
  957. }
  958. } else {
  959. // Mode: Strict
  960. if (incBasename == scannedFileBasename) {
  961. // Include self
  962. fileToMoc = absFilename;
  963. ownDotMocIncluded = true;
  964. // Accept but issue a warning if moc isn't required
  965. if (!requiresMoc) {
  966. std::ostringstream ost;
  967. ost << "AutoMoc: Warning: " << Quoted(absFilename) << "\n"
  968. << "The file includes the moc file " << Quoted(incString)
  969. << ", but does not contain a Q_OBJECT or Q_GADGET "
  970. "macro.";
  971. this->LogWarning(ost.str());
  972. }
  973. } else {
  974. // Don't allow FOO.moc include other than self in strict mode
  975. std::ostringstream ost;
  976. ost << "AutoMoc: Error: " << Quoted(absFilename) << "\n"
  977. << "The file includes the moc file " << Quoted(incString)
  978. << ", which seems to be the moc file from a different "
  979. "source file. This is not supported. Include "
  980. << Quoted(scannedFileBasename + ".moc")
  981. << " to run moc on this source file.";
  982. this->LogError(ost.str());
  983. return false;
  984. }
  985. }
  986. if (!fileToMoc.empty()) {
  987. mocsIncluded[fileToMoc] = incString;
  988. this->MocFindDepends(fileToMoc, contentText, mocDepends);
  989. }
  990. }
  991. // Forward content pointer
  992. contentChars += this->MocRegExpInclude.end();
  993. }
  994. }
  995. if (requiresMoc && !ownDotMocIncluded) {
  996. // In this case, check whether the scanned file itself contains a Q_OBJECT.
  997. // If this is the case, the moc_foo.cpp should probably be generated from
  998. // foo.cpp instead of foo.h, because otherwise it won't build.
  999. // But warn, since this is not how it is supposed to be used.
  1000. if (relaxed && !ownMocUnderscoreInclude.empty()) {
  1001. // This is for KDE4 compatibility:
  1002. std::ostringstream ost;
  1003. ost << "AutoMoc: Warning: " << Quoted(absFilename) << "\n"
  1004. << "The file contains a " << macroName
  1005. << " macro, but does not include "
  1006. << Quoted(scannedFileBasename + ".moc") << ", but instead includes "
  1007. << Quoted(ownMocUnderscoreInclude) << ".\n"
  1008. << "Running moc on " << Quoted(absFilename) << "!\n"
  1009. << "Better include " << Quoted(scannedFileBasename + ".moc")
  1010. << " for compatibility with strict mode (see "
  1011. "CMAKE_AUTOMOC_RELAXED_MODE).";
  1012. this->LogWarning(ost.str());
  1013. // Use scanned source file instead of scanned header file as moc source
  1014. mocsIncluded[absFilename] = ownMocUnderscoreInclude;
  1015. this->MocFindDepends(absFilename, contentText, mocDepends);
  1016. // Remove
  1017. mocsIncluded.erase(ownMocUnderscoreHeader);
  1018. } else {
  1019. // Otherwise always error out since it will not compile:
  1020. std::ostringstream ost;
  1021. ost << "AutoMoc: Error: " << Quoted(absFilename) << "\n"
  1022. << "The file contains a " << macroName
  1023. << " macro, but does not include "
  1024. << Quoted(scannedFileBasename + ".moc") << "!\n"
  1025. << "Consider adding the include or enabling SKIP_AUTOMOC for this "
  1026. "file.";
  1027. this->LogError(ost.str());
  1028. return false;
  1029. }
  1030. }
  1031. return true;
  1032. }
  1033. void cmQtAutoGenerators::MocParseHeaderContent(
  1034. const std::string& absFilename, const std::string& contentText,
  1035. std::map<std::string, std::string>& mocsNotIncluded,
  1036. std::map<std::string, std::set<std::string>>& mocDepends)
  1037. {
  1038. // Log
  1039. if (this->Verbose) {
  1040. this->LogInfo("AutoMoc: Checking " + absFilename);
  1041. }
  1042. if (this->MocRequired(contentText)) {
  1043. // Register moc job
  1044. mocsNotIncluded[absFilename] =
  1045. this->ChecksumedPath(absFilename, "moc_", this->ConfigSuffix + ".cpp");
  1046. this->MocFindDepends(absFilename, contentText, mocDepends);
  1047. }
  1048. }
  1049. void cmQtAutoGenerators::SearchHeadersForSourceFile(
  1050. const std::string& absFilename, std::set<std::string>& mocHeaderFiles,
  1051. std::set<std::string>& uicHeaderFiles) const
  1052. {
  1053. std::array<std::string, 2> basepaths;
  1054. {
  1055. std::string bpath = SubDirPrefix(absFilename);
  1056. bpath += cmsys::SystemTools::GetFilenameWithoutLastExtension(absFilename);
  1057. // search for default header files and private header files
  1058. basepaths[0] = bpath;
  1059. basepaths[1] = bpath;
  1060. basepaths[1] += "_p";
  1061. }
  1062. for (const std::string& bPath : basepaths) {
  1063. std::string headerName;
  1064. if (this->FindHeader(headerName, bPath)) {
  1065. // Moc headers
  1066. if (!this->MocSkip(absFilename) && !this->MocSkip(headerName)) {
  1067. mocHeaderFiles.insert(headerName);
  1068. }
  1069. // Uic headers
  1070. if (!this->UicSkip(absFilename) && !this->UicSkip(headerName)) {
  1071. uicHeaderFiles.insert(headerName);
  1072. }
  1073. }
  1074. }
  1075. }
  1076. bool cmQtAutoGenerators::ParseHeaders(
  1077. const std::set<std::string>& mocHeaderFiles,
  1078. const std::set<std::string>& uicHeaderFiles,
  1079. const std::map<std::string, std::string>& mocsIncluded,
  1080. std::map<std::string, std::string>& mocsNotIncluded,
  1081. std::map<std::string, std::set<std::string>>& mocDepends,
  1082. std::map<std::string, std::vector<std::string>>& uisIncluded)
  1083. {
  1084. bool success = true;
  1085. // Merged header files list to read files only once
  1086. std::set<std::string> headerFiles;
  1087. headerFiles.insert(mocHeaderFiles.begin(), mocHeaderFiles.end());
  1088. headerFiles.insert(uicHeaderFiles.begin(), uicHeaderFiles.end());
  1089. for (const std::string& headerName : headerFiles) {
  1090. std::string contentText;
  1091. if (ReadAll(contentText, headerName)) {
  1092. // Parse header content for MOC
  1093. if ((mocHeaderFiles.find(headerName) != mocHeaderFiles.end()) &&
  1094. (mocsIncluded.find(headerName) == mocsIncluded.end())) {
  1095. this->MocParseHeaderContent(headerName, contentText, mocsNotIncluded,
  1096. mocDepends);
  1097. }
  1098. // Parse header content for UIC
  1099. if (uicHeaderFiles.find(headerName) != uicHeaderFiles.end()) {
  1100. this->UicParseContent(headerName, contentText, uisIncluded);
  1101. }
  1102. } else {
  1103. std::ostringstream ost;
  1104. ost << "AutoGen: Error: Could not read header file:\n"
  1105. << Quoted(headerName);
  1106. this->LogError(ost.str());
  1107. success = false;
  1108. break;
  1109. }
  1110. }
  1111. return success;
  1112. }
  1113. bool cmQtAutoGenerators::MocGenerateAll(
  1114. const std::map<std::string, std::string>& mocsIncluded,
  1115. const std::map<std::string, std::string>& mocsNotIncluded,
  1116. const std::map<std::string, std::set<std::string>>& mocDepends)
  1117. {
  1118. if (!this->MocEnabled()) {
  1119. return true;
  1120. }
  1121. // Look for name collisions
  1122. {
  1123. std::multimap<std::string, std::string> collisions;
  1124. // Test merged map of included and notIncluded
  1125. std::map<std::string, std::string> mergedMocs(mocsIncluded);
  1126. mergedMocs.insert(mocsNotIncluded.begin(), mocsNotIncluded.end());
  1127. if (this->NameCollisionTest(mergedMocs, collisions)) {
  1128. std::ostringstream ost;
  1129. ost << "AutoMoc: Error: "
  1130. "The same moc file will be generated "
  1131. "from different sources.\n"
  1132. "To avoid this error either\n"
  1133. "- rename the source files or\n"
  1134. "- do not include the (moc_NAME.cpp|NAME.moc) file";
  1135. this->LogErrorNameCollision(ost.str(), collisions);
  1136. return false;
  1137. }
  1138. }
  1139. // Generate moc_predefs
  1140. if (!this->MocPredefsCmd.empty()) {
  1141. if (this->MocSettingsChanged ||
  1142. FileAbsentOrOlder(this->MocPredefsFileAbs, this->SettingsFile)) {
  1143. if (this->Verbose) {
  1144. this->LogBold("Generating MOC predefs " + this->MocPredefsFileRel);
  1145. }
  1146. std::string output;
  1147. {
  1148. // Compose command
  1149. std::vector<std::string> cmd = this->MocPredefsCmd;
  1150. // Add includes
  1151. cmd.insert(cmd.end(), this->MocIncludes.begin(),
  1152. this->MocIncludes.end());
  1153. // Add definitions
  1154. for (const std::string& def : this->MocDefinitions) {
  1155. cmd.push_back("-D" + def);
  1156. }
  1157. // Add options
  1158. cmd.insert(cmd.end(), this->MocOptions.begin(),
  1159. this->MocOptions.end());
  1160. // Execute command
  1161. if (!this->RunCommand(cmd, output, false)) {
  1162. {
  1163. std::ostringstream ost;
  1164. ost << "AutoMoc: Error: moc predefs generation command failed\n";
  1165. ost << "AutoMoc: Command:\n" << QuotedCommand(cmd) << "\n";
  1166. ost << "AutoMoc: Command output:\n" << output << "\n";
  1167. this->LogError(ost.str());
  1168. }
  1169. return false;
  1170. }
  1171. }
  1172. // (Re)write predefs file only on demand
  1173. if (this->FileDiffers(this->MocPredefsFileAbs, output)) {
  1174. if (this->FileWrite(cmQtAutoGen::MOC, this->MocPredefsFileAbs,
  1175. output)) {
  1176. this->MocPredefsChanged = true;
  1177. } else {
  1178. return false;
  1179. }
  1180. }
  1181. }
  1182. }
  1183. // Generate moc files that are included by source files.
  1184. for (std::map<std::string, std::string>::const_iterator it =
  1185. mocsIncluded.begin();
  1186. it != mocsIncluded.end(); ++it) {
  1187. if (!this->MocGenerateFile(it->first, it->second, mocDepends, true)) {
  1188. if (this->MocRunFailed) {
  1189. return false;
  1190. }
  1191. }
  1192. }
  1193. // Generate moc files that are _not_ included by source files.
  1194. bool mocCompFileGenerated = false;
  1195. for (std::map<std::string, std::string>::const_iterator it =
  1196. mocsNotIncluded.begin();
  1197. it != mocsNotIncluded.end(); ++it) {
  1198. if (this->MocGenerateFile(it->first, it->second, mocDepends, false)) {
  1199. mocCompFileGenerated = true;
  1200. } else {
  1201. if (this->MocRunFailed) {
  1202. return false;
  1203. }
  1204. }
  1205. }
  1206. // Compose mocs compilation file content
  1207. std::string automocSource;
  1208. {
  1209. std::ostringstream ost;
  1210. ost << "/* This file is autogenerated, do not edit*/\n";
  1211. if (mocsNotIncluded.empty()) {
  1212. // Dummy content
  1213. ost << "enum some_compilers { need_more_than_nothing };\n";
  1214. } else {
  1215. // Valid content
  1216. for (std::map<std::string, std::string>::const_iterator it =
  1217. mocsNotIncluded.begin();
  1218. it != mocsNotIncluded.end(); ++it) {
  1219. ost << "#include \"" << it->second << "\"\n";
  1220. }
  1221. }
  1222. automocSource = ost.str();
  1223. }
  1224. if (this->FileDiffers(this->MocCompFileAbs, automocSource)) {
  1225. // Actually write mocs compilation file
  1226. if (this->Verbose) {
  1227. this->LogBold("Generating MOC compilation " + this->MocCompFileRel);
  1228. }
  1229. if (!this->FileWrite(cmQtAutoGen::MOC, this->MocCompFileAbs,
  1230. automocSource)) {
  1231. return false;
  1232. }
  1233. } else if (mocCompFileGenerated) {
  1234. // Only touch mocs compilation file
  1235. if (this->Verbose) {
  1236. this->LogInfo("Touching MOC compilation " + this->MocCompFileRel);
  1237. }
  1238. cmSystemTools::Touch(this->MocCompFileAbs, false);
  1239. }
  1240. return true;
  1241. }
  1242. /**
  1243. * @return True if a moc file was created. False may indicate an error.
  1244. */
  1245. bool cmQtAutoGenerators::MocGenerateFile(
  1246. const std::string& sourceFile, const std::string& mocFileName,
  1247. const std::map<std::string, std::set<std::string>>& mocDepends,
  1248. bool included)
  1249. {
  1250. bool mocGenerated = false;
  1251. bool generateMoc = this->MocSettingsChanged || this->MocPredefsChanged;
  1252. const std::string mocFileRel =
  1253. included ? (this->AutogenIncludeDir + mocFileName) : mocFileName;
  1254. const std::string mocFileAbs =
  1255. cmSystemTools::CollapseCombinedPath(this->AutogenBuildDir, mocFileRel);
  1256. if (!generateMoc) {
  1257. // Test if the source file is newer that the build file
  1258. generateMoc = FileAbsentOrOlder(mocFileAbs, sourceFile);
  1259. if (!generateMoc) {
  1260. // Test if a dependency file changed
  1261. std::map<std::string, std::set<std::string>>::const_iterator dit =
  1262. mocDepends.find(sourceFile);
  1263. if (dit != mocDepends.end()) {
  1264. for (std::set<std::string>::const_iterator fit = dit->second.begin();
  1265. fit != dit->second.end(); ++fit) {
  1266. if (FileAbsentOrOlder(mocFileAbs, *fit)) {
  1267. generateMoc = true;
  1268. break;
  1269. }
  1270. }
  1271. }
  1272. }
  1273. }
  1274. if (generateMoc) {
  1275. // Log
  1276. if (this->Verbose) {
  1277. this->LogBold("Generating MOC source " + mocFileRel);
  1278. }
  1279. // Make sure the parent directory exists
  1280. if (this->MakeParentDirectory(cmQtAutoGen::MOC, mocFileAbs)) {
  1281. // Compose moc command
  1282. std::vector<std::string> cmd;
  1283. cmd.push_back(this->MocExecutable);
  1284. // Add includes
  1285. cmd.insert(cmd.end(), this->MocIncludes.begin(),
  1286. this->MocIncludes.end());
  1287. // Add definitions
  1288. for (const std::string& def : this->MocDefinitions) {
  1289. cmd.push_back("-D" + def);
  1290. }
  1291. // Add options
  1292. cmd.insert(cmd.end(), this->MocOptions.begin(), this->MocOptions.end());
  1293. // Add predefs include
  1294. if (!this->MocPredefsFileAbs.empty()) {
  1295. cmd.push_back("--include");
  1296. cmd.push_back(this->MocPredefsFileAbs);
  1297. }
  1298. cmd.push_back("-o");
  1299. cmd.push_back(mocFileAbs);
  1300. cmd.push_back(sourceFile);
  1301. // Execute moc command
  1302. std::string output;
  1303. if (this->RunCommand(cmd, output)) {
  1304. // Success
  1305. mocGenerated = true;
  1306. } else {
  1307. // Command failed
  1308. {
  1309. std::ostringstream ost;
  1310. ost << "AutoMoc: Error: moc process failed for\n";
  1311. ost << Quoted(mocFileRel) << "\n";
  1312. ost << "AutoMoc: Command:\n" << QuotedCommand(cmd) << "\n";
  1313. ost << "AutoMoc: Command output:\n" << output << "\n";
  1314. this->LogError(ost.str());
  1315. }
  1316. cmSystemTools::RemoveFile(mocFileAbs);
  1317. this->MocRunFailed = true;
  1318. }
  1319. } else {
  1320. // Parent directory creation failed
  1321. this->MocRunFailed = true;
  1322. }
  1323. }
  1324. return mocGenerated;
  1325. }
  1326. bool cmQtAutoGenerators::UicFindIncludedFile(std::string& absFile,
  1327. const std::string& sourceFile,
  1328. const std::string& searchPath,
  1329. const std::string& searchFile)
  1330. {
  1331. bool success = false;
  1332. std::vector<std::string> testFiles;
  1333. // Collect search paths list
  1334. {
  1335. std::string searchFileFull;
  1336. if (!searchPath.empty()) {
  1337. searchFileFull = searchPath;
  1338. searchFileFull += searchFile;
  1339. }
  1340. // Vicinity of the source
  1341. {
  1342. const std::string sourcePath = SubDirPrefix(sourceFile);
  1343. testFiles.push_back(sourcePath + searchFile);
  1344. if (!searchPath.empty()) {
  1345. testFiles.push_back(sourcePath + searchFileFull);
  1346. }
  1347. }
  1348. // AUTOUIC search paths
  1349. if (!this->UicSearchPaths.empty()) {
  1350. for (const std::string& sPath : this->UicSearchPaths) {
  1351. testFiles.push_back((sPath + "/").append(searchFile));
  1352. }
  1353. if (!searchPath.empty()) {
  1354. for (const std::string& sPath : this->UicSearchPaths) {
  1355. testFiles.push_back((sPath + "/").append(searchFileFull));
  1356. }
  1357. }
  1358. }
  1359. }
  1360. // Search for the .ui file!
  1361. for (const std::string& testFile : testFiles) {
  1362. if (cmsys::SystemTools::FileExists(testFile.c_str())) {
  1363. absFile = cmsys::SystemTools::GetRealPath(testFile);
  1364. success = true;
  1365. break;
  1366. }
  1367. }
  1368. // Log error
  1369. if (!success) {
  1370. std::ostringstream ost;
  1371. ost << "AutoUic: Error: " << Quoted(sourceFile) << "\n";
  1372. ost << "Could not find " << Quoted(searchFile) << " in\n";
  1373. for (const std::string& testFile : testFiles) {
  1374. ost << " " << Quoted(testFile) << "\n";
  1375. }
  1376. this->LogError(ost.str());
  1377. }
  1378. return success;
  1379. }
  1380. bool cmQtAutoGenerators::UicGenerateAll(
  1381. const std::map<std::string, std::vector<std::string>>& uisIncluded)
  1382. {
  1383. if (!this->UicEnabled()) {
  1384. return true;
  1385. }
  1386. // single map with input / output names
  1387. std::map<std::string, std::map<std::string, std::string>> sourceGenMap;
  1388. {
  1389. // Collision lookup map
  1390. std::map<std::string, std::string> testMap;
  1391. // Compile maps
  1392. for (std::map<std::string, std::vector<std::string>>::const_iterator sit =
  1393. uisIncluded.begin();
  1394. sit != uisIncluded.end(); ++sit) {
  1395. const std::string& source(sit->first);
  1396. const std::vector<std::string>& sourceIncs(sit->second);
  1397. // insert new source/destination map
  1398. std::map<std::string, std::string>& uiGenMap = sourceGenMap[source];
  1399. for (const std::string& inc : sourceIncs) {
  1400. // Remove ui_ from the begin filename by substr()
  1401. const std::string uiBasePath = SubDirPrefix(inc);
  1402. const std::string uiBaseName =
  1403. cmsys::SystemTools::GetFilenameWithoutLastExtension(inc).substr(3);
  1404. const std::string uiFileName = uiBaseName + ".ui";
  1405. std::string uiInputFile;
  1406. if (UicFindIncludedFile(uiInputFile, source, uiBasePath, uiFileName)) {
  1407. std::string uiOutputFile = uiBasePath;
  1408. uiOutputFile += "ui_";
  1409. uiOutputFile += uiBaseName;
  1410. uiOutputFile += ".h";
  1411. cmSystemTools::ReplaceString(uiOutputFile, "..", "__");
  1412. uiGenMap[uiInputFile] = uiOutputFile;
  1413. testMap[uiInputFile] = uiOutputFile;
  1414. } else {
  1415. return false;
  1416. }
  1417. }
  1418. }
  1419. // look for name collisions
  1420. {
  1421. std::multimap<std::string, std::string> collisions;
  1422. if (this->NameCollisionTest(testMap, collisions)) {
  1423. std::ostringstream ost;
  1424. ost << "AutoUic: Error: The same ui_NAME.h file will be generated "
  1425. "from different sources.\n"
  1426. "To avoid this error rename the source files.\n";
  1427. this->LogErrorNameCollision(ost.str(), collisions);
  1428. return false;
  1429. }
  1430. }
  1431. }
  1432. // generate ui files
  1433. for (const auto& srcItem : sourceGenMap) {
  1434. for (const auto& item : srcItem.second) {
  1435. if (!this->UicGenerateFile(srcItem.first, item.first, item.second)) {
  1436. if (this->UicRunFailed) {
  1437. return false;
  1438. }
  1439. }
  1440. }
  1441. }
  1442. return true;
  1443. }
  1444. /**
  1445. * @return True if a uic file was created. False may indicate an error.
  1446. */
  1447. bool cmQtAutoGenerators::UicGenerateFile(const std::string& realName,
  1448. const std::string& uiInputFile,
  1449. const std::string& uiOutputFile)
  1450. {
  1451. bool uicGenerated = false;
  1452. bool generateUic = this->UicSettingsChanged;
  1453. const std::string uicFileRel = this->AutogenIncludeDir + uiOutputFile;
  1454. const std::string uicFileAbs =
  1455. cmSystemTools::CollapseCombinedPath(this->AutogenBuildDir, uicFileRel);
  1456. if (!generateUic) {
  1457. // Test if the source file is newer that the build file
  1458. generateUic = FileAbsentOrOlder(uicFileAbs, uiInputFile);
  1459. }
  1460. if (generateUic) {
  1461. // Log
  1462. if (this->Verbose) {
  1463. this->LogBold("Generating UIC header " + uicFileRel);
  1464. }
  1465. // Make sure the parent directory exists
  1466. if (this->MakeParentDirectory(cmQtAutoGen::UIC, uicFileAbs)) {
  1467. // Compose uic command
  1468. std::vector<std::string> cmd;
  1469. cmd.push_back(this->UicExecutable);
  1470. {
  1471. std::vector<std::string> allOpts = this->UicTargetOptions;
  1472. std::map<std::string, std::string>::const_iterator optionIt =
  1473. this->UicOptions.find(uiInputFile);
  1474. if (optionIt != this->UicOptions.end()) {
  1475. std::vector<std::string> fileOpts;
  1476. cmSystemTools::ExpandListArgument(optionIt->second, fileOpts);
  1477. UicMergeOptions(allOpts, fileOpts, (this->QtMajorVersion == "5"));
  1478. }
  1479. cmd.insert(cmd.end(), allOpts.begin(), allOpts.end());
  1480. }
  1481. cmd.push_back("-o");
  1482. cmd.push_back(uicFileAbs);
  1483. cmd.push_back(uiInputFile);
  1484. std::string output;
  1485. if (this->RunCommand(cmd, output)) {
  1486. // Success
  1487. uicGenerated = true;
  1488. } else {
  1489. // Command failed
  1490. {
  1491. std::ostringstream ost;
  1492. ost << "AutoUic: Error: uic process failed for\n";
  1493. ost << Quoted(uicFileRel) << " needed by\n";
  1494. ost << Quoted(realName) << "\n";
  1495. ost << "AutoUic: Command:\n" << QuotedCommand(cmd) << "\n";
  1496. ost << "AutoUic: Command output:\n" << output << "\n";
  1497. this->LogError(ost.str());
  1498. }
  1499. cmSystemTools::RemoveFile(uicFileAbs);
  1500. this->UicRunFailed = true;
  1501. }
  1502. } else {
  1503. // Parent directory creation failed
  1504. this->UicRunFailed = true;
  1505. }
  1506. }
  1507. return uicGenerated;
  1508. }
  1509. bool cmQtAutoGenerators::RccGenerateAll()
  1510. {
  1511. if (!this->RccEnabled()) {
  1512. return true;
  1513. }
  1514. // generate single map with input / output names
  1515. std::map<std::string, std::string> qrcGenMap;
  1516. {
  1517. const std::string qrcPrefix = "qrc_";
  1518. const std::string qrcSuffix = this->ConfigSuffix + ".cpp";
  1519. for (const std::string& src : this->RccSources) {
  1520. qrcGenMap[src] = this->ChecksumedPath(src, qrcPrefix, qrcSuffix);
  1521. }
  1522. }
  1523. // look for name collisions
  1524. {
  1525. std::multimap<std::string, std::string> collisions;
  1526. if (this->NameCollisionTest(qrcGenMap, collisions)) {
  1527. std::ostringstream ost;
  1528. ost << "AutoRcc: Error: The same qrc_NAME.cpp file"
  1529. " will be generated from different sources.\n"
  1530. "To avoid this error rename the source .qrc files.\n";
  1531. this->LogErrorNameCollision(ost.str(), collisions);
  1532. return false;
  1533. }
  1534. }
  1535. // generate qrc files
  1536. for (const auto& item : qrcGenMap) {
  1537. bool unique = FileNameIsUnique(item.first, qrcGenMap);
  1538. if (!this->RccGenerateFile(item.first, item.second, unique)) {
  1539. if (this->RccRunFailed) {
  1540. return false;
  1541. }
  1542. }
  1543. }
  1544. return true;
  1545. }
  1546. /**
  1547. * @return True if a rcc file was created. False may indicate an error.
  1548. */
  1549. bool cmQtAutoGenerators::RccGenerateFile(const std::string& rccInputFile,
  1550. const std::string& rccOutputFile,
  1551. bool unique_n)
  1552. {
  1553. bool rccGenerated = false;
  1554. bool generateRcc = this->RccSettingsChanged;
  1555. const std::string rccBuildFile =
  1556. cmSystemTools::CollapseCombinedPath(this->AutogenBuildDir, rccOutputFile);
  1557. // Check if regeneration is required
  1558. if (!generateRcc) {
  1559. // Test if the resources list file is newer than build file
  1560. generateRcc = FileAbsentOrOlder(rccBuildFile, rccInputFile);
  1561. if (!generateRcc) {
  1562. // Acquire input file list
  1563. std::vector<std::string> readFiles;
  1564. const std::vector<std::string>* files = &this->RccInputs[rccInputFile];
  1565. if (files->empty()) {
  1566. // Read input file list from qrc file
  1567. std::string error;
  1568. if (cmQtAutoGen::RccListInputs(this->QtMajorVersion,
  1569. this->RccExecutable, rccInputFile,
  1570. readFiles, &error)) {
  1571. files = &readFiles;
  1572. } else {
  1573. files = nullptr;
  1574. this->LogError(error);
  1575. this->RccRunFailed = true;
  1576. }
  1577. }
  1578. // Test if any input file is newer than the build file
  1579. if (files != nullptr) {
  1580. for (const std::string& file : *files) {
  1581. if (FileAbsentOrOlder(rccBuildFile, file)) {
  1582. generateRcc = true;
  1583. break;
  1584. }
  1585. }
  1586. }
  1587. }
  1588. }
  1589. // Regenerate on demand
  1590. if (generateRcc) {
  1591. // Log
  1592. if (this->Verbose) {
  1593. this->LogBold("Generating RCC source " + rccOutputFile);
  1594. }
  1595. // Make sure the parent directory exists
  1596. if (this->MakeParentDirectory(cmQtAutoGen::RCC, rccBuildFile)) {
  1597. // Compose symbol name
  1598. std::string symbolName =
  1599. cmsys::SystemTools::GetFilenameWithoutLastExtension(rccInputFile);
  1600. if (!unique_n) {
  1601. symbolName += "_";
  1602. symbolName += FPathChecksum.getPart(rccInputFile);
  1603. }
  1604. // Replace '-' with '_'. The former is valid for
  1605. // file names but not for symbol names.
  1606. std::replace(symbolName.begin(), symbolName.end(), '-', '_');
  1607. // Compose rcc command
  1608. std::vector<std::string> cmd;
  1609. cmd.push_back(this->RccExecutable);
  1610. {
  1611. std::map<std::string, std::string>::const_iterator optionIt =
  1612. this->RccOptions.find(rccInputFile);
  1613. if (optionIt != this->RccOptions.end()) {
  1614. cmSystemTools::ExpandListArgument(optionIt->second, cmd);
  1615. }
  1616. }
  1617. cmd.push_back("-name");
  1618. cmd.push_back(symbolName);
  1619. cmd.push_back("-o");
  1620. cmd.push_back(rccBuildFile);
  1621. cmd.push_back(rccInputFile);
  1622. std::string output;
  1623. if (this->RunCommand(cmd, output)) {
  1624. // Success
  1625. rccGenerated = true;
  1626. } else {
  1627. // Command failed
  1628. {
  1629. std::ostringstream ost;
  1630. ost << "AutoRcc: Error: rcc process failed for\n";
  1631. ost << Quoted(rccOutputFile) << "\n";
  1632. ost << "AutoRcc: Command:\n" << QuotedCommand(cmd) << "\n";
  1633. ost << "AutoRcc: Command output:\n" << output << "\n";
  1634. this->LogError(ost.str());
  1635. }
  1636. cmSystemTools::RemoveFile(rccBuildFile);
  1637. this->RccRunFailed = true;
  1638. }
  1639. } else {
  1640. // Parent directory creation failed
  1641. this->RccRunFailed = true;
  1642. }
  1643. }
  1644. // For a multi configuration generator generate a wrapper file
  1645. if (!this->ConfigSuffix.empty() && !this->RccRunFailed) {
  1646. // Wrapper file name
  1647. const std::string cppSuffix = ".cpp";
  1648. const size_t suffixLength = this->ConfigSuffix.size() + cppSuffix.size();
  1649. const std::string wrapperFileRel =
  1650. rccOutputFile.substr(0, rccOutputFile.size() - suffixLength) + cppSuffix;
  1651. const std::string wrapperFileAbs = cmSystemTools::CollapseCombinedPath(
  1652. this->AutogenBuildDir, wrapperFileRel);
  1653. // Wrapper file content
  1654. std::string content =
  1655. "// This is an autogenerated configuration wrapper file. Do not edit.\n"
  1656. "#include \"";
  1657. content += cmsys::SystemTools::GetFilenameName(rccBuildFile);
  1658. content += "\"\n";
  1659. // Write content to file
  1660. if (this->FileDiffers(wrapperFileAbs, content)) {
  1661. // Write new wrapper file if the content differs
  1662. if (this->Verbose) {
  1663. this->LogBold("Generating RCC wrapper " + wrapperFileRel);
  1664. }
  1665. if (!this->FileWrite(cmQtAutoGen::RCC, wrapperFileAbs, content)) {
  1666. // Error
  1667. rccGenerated = false;
  1668. this->RccRunFailed = true;
  1669. }
  1670. } else if (rccGenerated) {
  1671. // Only touch wrapper file if the content matches
  1672. if (this->Verbose) {
  1673. this->LogInfo("Touching RCC wrapper " + wrapperFileRel);
  1674. }
  1675. cmSystemTools::Touch(wrapperFileAbs, false);
  1676. }
  1677. }
  1678. return rccGenerated;
  1679. }
  1680. void cmQtAutoGenerators::LogErrorNameCollision(
  1681. const std::string& message,
  1682. const std::multimap<std::string, std::string>& collisions) const
  1683. {
  1684. std::ostringstream ost;
  1685. // Add message
  1686. if (!message.empty()) {
  1687. ost << message;
  1688. if (message[message.size() - 1] != '\n') {
  1689. ost << '\n';
  1690. }
  1691. }
  1692. // Append collision list
  1693. for (const auto& item : collisions) {
  1694. ost << " " << item.first << " : " << item.second << '\n';
  1695. }
  1696. this->LogError(ost.str());
  1697. }
  1698. void cmQtAutoGenerators::LogBold(const std::string& message) const
  1699. {
  1700. cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundBlue |
  1701. cmsysTerminal_Color_ForegroundBold,
  1702. message.c_str(), true, this->ColorOutput);
  1703. }
  1704. void cmQtAutoGenerators::LogInfo(const std::string& message) const
  1705. {
  1706. std::string msg(message);
  1707. if (!msg.empty()) {
  1708. if (msg[msg.size() - 1] != '\n') {
  1709. msg.push_back('\n');
  1710. }
  1711. cmSystemTools::Stdout(msg.c_str(), msg.size());
  1712. }
  1713. }
  1714. void cmQtAutoGenerators::LogWarning(const std::string& message) const
  1715. {
  1716. std::string msg(message);
  1717. if (!msg.empty()) {
  1718. if (msg[msg.size() - 1] != '\n') {
  1719. msg.push_back('\n');
  1720. }
  1721. // Append empty line
  1722. msg.push_back('\n');
  1723. cmSystemTools::Stdout(msg.c_str(), msg.size());
  1724. }
  1725. }
  1726. void cmQtAutoGenerators::LogError(const std::string& message) const
  1727. {
  1728. std::string msg(message);
  1729. if (!msg.empty()) {
  1730. if (msg[msg.size() - 1] != '\n') {
  1731. msg.push_back('\n');
  1732. }
  1733. // Append empty line
  1734. msg.push_back('\n');
  1735. cmSystemTools::Stderr(msg.c_str(), msg.size());
  1736. }
  1737. }
  1738. /**
  1739. * @brief Collects name collisions as output/input pairs
  1740. * @return True if there were collisions
  1741. */
  1742. bool cmQtAutoGenerators::NameCollisionTest(
  1743. const std::map<std::string, std::string>& genFiles,
  1744. std::multimap<std::string, std::string>& collisions) const
  1745. {
  1746. typedef std::map<std::string, std::string>::const_iterator Iter;
  1747. typedef std::map<std::string, std::string>::value_type VType;
  1748. for (Iter ait = genFiles.begin(); ait != genFiles.end(); ++ait) {
  1749. bool first_match(true);
  1750. for (Iter bit = (++Iter(ait)); bit != genFiles.end(); ++bit) {
  1751. if (ait->second == bit->second) {
  1752. if (first_match) {
  1753. if (collisions.find(ait->second) != collisions.end()) {
  1754. // We already know of this collision from before
  1755. break;
  1756. }
  1757. collisions.insert(VType(ait->second, ait->first));
  1758. first_match = false;
  1759. }
  1760. collisions.insert(VType(bit->second, bit->first));
  1761. }
  1762. }
  1763. }
  1764. return !collisions.empty();
  1765. }
  1766. /**
  1767. * @brief Generates a file path based on the checksum of the source file path
  1768. * @return The path
  1769. */
  1770. std::string cmQtAutoGenerators::ChecksumedPath(
  1771. const std::string& sourceFile, const std::string& basePrefix,
  1772. const std::string& baseSuffix) const
  1773. {
  1774. std::string res = FPathChecksum.getPart(sourceFile);
  1775. res += "/";
  1776. res += basePrefix;
  1777. res += cmsys::SystemTools::GetFilenameWithoutLastExtension(sourceFile);
  1778. res += baseSuffix;
  1779. return res;
  1780. }
  1781. /**
  1782. * @brief Generates the parent directory of the given file on demand
  1783. * @return True on success
  1784. */
  1785. bool cmQtAutoGenerators::MakeParentDirectory(
  1786. cmQtAutoGen::GeneratorType genType, const std::string& filename) const
  1787. {
  1788. bool success = true;
  1789. const std::string dirName = cmSystemTools::GetFilenamePath(filename);
  1790. if (!dirName.empty()) {
  1791. success = cmsys::SystemTools::MakeDirectory(dirName);
  1792. if (!success) {
  1793. std::string error = cmQtAutoGen::GeneratorName(genType);
  1794. error += ": Error: Parent directory creation failed for ";
  1795. error += Quoted(filename);
  1796. this->LogError(error);
  1797. }
  1798. }
  1799. return success;
  1800. }
  1801. bool cmQtAutoGenerators::FileDiffers(const std::string& filename,
  1802. const std::string& content)
  1803. {
  1804. bool differs = true;
  1805. {
  1806. std::string oldContents;
  1807. if (ReadAll(oldContents, filename)) {
  1808. differs = (oldContents != content);
  1809. }
  1810. }
  1811. return differs;
  1812. }
  1813. bool cmQtAutoGenerators::FileWrite(cmQtAutoGen::GeneratorType genType,
  1814. const std::string& filename,
  1815. const std::string& content)
  1816. {
  1817. std::string error;
  1818. // Make sure the parent directory exists
  1819. if (this->MakeParentDirectory(genType, filename)) {
  1820. cmsys::ofstream outfile;
  1821. outfile.open(filename.c_str(), std::ios::trunc);
  1822. if (outfile) {
  1823. outfile << content;
  1824. // Check for write errors
  1825. if (!outfile.good()) {
  1826. error = cmQtAutoGen::GeneratorName(genType);
  1827. error += ": Error: File writing failed\n";
  1828. error += " ";
  1829. error += Quoted(filename);
  1830. }
  1831. } else {
  1832. error = cmQtAutoGen::GeneratorName(genType);
  1833. error += ": Error: Opening file for writing failed\n";
  1834. error += " ";
  1835. error += Quoted(filename);
  1836. }
  1837. }
  1838. if (!error.empty()) {
  1839. this->LogError(error);
  1840. return false;
  1841. }
  1842. return true;
  1843. }
  1844. /**
  1845. * @brief Runs a command and returns true on success
  1846. * @return True on success
  1847. */
  1848. bool cmQtAutoGenerators::RunCommand(const std::vector<std::string>& command,
  1849. std::string& output, bool verbose) const
  1850. {
  1851. // Log command
  1852. if (this->Verbose) {
  1853. this->LogInfo(QuotedCommand(command));
  1854. }
  1855. // Execute command
  1856. int retVal = 0;
  1857. bool res = cmSystemTools::RunSingleCommand(
  1858. command, &output, &output, &retVal, nullptr,
  1859. verbose ? cmSystemTools::OUTPUT_MERGE : cmSystemTools::OUTPUT_NONE);
  1860. return (res && (retVal == 0));
  1861. }
  1862. /**
  1863. * @brief Tries to find the header file to the given file base path by
  1864. * appending different header extensions
  1865. * @return True on success
  1866. */
  1867. bool cmQtAutoGenerators::FindHeader(std::string& header,
  1868. const std::string& testBasePath) const
  1869. {
  1870. for (const std::string& ext : this->HeaderExtensions) {
  1871. std::string testFilePath(testBasePath);
  1872. testFilePath.push_back('.');
  1873. testFilePath += ext;
  1874. if (cmsys::SystemTools::FileExists(testFilePath.c_str())) {
  1875. header = testFilePath;
  1876. return true;
  1877. }
  1878. }
  1879. return false;
  1880. }
  1881. std::string cmQtAutoGenerators::MocFindHeader(
  1882. const std::string& sourcePath, const std::string& includeBase) const
  1883. {
  1884. std::string header;
  1885. // Search in vicinity of the source
  1886. if (!this->FindHeader(header, sourcePath + includeBase)) {
  1887. // Search in include directories
  1888. for (const std::string& path : this->MocIncludePaths) {
  1889. std::string fullPath = path;
  1890. fullPath.push_back('/');
  1891. fullPath += includeBase;
  1892. if (FindHeader(header, fullPath)) {
  1893. break;
  1894. }
  1895. }
  1896. }
  1897. // Sanitize
  1898. if (!header.empty()) {
  1899. header = cmsys::SystemTools::GetRealPath(header);
  1900. }
  1901. return header;
  1902. }
  1903. bool cmQtAutoGenerators::MocFindIncludedFile(
  1904. std::string& absFile, const std::string& sourcePath,
  1905. const std::string& includeString) const
  1906. {
  1907. bool success = false;
  1908. // Search in vicinity of the source
  1909. {
  1910. std::string testPath = sourcePath;
  1911. testPath += includeString;
  1912. if (cmsys::SystemTools::FileExists(testPath.c_str())) {
  1913. absFile = cmsys::SystemTools::GetRealPath(testPath);
  1914. success = true;
  1915. }
  1916. }
  1917. // Search in include directories
  1918. if (!success) {
  1919. for (const std::string& path : this->MocIncludePaths) {
  1920. std::string fullPath = path;
  1921. fullPath.push_back('/');
  1922. fullPath += includeString;
  1923. if (cmsys::SystemTools::FileExists(fullPath.c_str())) {
  1924. absFile = cmsys::SystemTools::GetRealPath(fullPath);
  1925. success = true;
  1926. break;
  1927. }
  1928. }
  1929. }
  1930. return success;
  1931. }