cmQtAutoGenerators.cxx 66 KB

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